Skip to content

Block compile: transformers 5.24 cache contract, second hooked model, replay skip eligibility - #18986

Merged
danielhanchen merged 3 commits into
mainfrom
fu-block-compile-recheck
Nov 23, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fu-block-compile-recheck

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

What

Follow-ups to #18811 and #18934 in block compile (unsloth/models/_block_compile.py, unsloth/kernels/fast_lora.py):

  1. The checkpoint shim that block compile puts back outside the block (_checkpointing) now follows the transformers 5.24 GradientCheckpointingLayer wrapper. It checkpoints only while grad is enabled, and it clears the renamed cache= keyword as well as past_key_values= / layer_past=. _has_cache also treats cache= as a cache call, so cached calls keep the stock forward as they did with past_key_values=.
  2. patch_block_compile rebinds accelerate-hooked layers of a model whose layer class was already wrapped for an earlier model. The installed forward keeps the forward it replaced (_unsloth_block_before) for that rebind.
  3. block_skip_down_eligible refuses MLPs whose gate / up / down adapters have a dropout module or a lora_B bias. _mlp_output_unobserved refuses an MLP class that overrides __call__.

Why

  1. transformers 5.24 renamed the layer cache keyword to cache. It also stopped checkpointing a training-mode layer under no_grad, so generate() on a model left in train() keeps its cache. The shim still checkpointed under no_grad, never cleared cache=, and _has_cache missed cache=. A cached call therefore ran the compiled block and could write the cache twice. The repro was a two-layer random Llama on transformers 5.24.0 behind accelerate dispatch hooks, CPU, torch 2.14.1. The block was installed with aot_eager:
    • no_grad prefill + decode in train mode: main raised The size of tensor a (6) must match the size of tensor b (3) (6 cached keys against a 3-position mask), after 17 graphs and 49 breaks. With this change the cache lengths are 3 then 4 and the logits match stock transformers exactly (max delta 0), with 0 graphs.
    • Grad-enabled forward with an explicit cache: main raised the same error. Here it runs, matching stock transformers.
  2. Block compile: keep gradient checkpointing on layers behind accelerate device-map hooks #18811 rebinds accelerate's _old_forward only when it wraps the class. A second model of the same layer class, dispatched before the first was patched, kept the stale bound wrapper. On transformers 5.23+ that means no checkpointing and no compiled block. Same repro, transformers 5.24: the second model's layer ran its projection once with no regional graph on main (no checkpoint replay). With this change it runs twice with one graph, the same as the first model.
  3. LoRA dropout and a lora_B bias take LoRA_MLP's branch that always runs the down projection. The compiled block still passed the skip flag (an extra replay graph) and counted a skip in MLP_DOWN_SKIP_STATS. On Gemma GEGLU with lora_dropout=0.1, main counted 3 skips for 3 layers whose replay outputs were all finite (none skipped). An MLP subclass that overrides __call__ can transform mlp(x) outside its forward. With a __call__ that squares the output, main still skipped that layer's down projection in eager. The backward through the square then read the placeholder: 29 of 43 gradient tensors differed from skip-off, on both GEGLU forms and on Llama SwiGLU.

Tests

Each new test fails on main (632c437424) and passes here (CPU, torch 2.14.1):

  • tests/test_block_compile.py::test_block_checkpoint_shim_keeps_the_5_24_cache_contract: main checkpointed under no_grad ([1] == []).
  • tests/test_block_compile.py::test_block_rebinds_hooked_layers_of_a_second_model: main ran the second model with no checkpoint ([] == [1]).
  • tests/test_gc_skip_replay_mlp_down_gemma.py::test_mlp_call_override_keeps_down_projection[gemma_approx|gemma_exact|llama]: main counted 3 skips where 2 are allowed.
  • tests/test_gc_skip_replay_mlp_down_gemma.py::test_compiled_replay_with_lora_dropout_counts_no_skip[gemma_approx|gemma_exact]: main reported a dropout MLP as skip-eligible.

Suites, run with unsloth-zoo main for gradient_checkpoint_replay_module:

  • tests/test_block_compile.py, tests/test_gc_skip_replay_mlp_down.py, tests/test_gc_skip_replay_mlp_down_gemma.py and tests/test_gc_skip_replay_mlp_down_block_compile.py on transformers 4.57.6: 134 passed, 25 skipped (CUDA only).
  • tests/test_block_compile.py on transformers 5.23.0 (torch 2.15.0) and on 5.24.0: 81 passed, 9 skipped. The 2 failures in each venv also fail on main: vllm.sampling_params is missing there.

Not covered

  • No GPU run. To confirm on a GPU, run training-mode generate() from a QLoRA Llama on transformers 5.24 with block compile on, once on a single GPU and once with device_map split across 2 GPUs. Also run a Gemma LoRA with lora_dropout > 0 under block compile and check the graph count.
  • Two findings are not changed here. An enclosing torch.compile(fullgraph=True) around a hooked model still breaks on the block's inline flags inside the checkpoint. The FP8-LoRA per-instance layer.forward still shadows accelerate's hook (this predates Block compile: keep gradient checkpointing on layers behind accelerate device-map hooks #18811).

GPU check

Colab L4, transformers 5.24.0, QLoRA Llama-3.2-1B through FastModel with block compile on, left in train(): a no-grad prefill then one cached step raises expanded size (12) must match (6) on the merge base; with this PR the cache goes 6 then 7. Gemma with lora_dropout=0.1: base marks the layer skip-eligible and compiles 3 graphs, this PR refuses and compiles 2. Unit tests: base 7 failed, head 129 passed.

transformers 5.24 renamed the layer cache keyword from past_key_values to
cache and stopped checkpointing a training-mode layer when grad is off (so
generate() from a model left in train() keeps its cache). The block's
checkpoint shim still checkpointed under no_grad and never cleared cache=,
and _has_cache missed cache=, so a cached call ran the compiled block and
could write the cache twice (8 keys against a 4-position mask).

Also rebind accelerate-hooked layers of a second model whose layer class was
already wrapped for an earlier model: the rebind only ran on the first wrap,
so the second model kept the stale bound forward with no checkpointing.
…l__ overrides

block_skip_down_eligible let an MLP with LoRA dropout or a lora_B bias
through, though LoRA_MLP's dropout / bias branch always runs the down
projection: the compiled block counted a skip in MLP_DOWN_SKIP_STATS that
never happened and compiled a replay graph for the flag. Refuse them.

_mlp_output_unobserved also accepted an MLP class overriding __call__, which
can transform mlp(x) outside its forward; with a squaring __call__ the eager
replay skip changed 29 of 43 gradients. Refuse those too.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T05:30:28.392759Z 7bfa5cf 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 05f3993aac

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

The checkpoint shim applied the transformers 5.24 rule (skip checkpointing
when grad is off) on every version. On 5.23 the stock wrapper still
checkpoints a training-mode layer under no_grad with use_cache=False and
past_key_values=None, so a cache handed to the layer stays empty; the shim
ran the layer as is and filled it (real LlamaDecoderLayer: 0 stock vs 3).

Derive the contract from the transformers wrapper being replaced: the grad
gate when its code calls is_grad_enabled, and only the cache keywords it
clears. Unknown wrappers keep the 5.24 rule and clear every cache name.

[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. Can't wait for the next one!

Reviewed commit: 7bfa5cfc02

ℹ️ 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
danielhanchen merged commit ee75c49 into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the fu-block-compile-recheck branch November 23, 2026 07:27
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