Skip to content

Block compile: keep gradient checkpointing on transformers 5.23+ - #17806

Merged
danielhanchen merged 1 commit into
mainfrom
block-compile-gc-523
Nov 15, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
block-compile-gc-523

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 a forward_with_checkpointing wrapper that __init_subclass__ installs on each layer class's forward. That wrapper only checkpoints while it is still type(self).forward.

_block_compile._wrap replaces cls.forward with the compiled block, which calls the original forward. The transformers wrapper therefore ran inside the block, never saw itself as the outermost forward, 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:

main this PR
seq 2048, peak memory 25.2 GB 8.4 GB
seq 2048, activations kept after forward 17 GB 0.07 GB
seq 8192 out of memory 10.2 GB
LoRA seq 2048, peak memory 40.3 GB 23.5 GB

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

  • When the class forward is transformers' checkpoint wrapper (__code__.co_name == "forward_with_checkpointing" with a __wrapped__), compile the layer's own forward.
  • Install a checkpoint wrapper with the same semantics outside the block. It checkpoints only when it is the outermost forward, and it clears use_cache / past_key_values / layer_past unless _can_checkpoint_with_cache.
  • Wrapping a class a second time (a second model load) still checkpoints once.
  • A reentrant checkpoint's first no-grad call runs the block itself and does not re-enter the checkpoint wrapper.
  • With transformers 5.22.1 and earlier nothing changes, because checkpointing stays in __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 real GradientCheckpointingLayer subclass on the installed transformers. It is skipped when that version checkpoints in __call__.
transformers 5.23.0, torch 2.15.0 transformers 5.22.1
main + new tests 2 failed (assert [] == [1]: no checkpoint call) 1 failed, real-layer test skipped
this PR 7 passed 6 passed, real-layer test skipped

The whole tests/test_block_compile.py file 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_torch
  • three test_router_* tests

Those are separate and not touched here.

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.
@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-15T09:53:57.196239Z 518903d 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. Already looking forward to the next diff.

Reviewed commit: 518903d1b1

ℹ️ 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 a21e6b7 into main Nov 15, 2026
@danielhanchen
danielhanchen deleted the block-compile-gc-523 branch November 15, 2026 12:41
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.
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