Repository navigation
Block compile on transformers 5.23: router logit hooks, GDN op with grouped value heads, int4 LoRA without graph breaks - #17829
Conversation
…23 too transformers 5.23 (huggingface/transformers#49594) turned _CAN_RECORD_REGISTRY into a dict subclass whose .get takes the model and stringifies its class itself. _install_router_capture_hooks passed the class string, so every lookup answered {} and no hook was installed before the first block compiled: a forward with output_router_logits after one without returned no router logits and the aux loss raised IndexError (test_router_logits_after_a_forward_without_them). Read the string keys with dict.get, which both registry versions store.
…DN test before transformers 5.2 test_old_torch_installs_nothing checks the #10744 claim at the patch level (no class wrapped, nothing compiled, then 2.7 wraps). test_qwen3_5_gdn_block_has_no_break failed with ModuleNotFoundError on transformers 4.57 instead of skipping.
…formers 5.23) transformers 5.23 (huggingface/transformers#49141) stopped repeating the gated DeltaNet query / key heads up to the value heads before fla's chunk kernel. The opaque op's fake meta gave A (chunk_scaled_dot_kkt, one per value head) the q / k head count, so Inductor's output check failed on the first compiled call and every linear-attention layer with num_v_heads > num_k_heads (Qwen3.5-MoE, Qwen3.6, Qwen3.8-Flash-Next) fell back to the stock forward. A now takes v's heads, the self-check runs on the unrepeated q / k layout, and the Qwen3.5 GDN test asserts the block actually compiled (a demoted layer also has no graph break).
…nsformers < 5.15) The transformers < 5.15 GatedDeltaNet (Qwen3-Next) binds self.causal_conv1d_fn at init and calls it as (x = ..., weight = ..., bias = ..., activation = ..., seq_idx = None). The block adapter required hidden_states, so a Qwen3-Next model created after the first block forward raised TypeError on transformers 4.57. Arguments now pass through to the original exactly as given.
…piled blocks PEFT's LoRA forward reads base_layer.weight inside Unsloth's per-layer compiled block, under the gradient checkpoint's higher-order op. The property read the packed parameter's __dict__, which Dynamo cannot put in that subgraph, so every LoRA layer broke the block graph (26 breaks per step on the tiny compressed-tensors QLoRA models, transformers 5.22 / 5.23). Read the attribute with getattr instead.
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…5.23+ (unslothai#17830) On transformers 5.23.0, FastLanguageModel trains Llama, Qwen3, Qwen2, Mistral, Gemma and Gemma2 with no gradient checkpointing at all, whatever `use_gradient_checkpointing` is set to. This is the FastLanguageModel side of unslothai#17806, which fixed the same break for block-compiled layers. ## Cause transformers 5.23 moved layer checkpointing into a `forward_with_checkpointing` wrapper. `GradientCheckpointingLayer.__init_subclass__` installs it on each layer class's `forward`, and it only checkpoints while it is still `type(self).forward`. FastLanguageModel puts its own `gated` dispatcher on the class (`_gate_pre_patch_to_unsloth_models` in `llama.py`). transformers' wrapper ends up behind that gate, so it never checkpoints. This hits: - Unsloth's fast decoder-layer forwards. - Plain transformers models of the same class that are built later in the same process. ## Fix - `_gated_method`: when the pre-patch class forward is transformers' checkpoint wrapper, the gate's stock fallback becomes the wrapped forward, and the gate itself is wrapped in the same outside-checkpoint shim unslothai#17806 added to `_block_compile`. Only the outermost wrapper checkpoints, and `use_cache` / `past_key_values` / `layer_past` are cleared unless `_can_checkpoint_with_cache`. - `running_forward` unwraps through the checkpoint wrapper to the fast forward. - A second load re-gates from the first-load original, so it still checkpoints exactly once. - On transformers 5.22.1 and older the class forward is not a wrapper, so nothing changes there. ## Checkpoint calls per training step Tiny models, 2 layers each, `use_gradient_checkpointing = True`, B200 (correctness only): | Arm | Llama | Qwen3 | Qwen2 | Mistral | Gemma | Gemma2 | Llama, 2nd load | |---|---|---|---|---|---|---|---| | transformers 5.22.1, main | 2 | 2 | 2 | 2 | 2 | 2 | 2 | | transformers 5.23.0, main | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | transformers 5.23.0, this PR | 2 | 2 | 2 | 2 | 2 | 2 | 2 | | transformers 5.22.1, this PR | 2 | 2 | 2 | 2 | 2 | 2 | 2 | Cohere and Granite already go through FastModel, which unslothai#17806 fixed, so they checkpoint on main as well. `use_gradient_checkpointing = "unsloth"` shows the same pattern. On 5.23 main the offloaded checkpoint never runs. With this PR there are 2 offloaded-checkpoint forwards per step, the same as 5.22.1. Other checks: - **Loss and gradients:** 5.23 with this PR is bitwise equal to 5.22.1 main in every cell with `True`. With `"unsloth"` it is bitwise equal in all but two cells, which differ by about 1e-7 relative. - **5.23 main** (no checkpointing) drifts 1 to 4% in the gradients and keeps every layer's activations. - **Compile:** 0 graph breaks in every cell, and the same number of unique graphs as 5.22.1. ## Tests `tests/test_fast_layer_checkpointing.py` uses a real `GradientCheckpointingLayer` subclass, on CPU in under 1 s: | transformers | main | this PR | |---|---|---| | 5.23.0 | fails (`[] == [1]`: no checkpoint call) | passes | | 5.22.1 | passes | passes | | 4.57.6 | passes | passes | The existing block-compile, gate and gradient-checkpointing tests behave as follows: - On 5.23: the same two failures on main and on this PR. - `test_router_logits_after_a_forward_without_them`, fixed separately in unslothai#17829. - `test_explicit_config_true_still_checkpoints`, which counts forward pre-hooks that 5.23 deliberately moved. - On 5.22.1: 195 passed.
[skip ci]
… older Unsloth's Inductor cache is not replayed Inductor's on-disk FX graph / AOTAutograd caches key on the traced graph, which names the custom op but not its fake implementation. With the op still called unsloth::qwen3_5_gdn_chunk, a cache an older Unsloth wrote (A sized by the q / k heads) was reused after the fake moved A to the value heads: the compiled block asserted the old output shape on its first call and every grouped value head layer fell back to the stock forward. Same on NVIDIA (B200) and AMD (gfx1151 Linux / Windows), wherever the cache already held the old graph. The forward op is now qwen3_5_gdn_chunk_v2, and a test pins each published op name to its fake meta. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
[skip ci]
…usal stays a bool under dynamic shapes (unslothai#2526) Two graph-break fixes that matter under Unsloth's per-layer block compile, which marks the sequence dimension dynamic. ## Fixes **Grouped ModuleList MoE recompiled every call.** `CALLS["grouped"] += 1` inside the traced forward made Dynamo guard on the counter's old value. On transformers 4.x, Qwen3-MoE, Mixtral and OLMoE therefore recompiled the block 4 times per training step until the recompile limit, after which the block ran eager. The counter now only counts in eager mode. The fullgraph tests prove the grouped path under compile by asserting that the per-expert loop never runs. **SDPA `is_causal` as a bool.** transformers 4.x OLMoE / StableLM / Nemotron / DBRX / PhiMoE compute `is_causal = mask is None and q_len > 1` (StableLM wraps it in `bool()`). With a dynamic sequence dimension that is a SymBool, which `scaled_dot_product_attention` rejects, so Dynamo broke the graph at every attention call: 12 breaks per step on tiny OLMoE and 10 on tiny StableLM. The compiled source now uses the conditional form Llama uses, which guards on the length. This is not GPU specific: the CPU test shows the stock form breaking under plain dynamic shapes. ## Tests - `tests/test_moe_grouped_modulelist_compile_guard.py` (new): fails on main. - `tests/test_sdpa_is_causal_symbool.py` (new): fails on main. - The two grouped ModuleList LoRA test files now assert the grouped path under compile. After the fix, tiny OLMoE and StableLM have 0 breaks per step, with exact fp32 parity. The unsloth side is unslothai/unsloth#17829.
Five fixes to the per-layer block compile. On transformers 5.23 it silently turned itself off, or kept graph-breaking, for several model families.
Fixes
Router logits on transformers 5.23. transformers 5.23 (huggingface/transformers#49594) turned
_CAN_RECORD_REGISTRYinto a dict subclass whose.gettakes the model._install_router_capture_hookspassed the class string, so every lookup returned{}and no hook was installed. A forward withoutput_router_logitsthat followed one without them returned no router logits, and the aux loss raisedIndexError. The fix reads the string keys withdict.get, which works with both registry versions. This fixestest_router_logits_after_a_forward_without_them, which fails on main with 5.23.GDN opaque op on transformers 5.23. transformers 5.23 (huggingface/transformers#49141) stopped repeating the GatedDeltaNet q / k heads up to the value heads before fla's chunk kernel. The op's fake meta gave
Athe q / k head count, so Inductor's output check failed on the first compiled call. Every linear-attention layer withnum_v_heads > num_k_headsthen fell back to the stock forward: Qwen3.5-MoE, Qwen3.6 and Qwen3.8-Flash-Next.Anow takes v's heads, and the Qwen3.5 GDN test asserts that the block really compiled, because a demoted layer has no graph break either.causal_conv1d adapter on transformers < 5.15. Qwen3-Next binds
causal_conv1d_fnat init and calls it withx=. The block adapter requiredhidden_states, so a Qwen3-Next model created after the first block forward raisedTypeErroron 4.57. Arguments now pass through unchanged.Compressed-tensors int4 LoRA without a graph break. PEFT's LoRA forward reads
base_layer.weightinside the compiled block, under the checkpoint's higher-order op. The property read the packed parameter's__dict__, which Dynamo cannot trace there. That gave 26 breaks per step on the tiny compressed-tensors QLoRA models. It now usesgetattr.Tests.
test_old_torch_installs_nothingchecks the torch < 2.7 claim at the patch level. The Qwen3.5 GDN test now skips before transformers 5.2 instead of erroring.Graph-break census
Every
--tier fullregression model plus Qwen3.8-Flash-Next was run with LoRA and QLoRA, over 4 steps at lengths 64, 96 and 64. Together with unslothai/unsloth-zoo#2526, the block-engaged rows with 0 breaks per step are:The rest are known exceptions:
Colab L4: block on vs
UNSLOTH_BLOCK_COMPILE=0Setup: torch 2.14.1, transformers 5.23.0, batch 2 x seq 512, median of steps 6 to 25. Arms are fresh processes, interleaved. The range is the spread across stock arms.
These are tiny, launch-bound models, so real models will gain less. Losses match between arms.
Tests
Each fix has a test that fails on main and passes here: in
tests/test_block_compile.py, plustest_weight_property_traces_without_a_graph_breakintests/test_compressed_tensors_int4.py.