Skip to content

FastLanguageModel: keep layer gradient checkpointing on transformers 5.23+ - #17830

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

danielhanchen merged 1 commit into
mainfrom
flm-gc-523

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 #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 Block compile: keep gradient checkpointing on transformers 5.23+ #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 #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:

…5.23+

transformers 5.23 moved layer checkpointing from GradientCheckpointingLayer.__call__
into a forward_with_checkpointing wrapper that __init_subclass__ puts on each layer
class's forward, and it only checkpoints while it is type(self).forward. pre_patch
replaces the decoder layer forward with the fast forward (then the gate around it),
and LlamaModel_fast_forward leaves GradientCheckpointingLayer instances to their
own checkpointing, so Llama, Qwen3, Qwen2, Mistral, Gemma and Gemma2 trained with
no gradient checkpointing at all, with either use_gradient_checkpointing="unsloth"
or True. Plain transformers models built after a FastLanguageModel load lost it too.

When the pre-patch class forward is transformers' checkpoint wrapper, the gate now
wraps its stock forward and goes inside the same wrapper semantics as the block
compile fix (_checkpointing: outermost only, use_cache / past_key_values /
layer_past cleared unless _can_checkpoint_with_cache). Block compile sees it as a
transformers wrapper and keeps checkpointing outside the block. transformers 5.22
and older are unchanged: their class forward is not a wrapper.
@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-15T13:22:05.316292Z 1232e9d 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. Another round soon, please!

Reviewed commit: 1232e9d2bb

ℹ️ 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 e9664f8 into main Nov 15, 2026
@danielhanchen
danielhanchen deleted the flm-gc-523 branch November 15, 2026 16:18
danielhanchen added a commit that referenced this pull request Nov 15, 2026
…relative imports (#17853)

## Summary


`tests/test_grpo_prefix_grouper_capability.py::test_pre_patch_gate_applies_only_on_marked_modules`
has failed in `Repo tests (CPU, rest)` on `main` since #17830 ("keep
layer gradient checkpointing on transformers 5.23+"). Seen on the
staging run of #12384, base `57d9d1de`:

```
unsloth/models/llama.py:3456: in _gated_method
    from ._block_compile import _checkpointing, _is_hf_checkpoint_wrapper
E   KeyError: "'__name__' not in globals"
```

#17830 is correct: `_gated_method` now re-applies transformers' layer
checkpoint wrapper. The test's `_top_level` helper pulls functions out
of `llama.py` with `ast` and execs them in a bare namespace, to avoid
importing `unsloth` (GPU init). A relative import has no package to
resolve against in that namespace.

## Change (test only)

`_top_level` now gives the namespace a `__name__` and `__package__`
under a stand-in package (`_unsloth_models_under_test`), registered once
with `__path__ = [unsloth/models]`. A relative import inside an
extracted function then loads the real sibling file (`_block_compile.py`
here) as `_unsloth_models_under_test._block_compile`. It does not run
`unsloth/models/__init__.py`, so the harness still avoids the GPU stack,
and the test exercises the shipped `_checkpointing` /
`_is_hf_checkpoint_wrapper` rather than stubs.

## Verification

| | `tests/test_grpo_prefix_grouper_capability.py` |
|---|---|
| main (`57d9d1de`) | 1 failed, 19 passed |
| this branch | 20 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