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
Block compile: install the router_logits capture hooks before the first block compiles (#16410)
Daniel Han5a1a5226e6c9
diff --git a/tests/test_block_compile.py b/tests/test_block_compile.pyindex dbafb428e1b..64ba540209d 100644--- a/tests/test_block_compile.py+++ b/tests/test_block_compile.py@@ -1541,6 +1541,68 @@ def test_zero3_partitioned_training_keeps_the_stock_forward(monkeypatch):assert calls+def test_router_logits_after_a_forward_without_them(request, monkeypatch):+ """transformers installs the router_logits hooks on the first forward that asks for them.++ Dynamo does not guard on module hooks (skip_nnmodule_hook_guards), so a block compiled during an+ earlier forward without output_router_logits kept running without the gate hook: no router logits,+ and the aux loss raised IndexError in load_balancing_loss_func. The hooks now exist before the+ first block compiles, and the hook body (guarded on the collector keys) decides per call.+ """+ misc = pytest.importorskip("unsloth_zoo.temporary_patches.misc")+ if not hasattr(misc, "output_capture_scratch"):+ pytest.skip("needs an unsloth_zoo with output_capture_scratch (unsloth-zoo#2041)")+ misc.patch_output_collector_for_compiled_submodules()+ M = _load()+ torch.manual_seed(0)+ model = _tiny_qwen3_moe(request, monkeypatch)+ ids = torch.randint(0, 100, (2, 8))+ want = model(input_ids = ids, labels = ids, use_cache = False, output_router_logits = True)+ model = (+ type(model)+ .from_pretrained(+ "trl-internal-testing/tiny-Qwen3MoeForCausalLM",+ dtype = torch.float32,+ experts_implementation = "batched_mm",+ )+ .train()+ )+ monkeypatch.setattr(M, "_lora_would_fold", lambda experts: False)+ inner = _install_blocks(M, model, monkeypatch)+ torch._dynamo.reset()+ model(input_ids = ids, labels = ids, use_cache = False).loss.backward()+ out = model(input_ids = ids, labels = ids, use_cache = False, output_router_logits = True)+ out.loss.backward()+ assert inner, "the blocks did not run compiled"+ assert len(out.router_logits) == len(want.router_logits) == model.config.num_hidden_layers+ torch.testing.assert_close(out.aux_loss.detach(), want.aux_loss.detach())+ torch.testing.assert_close(out.loss.detach(), want.loss.detach())+ torch._dynamo.reset()+++def test_router_hooks_are_not_installed_twice_after_an_eager_capture(request, monkeypatch):+ """Failing before: an eager capturing forward hooks the inner model; installing on the unflagged outer+ CausalLM recursed into it again and every captured tuple held each layer twice."""+ misc = pytest.importorskip("unsloth_zoo.temporary_patches.misc")+ if not hasattr(misc, "output_capture_scratch"):+ pytest.skip("needs an unsloth_zoo with output_capture_scratch (unsloth-zoo#2041)")+ misc.patch_output_collector_for_compiled_submodules()+ M = _load()+ torch.manual_seed(0)+ model = _tiny_qwen3_moe(request, monkeypatch).train()+ ids = torch.randint(0, 100, (2, 8))+ kwargs = dict(use_cache = False, output_router_logits = True, output_hidden_states = True)+ model(input_ids = ids, **kwargs)+ monkeypatch.setattr(M, "_lora_would_fold", lambda experts: False)+ _install_blocks(M, model, monkeypatch)+ torch._dynamo.reset()+ out = model(input_ids = ids, **kwargs)+ layers = model.config.num_hidden_layers+ assert len(out.router_logits) == layers, len(out.router_logits)+ assert len(out.hidden_states) == layers + 1, len(out.hidden_states)+ torch._dynamo.reset()++def test_router_logits_capture_compiles_one_graph_for_every_layer(monkeypatch):"""A capture hook inside the block appends to an empty scratch list on every call.diff --git a/unsloth/models/_block_compile.py b/unsloth/models/_block_compile.pyindex f696490ee85..2242911aa29 100644--- a/unsloth/models/_block_compile.py+++ b/unsloth/models/_block_compile.py@@ -1852,6 +1852,47 @@ def _raise_cache_limit(kinds):setattr(config, name, need)+def _install_router_capture_hooks(model):+ """Install transformers' output capture hooks before any block compiles, for models that record+ router_logits.++ transformers installs them on the first forward that asks for an output (output_router_logits),+ and Dynamo does not guard on module hooks (skip_nnmodule_hook_guards). A block compiled during an+ earlier forward without them kept running without the router hook: no router logits, and the+ aux loss raised IndexError. Installed up front, the hook body runs on every call and returns+ early unless the collector asks for its key (a guarded dict lookup). Needs the zoo collector+ mirror: the stock ContextVar.get graph-breaks every compiled block."""+ try:+ from transformers.utils import output_capturing+ except Exception:+ return 0+ registry = getattr(output_capturing, "_CAN_RECORD_REGISTRY", None)+ install = getattr(output_capturing, "maybe_install_capturing_hooks", None)+ collector = getattr(output_capturing, "CompileableContextVar", None)+ if (+ not isinstance(registry, dict)+ or install is None+ or not getattr(collector, "_unsloth_eager_mirror", False)+ ):+ return 0+ installed = 0+ # Outermost first, as transformers would: an install recurses into nested models and flags them. Its+ # recursion does not check that flag, so a module with an already hooked descendant (an earlier eager+ # capturing forward) is skipped: installing it would hook that descendant twice (duplicated outputs).+ for module in model.modules():+ flags = registry.get(str(type(module))) or {}+ if "router_logits" not in flags or any(+ getattr(m, "_output_capturing_hooks_installed", False) for m in module.modules()+ ):+ continue+ try:+ install(module)+ installed += 1+ except Exception:+ pass+ return installed++def patch_block_compile(model):"""Compile every decoder-layer class of `model` as one region. Returns the classes wrapped."""# getattr: PeftModel delegates. The env fills only unstamped layers, so a re-patch keeps the stamp.@@ -1892,6 +1933,7 @@ def patch_block_compile(model):layer.__dict__["_unsloth_block_moe_may_move"] = Trueif not classes:return []+ _install_router_capture_hooks(model)inner = {type(m) for layer in compiled_layers for m in layer.modules()}for cls in inner:_rebind_class(cls)