Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Stop the empty-logits sentinel from claiming protocol dunders it cannot honour (#11130)
Daniel Han3efb3b81a884
diff --git a/pyproject.toml b/pyproject.tomlindex 2c75d45a451..c59e38c9a86 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -191,6 +191,16 @@ triton = []huggingfacenotorch = [+ # unsloth_zoo.compiler embeds its own copy of the empty-logits sentinel in the code it+ # generates for the compiled trainers, so fixing _utils.py here does not reach the+ # compiled path while an older zoo is resolvable: 2026.9.4, the newest on PyPI, still+ # hands FSDP2 mixed precision a sentinel that answers `__dataclass_fields__` and dies in+ # `dataclasses.replace`. The release carrying the matching fix+ # (unslothai/unsloth-zoo#1259) is not published yet, and a floor no release satisfies+ # makes the package uninstallable, so the floor stays at 2026.9.4 for now and the+ # eager-path fix below stands on its own. Raise the floor once #1259 ships; the+ # compiled-path probes in tests/test_empty_logits_compiled_path_probes.py gate on the+ # INSTALLED zoo, not on this pin, so they start running on their own."unsloth_zoo>=2026.9.4","wheel>=0.42.0","packaging",diff --git a/tests/test_empty_logits_compiled_path_probes.py b/tests/test_empty_logits_compiled_path_probes.pynew file mode 100644index 00000000000..c2a35512af6--- /dev/null+++ b/tests/test_empty_logits_compiled_path_probes.py@@ -0,0 +1,159 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""unsloth#409, compiled path: unsloth_zoo.compiler generates its OWN empty-logits sentinel.++`unsloth_compile_transformers()` hands the trainers source text built from+`compiler._cross_entropy_code`, which carries a second `EmptyLogits` that never goes through+`unsloth/models/_utils.py`. Fixing the singleton there leaves that copy claiming+`__dataclass_fields__`, so torch's `_apply_to_tensors` (the FSDP2 mixed-precision output cast)+still calls `dataclasses.replace` on it and dies. The generated text is read off the installed+zoo and exec'd, because the module is never importable without an accelerator.+"""++from __future__ import annotations++import ast+import importlib.util+from pathlib import Path++import pytest+import torch+from packaging.version import Version+from torch.distributed.utils import _apply_to_tensors+++# Not tensor dunders: the loop after the class binds those as real instance attributes, so+# only names outside `dir(torch.Tensor)` ever reach `__getattr__`.+PROTOCOL_DUNDERS = (+ "__dataclass_fields__",+ "__fields__",+ "__attrs_attrs__",+ "__get_validators__",+ "__pydantic_fields__",+ "__dataclass_params__",+)++# The sentinel exactly as unsloth_zoo 2026.9.4 generated it, kept verbatim so the probes below+# are shown to have teeth on every machine, whatever zoo happens to be installed.+PRE_FIX_SENTINEL_SOURCE = """+LOGITS_ERROR_STRING = "Unsloth: Logits are empty, set UNSLOTH_RETURN_LOGITS"+def raise_logits_error(*args, **kwargs): raise NotImplementedError(LOGITS_ERROR_STRING)+def return_none(*args, **kwargs): return None+class EmptyLogits:+ def __init__(self): return+ def raise_getattr_error(self, attr): return return_none if attr == "to" else raise_logits_error+ __getitem__ = raise_logits_error+ __getattr__ = raise_getattr_error+ def __repr__(self): return LOGITS_ERROR_STRING+ def __str__ (self): return LOGITS_ERROR_STRING+ def __reduce__(self): return (type(self), ())+ def __eq__(self, other): return type(other).__name__ == "EmptyLogits"+ __hash__ = object.__hash__+"""+++# The first unsloth_zoo release expected to generate a fixed sentinel, i.e. the one that+# carries unslothai/unsloth-zoo#1259. Not yet published: 2026.9.4 is the newest on PyPI.+#+# This deliberately does NOT read the `unsloth_zoo>=` floor out of pyproject.toml, which is+# what it used to do. That coupling was only correct while the pin and the fix named the+# same release. The pin is now held at 2026.9.4 because a floor no release satisfies makes+# unsloth uninstallable, and 2026.9.4 is exactly the zoo that still generates the BROKEN+# sentinel -- so a gate reading the pin would let these probes run against a zoo that has+# the bug, and they would fail on a correct tree. What the probes assert is a property of+# the INSTALLED zoo, so the gate names the release that fixes it, directly.+#+# Until that release exists, every probe below skips and the always-on canary at the bottom+# of this file is what keeps the assertions honest. Move this constant when #1259 ships.+ZOO_RELEASE_WITH_GENERATED_SENTINEL_FIX = Version("2026.9.5")+++def _installed_zoo() -> tuple[Path, Version]:+ spec = importlib.util.find_spec("unsloth_zoo") # locates without importing: no GPU needed+ if spec is None or not spec.submodule_search_locations:+ pytest.skip("unsloth_zoo is not installed")+ compiler = Path(spec.submodule_search_locations[0]) / "compiler.py"+ if not compiler.is_file():+ pytest.skip(f"unsloth_zoo carries no compiler.py at {compiler}")+ from importlib.metadata import PackageNotFoundError, version++ try:+ return compiler, Version(version("unsloth_zoo"))+ except PackageNotFoundError:+ pytest.skip("unsloth_zoo has no installed distribution metadata to version-gate on")+++def _generated_sentinel_source(compiler: Path) -> str:+ """The sentinel slice of `_cross_entropy_code`, pulled out of the file as text."""+ module = ast.parse(compiler.read_text())+ for node in module.body:+ if isinstance(node, ast.Assign) and any(+ getattr(target, "id", None) == "_cross_entropy_code" for target in node.targets+ ):+ code = ast.literal_eval(node.value)+ break+ else:+ pytest.fail(+ f"{compiler} defines no module-level `_cross_entropy_code`; the compiled trainers "+ f"are built from somewhere else now and this probe is aimed at nothing"+ )+ start = code.index("LOGITS_ERROR_STRING")+ end = code.index("EMPTY_LOGITS = EmptyLogits()")+ return code[start:end]+++def _build(source: str):+ namespace: dict = {"torch": torch}+ exec(compile(source, "<unsloth_zoo _cross_entropy_code>", "exec"), namespace)+ return namespace["EmptyLogits"]()++[email protected](scope = "module")+def generated_sentinel():+ compiler, installed = _installed_zoo()+ if installed < ZOO_RELEASE_WITH_GENERATED_SENTINEL_FIX:+ pytest.skip(+ f"installed unsloth_zoo {installed} still generates the pre-fix sentinel; it is "+ f"fixed from {ZOO_RELEASE_WITH_GENERATED_SENTINEL_FIX} "+ f"(unslothai/unsloth-zoo#1259) onwards, which is not published yet. The "+ f"canary test in this file runs unconditionally and shows these probes have "+ f"teeth."+ )+ return _build(_generated_sentinel_source(compiler))++[email protected]("name", PROTOCOL_DUNDERS)+def test_the_generated_sentinel_does_not_claim_a_protocol_dunder(generated_sentinel, name):+ assert not hasattr(generated_sentinel, name), (+ f"the sentinel unsloth_zoo.compiler generates answers hasattr({name!r}); a library that "+ f"duck-types on it takes a branch the sentinel cannot honour"+ )+++def test_the_fsdp2_output_cast_leaves_the_generated_sentinel_alone(generated_sentinel):+ """`_apply_to_tensors` is what FSDP2 mixed precision runs over every forward's outputs."""+ outputs = {"loss": torch.tensor(1.0), "logits": generated_sentinel}+ cast = _apply_to_tensors(lambda tensor: tensor.to(torch.bfloat16), outputs)+ assert cast["loss"].dtype is torch.bfloat16+ assert cast["logits"] is generated_sentinel+++def test_the_generated_sentinel_still_absorbs_the_to_call(generated_sentinel):+ """accelerate calls `.to(device)` on outputs, so `to` stays special-cased ahead of the guard."""+ assert generated_sentinel.to("cpu") is None+++def test_an_ordinary_attribute_on_the_generated_sentinel_still_explains_itself(generated_sentinel):+ with pytest.raises(NotImplementedError) as excinfo:+ generated_sentinel.shape()+ assert "UNSLOTH_RETURN_LOGITS" in str(excinfo.value)+++def test_these_probes_fail_on_the_sentinel_zoo_used_to_generate():+ """Mutation control: the pre-fix copy must trip both probes, so a skip above is the only+ way they stay quiet. Without this, a zoo that stopped shipping the fix would look green."""+ stale = _build(PRE_FIX_SENTINEL_SOURCE)+ assert hasattr(stale, "__dataclass_fields__")+ with pytest.raises(TypeError, match = "replace"):+ _apply_to_tensors(lambda tensor: tensor, {"logits": stale})diff --git a/tests/test_empty_logits_protocol_probes.py b/tests/test_empty_logits_protocol_probes.pynew file mode 100644index 00000000000..2ebfd82c58c--- /dev/null+++ b/tests/test_empty_logits_protocol_probes.py@@ -0,0 +1,60 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""unsloth#409: EMPTY_LOGITS must not answer hasattr for protocol dunders it cannot honour."""++from __future__ import annotations++import dataclasses++import pytest++from unsloth.models._utils import EMPTY_LOGITS, LOGITS_ERROR_STRING+++# No tensor dunders: the loop under EMPTY_LOGITS binds those as real instance+# attributes, so only these ever reach `__getattr__`.+PROTOCOL_DUNDERS = (+ "__dataclass_fields__",+ "__fields__",+ "__attrs_attrs__",+ "__get_validators__",+ "__pydantic_fields__",+ "__dataclass_params__",+)++[email protected]("name", PROTOCOL_DUNDERS)+def test_the_sentinel_does_not_claim_a_protocol_dunder(name):+ assert not hasattr(EMPTY_LOGITS, name), (+ f"EMPTY_LOGITS answers hasattr({name!r}); a library that duck-types on it "+ f"will take a branch the sentinel cannot honour"+ )+++def test_the_torch_distributed_output_walk_leaves_the_sentinel_alone():+ """The exact probe `_apply_to_tensors` makes, and the call it makes next."""+ assert not hasattr(EMPTY_LOGITS, "__dataclass_fields__")+ with pytest.raises(TypeError):+ dataclasses.replace(EMPTY_LOGITS)+++def test_an_ordinary_attribute_still_explains_how_to_get_real_logits():+ """Dunders only: a tensor attribute must still name UNSLOTH_RETURN_LOGITS, not `AttributeError: shape`."""+ raiser = EMPTY_LOGITS.shape+ with pytest.raises(NotImplementedError) as excinfo:+ raiser()+ assert "UNSLOTH_RETURN_LOGITS" in str(excinfo.value)+ assert LOGITS_ERROR_STRING in str(excinfo.value)+++def test_to_is_still_the_no_op_accelerate_needs():+ """accelerate calls `.to(device)` on model outputs, so it is special-cased ahead of the dunder check."""+ assert EMPTY_LOGITS.to("cpu") is None+++def test_dunder_names_the_class_really_defines_are_untouched():+ """`__getattr__` runs only after normal lookup fails, so what the class defines is reached as before."""+ assert EMPTY_LOGITS == EMPTY_LOGITS+ assert repr(EMPTY_LOGITS) == LOGITS_ERROR_STRING+ assert EMPTY_LOGITS.__reduce__() == (type(EMPTY_LOGITS), ())diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex b2cfc09d79f..65e7a6b894c 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -3502,7 +3502,13 @@ class EmptyLogits:returndef raise_getattr_error(self, attr):- return return_none if attr == "to" else raise_logits_error+ if attr == "to":+ return return_none+ # unsloth#409: a catch-all __getattr__ answers hasattr() for every name, so FSDP2's+ # output cast saw __dataclass_fields__ and called dataclasses.replace() on the sentinel.+ if len(attr) > 4 and attr.startswith("__") and attr.endswith("__"):+ raise AttributeError(f"{type(self).__name__!r} object has no attribute {attr!r}")+ return raise_logits_error__getitem__ = raise_logits_error__getattr__ = raise_getattr_error