Skip to content

Keep the load-time gradient checkpointing mode in for_training - #12629

Merged
danielhanchen merged 7 commits into
mainfrom
fix-for-training-gc-off
Oct 3, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fix-for-training-gc-off

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 3, 2026 •

Copy link
Copy Markdown
Member

Problem

Loading with use_gradient_checkpointing = False and then calling FastLanguageModel.for_training(model) (or FastModel.for_training(model), which notebooks do after an inference cell) crashes on the next training step:

AttributeError: 'Qwen3DecoderLayer' object has no attribute '_gradient_checkpointing_func'

for_training defaulted to use_gradient_checkpointing = True and set that flag on every module. In transformers 5 the decoder layers are GradientCheckpointingLayers, which checkpoint themselves through _gradient_checkpointing_func. That attribute is only installed by gradient_checkpointing_enable(), which never ran because checkpointing was turned off at load. Training with checkpointing off works fine as long as for_training is not called.

Fix

  • for_training(model, use_gradient_checkpointing = None): None now restores the mode recorded at load / get_peft_model (model._unsloth_gradient_checkpointing, the same value the GRPO trainer already restores). With nothing recorded, it follows whether loading armed the checkpointing layers, and models without any keep the old default of True.
  • An explicit truthy mode (True / "unsloth") on a model loaded without checkpointing now arms it first through gradient_checkpointing_enable(), the same call the load path uses, instead of setting a flag with nothing behind it. It calls the outer model's gradient_checkpointing_enable, so the per-model overrides Unsloth installs there (Gemma 3N / 4 reentrant, DeepSeek-V4.1 non-reentrant) still apply.
  • "Needs a checkpoint function" covers GradientCheckpointingLayers and any module whose own forward calls self._gradient_checkpointing_func (older and remote-code backbones). One that still has no checkpoint function (a model whose gradient_checkpointing_enable() refuses) is never switched on, so it trains without checkpointing instead of crashing.
  • Applied to FastLlamaModel, FastBaseModel and the FastModel wrapper; FastDiffusionModel.get_peft_model now records its choice too, so FastModel.for_training(model) keeps it.
  • Arming late also turns use_cache off, as loading with checkpointing on does (for_inference restores it).
  • Limitation: arming late uses the standard checkpoint function even for "unsloth", so there is no activation offload (Qwen3-0.6B, 1.6k tokens: 1.17 GB armed late vs 1.04 GB with "unsloth" at load). Loading with "unsloth" stays the way to get offloading.

Results

Case main this PR
Qwen3-0.6B, GC off, then for_training(model) AttributeError trains, loss 0.677 then 0.5945 (same as GC off without for_training)
Qwen3-0.6B, GC off, generate, then for_training(model) AttributeError trains
Qwen3-0.6B, GC off, for_training(model, use_gradient_checkpointing = True), 1.6k tokens AttributeError checkpointing armed: peak 4.18 GB -> 1.17 GB (GC on at load: 1.04 GB), same loss, all 196 LoRA B matrices get gradients
gemma-3-270m via FastModel, GC off, then for_training(model) AttributeError trains, loss 0.7333 then 0.5314
Qwen3-0.6B full finetuning, GC off, then for_training(model) AttributeError trains with checkpointing off
Qwen3-0.6B, GC "unsloth" (default path) loss 0.677 / 0.5945, peak 0.72 GB identical losses and peak

Every input

for_training over class (Llama path, generic path) x recorded mode (none, "unsloth", True, False) x layers armed or not x argument (omitted, True, "unsloth", False), 64 cells, main vs this PR:

  • 36 identical.
  • 24 crashed on main and now train: 20 asked for checkpointing and get it armed, 4 stay off (recorded False, or nothing recorded and loaded without checkpointing).
  • 4 changed: with the argument omitted, a recorded "unsloth" is restored as "unsloth" instead of True (same behaviour, both truthy), and a recorded False from get_peft_model(use_gradient_checkpointing = False) is now respected instead of being switched back on. The trainers already restore the recorded value at init, so that only differs in custom training loops.

for_training per call on Qwen3-0.6B (2389 modules), interleaved: main 11.2 / 10.6 ms, this PR 10.5 / 11.1 ms.

Tests

  • New tests/test_for_training_gc_off.py: 26 tests (default keeps checkpointing off when it was off at load, an explicit enable arms it and every layer gets gradients, the default restores the recorded mode, unrecorded models keep their load-time choice, a backbone that calls the checkpoint function itself, the outer gradient_checkpointing_enable override is used, a late enable turns use_cache off and for_inference restores it, a source-unreadable forward counts as checkpointing, FastModel keeps a diffusion adapter's recorded choice).
  • Passes on transformers 5.17.0, 4.57.6 and 4.52.4; Qwen3-0.6B armed late on 4.57.6: peak 3.88 GB -> 1.17 GB, same loss, all LoRA B matrices get gradients.
  • tests/test_for_training_generation_flag.py rebuilds for_training from source with only the helpers in the same file, so it now also pulls the new helpers from _utils.py.
  • The 19 test files touching for_training / gradient checkpointing fail the same set on main and on this branch (only pre-existing tests/test_rms_rope_compile.py failures on this machine).

for_training() defaulted to use_gradient_checkpointing=True and set the flag on every module.
On a model loaded with use_gradient_checkpointing=False, transformers' GradientCheckpointingLayer
then tried to call a _gradient_checkpointing_func that gradient_checkpointing_enable() never
installed, so the next training forward raised AttributeError.

The default is now None, which restores the mode recorded at load / get_peft_model (True when
nothing was recorded, as before), and a checkpointing layer without a checkpoint function is never
switched on.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-03T13:55:56.092692Z b8ed266 New commits
🔒 Security Review ✅ Completed 2026-10-03T12:00:06.576819Z 2b60ba4 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 security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 2b60ba410c

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 658bac09ec

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

Comment thread unsloth/models/llama.py
Comment on lines +4362 to +4363
if use_gradient_checkpointing:
arm_gradient_checkpointing(model)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Install smart checkpointing when requesting Unsloth mode

When a model was prepared with checkpointing disabled and the caller later uses for_training(..., use_gradient_checkpointing="unsloth"), the earlier preparation has removed the smart-checkpointing patch, while this path only calls ordinary gradient_checkpointing_enable(). The layers are then labeled with the truthy string "unsloth", but their checkpoint function is the standard Transformers implementation, so the requested activation offloading and associated memory savings are absent. The new test only verifies that the function is callable and therefore misses this mode mismatch; this path must apply the Unsloth checkpointing configuration before arming the layers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: the late enable gives real checkpointing (Qwen3-0.6B, 1.6k tokens: peak 4.18 GB off, 1.17 GB armed late, 1.04 GB with "unsloth" at load, same loss, every LoRA B gets gradients), so nothing is lost or wrong, only the activation offload is missing. Load-time "unsloth" also does not bind the zoo checkpoint on the layers (they keep torch.utils.checkpoint.checkpoint while the module-level function is patched), so re-running apply_unsloth_gradient_checkpointing mid-session would arm a different function than loading does. Loading with "unsloth" stays the way to get offloading.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c17713dccb

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 3, 2026
@danielhanchen
danielhanchen merged commit 2557cba into main Oct 3, 2026
@danielhanchen
danielhanchen deleted the fix-for-training-gc-off branch October 3, 2026 18:10
JoshuaL3000 pushed a commit to JoshuaL3000/unsloth that referenced this pull request Oct 4, 2026
…thai#12629)

for_training() no longer forces gradient checkpointing on: an omitted mode keeps the one chosen at load / get_peft_model, an explicit enable on a model loaded without checkpointing arms it through gradient_checkpointing_enable() (and turns use_cache off), and a layer without a checkpoint function is never switched on, so models loaded with use_gradient_checkpointing=False no longer crash with a missing _gradient_checkpointing_func.
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