Repository navigation
Block compile: keep gradient checkpointing on transformers 5.23+ - #17806
Merged
Merged
Conversation
transformers 5.23 moved layer checkpointing from GradientCheckpointingLayer.__call__ into a forward wrapper that checkpoints only while it is type(self).forward. Block compile replaced the class forward, so that wrapper ran inside the block, never saw itself as outermost, and every layer trained without checkpointing: gemma-4-12b QLoRA kept 16 GB of activations at seq 2048 and 64 GB at 8192 (A100-80 OOM). Compile the layer's own forward and put the checkpoint wrapper back outside the block.
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. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
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.
danielhanchen
added a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Nov 16, 2026
Final comment pass for recently merged PRs. Trims comments added by unslothai#17660, unslothai#17806, unslothai#17807, unslothai#17808, unslothai#17812, unslothai#17830, unslothai#17854, unslothai#17857 and unslothai#17870 that are still on main. Multi-line explanations are collapsed to one line, and comments that restate the code are removed. Comments that explain a version quirk or a correctness trap are kept, along with license headers and pragmas. Changed comment lines: unslothai#17660 5 -> 2, unslothai#17806 4 -> 2, unslothai#17808 1 -> 0, unslothai#17830 3 -> 1, unslothai#17857 1 -> 0. unslothai#17807, unslothai#17812, unslothai#17854 and unslothai#17870 are unchanged. Overall: 6 files, 14 lines removed, 5 added. Only comments change: the AST check (comment_tools.py check) and the pre-push gate both pass.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
On transformers 5.23.0 and later, block compile silently turns off gradient checkpointing for every block-compiled decoder layer. This PR puts the checkpoint back outside the compiled block.
Cause
transformers 5.23 moved layer checkpointing out of
GradientCheckpointingLayer.__call__. It now lives in aforward_with_checkpointingwrapper that__init_subclass__installs on each layer class'sforward. That wrapper only checkpoints while it is stilltype(self).forward._block_compile._wrapreplacescls.forwardwith the compiled block, which calls the original forward. The transformers wrapper therefore ran inside the block, never saw itself as the outermostforward, and every layer trained with no checkpointing at all. transformers 5.22.1 and earlier checkpoint in__call__, so they are not affected.Measured on gemma-4-12b-it QLoRA, using random weights from the real config, batch 1, GC
"unsloth", on an A100-80:The right-hand column was measured with this fix plus Gemma-4 attention-kernel changes that will be a separate PR. Those kernels do not change peak memory: on transformers 5.22.1, where checkpointing works on both sides, QLoRA 2048 peaks at 8.5 GB with and without them.
Fix
__code__.co_name == "forward_with_checkpointing"with a__wrapped__), compile the layer's own forward.use_cache/past_key_values/layer_pastunless_can_checkpoint_with_cache.__call__.Tests
New in
tests/test_block_compile.py, CPU only, under 4 s together:test_block_keeps_transformers_layer_checkpointing: a 5.23-style wrapper around a toy layer. Checks exactly one checkpoint call in training, none in eval, one after re-wrapping, and the reentrant case.test_block_leaves_call_level_checkpointing_alone: the 5.22 shape, where nothing is added.test_block_keeps_real_transformers_checkpointing: a realGradientCheckpointingLayersubclass on the installed transformers. It is skipped when that version checkpoints in__call__.assert [] == [1]: no checkpoint call)The whole
tests/test_block_compile.pyfile on transformers 5.23.0 + torch 2.15.0 has the same 6 failures on main and on this PR:test_outer_compile_traces_decode_aware_moe[fullgraph|default]test_disable_unless_decode_keeps_original_traceable_on_old_torchtest_router_*testsThose are separate and not touched here.