Skip to content

Block compile on transformers 5.23: router logit hooks, GDN op with grouped value heads, int4 LoRA without graph breaks - #17829

Merged
danielhanchen merged 8 commits into
mainfrom
w9-block-compile-523
Nov 15, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
w9-block-compile-523

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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_REGISTRY into a dict subclass whose .get takes the model. _install_router_capture_hooks passed the class string, so every lookup returned {} and no hook was installed. A forward with output_router_logits that followed one without them returned no router logits, and the aux loss raised IndexError. The fix reads the string keys with dict.get, which works with both registry versions. This fixes test_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 A the q / k head count, so Inductor's output check failed on the first compiled call. Every linear-attention layer with num_v_heads > num_k_heads then fell back to the stock forward: Qwen3.5-MoE, Qwen3.6 and Qwen3.8-Flash-Next. A now 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_fn at init and calls it with x=. The block adapter required hidden_states, so a Qwen3-Next model created after the first block forward raised TypeError on 4.57. Arguments now pass through unchanged.

Compressed-tensors int4 LoRA without a graph break. PEFT's LoRA forward reads base_layer.weight inside 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 uses getattr.

Tests. test_old_torch_installs_nothing checks 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 full regression 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:

transformers Block-engaged rows with 0 breaks
4.57.6 91 of 103
5.23.0 112 of 124

The rest are known exceptions:

  • MoE experts kept outside the block by design: granitemoe on 4.57, llama4, qwen3vlmoe.
  • Qwen3.8-Flash-Next QSA selection: compiler-disabled, sparse path only.
  • phi3 rotary: outside the block.
  • One fixture artifact.

Colab L4: block on vs UNSLOTH_BLOCK_COMPILE=0

Setup: 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.

Model Stock ms Block ms Speedup A/A
tiny Qwen3 30.09 [28.9 - 31.4] 14.17 2.12x 3.3%
tiny Qwen3-MoE 45.91 [45.0 - 46.2] 21.39 2.15x 2.8%
tiny Qwen3.5 (GDN) 33.71 [32.6 - 35.7] 21.54 1.56x 9.5%
tiny Qwen2.5-VL (text) 30.98 [30.3 - 31.6] 22.15 1.40x 2.9%
SmolLM2-135M bnb 4-bit 419.6 [415 - 431] 65.90 6.37x 1.1%
tiny Qwen3.8-Flash-Next 140.24 [138 - 141] 71.03 1.97x 2.3%

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, plus test_weight_property_traces_without_a_graph_break in tests/test_compressed_tensors_int4.py.

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T18:54:33.342764Z 2bda4f0 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 5a8cbdba55

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 15, 2026
…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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 2bda4f0d1c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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]
@danielhanchen
danielhanchen merged commit 2fa2204 into main Nov 15, 2026
@danielhanchen
danielhanchen deleted the w9-block-compile-523 branch November 15, 2026 19:52
danielhanchen added a commit to danielhanchen/unsloth-zoo-staging that referenced this pull request Nov 15, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant