Skip to content

Gradient checkpointing: checkpoint_skip_layers = "auto" and UNSLOTH_GC_KEEP_LAYERS - #14404

Merged
danielhanchen merged 18 commits into
mainfrom
dh/s2-w6-skipauto
Oct 21, 2026
Merged

danielhanchen merged 18 commits into
mainfrom
dh/s2-w6-skipauto

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

checkpoint_skip_layers = K keeps K decoder layers un-checkpointed (no recompute, more memory). Choosing K by hand means knowing the card. "auto" picks it after the first training step:

  • every eligible layer's reentrant recompute is measured in the first backward and the largest one sizes each kept layer (hybrid stacks mix attention and Mamba blocks);
  • the measured step is scaled to the trainer's batch (per_device_train_batch_size, doubled for DPO / ORPO / CPO pairs) at the longest of max_length, max_seq_length and the measured length, and quadratically for eager or unknown attention backends;
  • at the next training forward, 3/4 of the card's usable memory, minus 1 GiB, after the scaled activation peak, pending AdamW state and the foreach optimizer workspace on that card, is spent on layers; gradients still resident under gradient accumulation are counted once;
  • the plan never changes afterwards. Inputs a collator expands past that length bound (images, audio) need max_seq_length set to their bound.

UNSLOTH_GC_KEEP_LAYERS = K | max | auto sets the same option without code changes when the argument is left at 0, and also applies on the full finetuning path. An explicit value replaces an earlier "auto" planner. Distributed launches, layers split over several GPUs and non-reentrant checkpointing keep every layer checkpointed, with a printed reason. With neither the argument nor the env var set, nothing changes.

Tests

  • tests/test_gc_skip_auto.py: main 9 failed / 1 passed, this PR 10 passed (torch 2.10, 2.13, 2.14). Tiny fp32 Qwen3 on CUDA: step 1 stays fully checkpointed, then all layers are kept, and loss and every gradient are bitwise equal to full checkpointing over 3 steps. With no free memory nothing is kept; non-reentrant backs off.
  • Step time vs full checkpointing, 3 runs per arm, ABBA, A/A first:
GPU model auto keeps step peak
T4 (fp16) Qwen3-0.6B 4k 28/28 1.837 -> 1.398 s (-24%) 1.8 -> 6.4 GB
T4 (fp16) Qwen3-4B 4-bit 8k 7/36 about -5% 9.9 of 15 GB
A100 40 GB (bf16) Qwen3-0.6B 4k 28/28 -31.6% 6.4 GB
A100 40 GB (bf16) Qwen3-4B 4-bit 8k 32/36 1.619 -> 1.232 s (-23.9%) 28.4 of 39.5 GB

Losses match per step across arms.

Notes

  • With "auto" on, the planner resets the CUDA peak memory statistics once at the first training forward (step-local peak), so a later max_memory_reserved() covers training from that point.
  • Non-CUDA accelerators print that "auto" needs CUDA and keep every layer checkpointed.

Not covered

L4, multi-GPU / DDP / FSDP2 (refused by design), GRPO / DPO runs, Windows / macOS / AMD. The step-time table predates the later sizing changes (batch and quadratic scaling, foreach workspace reserve), which can keep fewer layers on tight cards.

checkpoint_skip_layers = K keeps K decoder layers un-checkpointed, trading their activations for no
recompute. "auto" picks K after the first training step: one layer's reentrant recompute is measured
in the first backward (scaled to max_seq_length), and the next training forward spends 3/4 of the
card's free memory, after the first step's activation peak and AdamW state, minus 1 GiB on layers.
The smart offloader then recounts its checkpointed calls. UNSLOTH_GC_KEEP_LAYERS = K | max | auto sets
the same choice when the argument is left at 0. Single process, single GPU only; without reentrant
checkpointing every layer stays checkpointed.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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 🔄 Running since 2026-10-21T07:49:11.103761Z ac85c41 New commits
🔒 Security Review ⚠️ Failed 2026-10-20T20:07:02.707768Z
We couldn’t complete this review. Comment @codex security review to try again.
4ec46ba PR opened
ℹ️ 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 danielhanchen self-assigned this Oct 20, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits October 20, 2026 21:05
…CUDA

Reserve AdamW state for each trainable param the optimizer has no state for yet instead of all or
nothing after the first step, scale only the sequence-dependent part of the first step's peak (the
grads the first backward allocated are added back unscaled), and keep every layer checkpointed with
the one-time diagnostic when no decoder layer sits on CUDA, so no hook is registered.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 3 commits October 20, 2026 22:06
…ager attention, drop the strong optimizer hook

Measure every eligible layer recompute and size kept layers by the largest, so hybrid
attention + Mamba stacks are not sized by a cheap last layer. Scale by seq ratio squared
when the decoder attention is eager or unidentified. Register the global optimizer
step pre hook through a weakref and remove it when the planner is collected, so a model
that never reaches plan() can be freed.
Both get_peft_model early returns for full finetuning now call skip_checkpointing, so
an explicit checkpoint_skip_layers or UNSLOTH_GC_KEEP_LAYERS is no longer ignored.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ount resident accumulated grads once, reserve the foreach AdamW workspace, drop the planner on an explicit value

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@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: 3ff65cac6a

ℹ️ 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/_utils.py Outdated
# State an optimizer step already allocated is excluded by usable_cuda_bytes; reserve the rest
# (sparse MoE experts, unused towers and gradient accumulation have none yet).
trainable = [p for p in self.model.parameters() if p.requires_grad]
optimizer = sum(p.numel() * 8 for p in trainable if not self._has_optimizer_state(p))

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 Charge pending optimizer state only to its parameter device

When the decoder is on one GPU but another trainable component (for example, a vision tower) is on a second GPU, usable_cuda_bytes(device) measures only the decoder card while this sum deducts AdamW state for parameters on every device. A sufficiently large tower can therefore make the budget negative and leave every decoder layer checkpointed even though its optimizer state will be allocated on the other card; restrict this pending-state estimate to parameters whose state belongs on device.

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.

Fixed in 74df70e. Pending AdamW state is reserved only for trainable params on the planned card; a tower on another GPU no longer reduces the decoder card's budget.

Comment thread unsloth/models/_utils.py Outdated
Comment on lines +8653 to +8655
max_seq = max(
rows, self.target_seq or getattr(self.model, "max_seq_length", None) or rows
)

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 Account for later batches that exceed the first measured length

When a later batch expands beyond both the configured limit and the first measured rows—notably with multimodal collators whose image/audio token count varies per example—this permanent plan is still sized using only the first batch's length. The later batch can therefore need substantially more activation memory after layers have been un-checkpointed and OOM; either derive a real upper bound for expanded sequences, keep observing until that bound is known, or decline auto-skipping for unbounded batches.

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 the behaviour here. The plan is sized for the trainer batch at the longest of max_length, max_seq_length and the measured length, which is the same bound every other Unsloth memory estimate (offload_layers and offload_embedding auto) uses. A collator that expands inputs past max_seq_length without a known bound cannot be sized up front by any one-shot planner, and keeping the hooks alive to re-plan would add per-step overhead to an opt-in speed feature. The docstring now says to set max_seq_length to the expanded bound in that case (74df70e).

Comment thread unsloth/models/_utils.py
budget = headroom * self.FRACTION - self.MARGIN
per_layer = self.layer_bytes * scale
count = int(budget // per_layer) if per_layer > 0 and budget > 0 else 0
self.kept = skip_checkpointing(self.model, count) if count > 0 else []

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 Exclude non-checkpointable layers when applying the auto count

For a heterogeneous decoder where only some blocks expose gradient_checkpointing, installation probes only those blocks, but this call delegates to skip_checkpointing, whose candidate list includes every non-swapped block. An evenly spaced choice can consequently land on a block without the flag; that block is skipped by the helper's loop while its index is still returned and reported as kept, so the auto budget may produce no speedup or fewer un-checkpointed layers than calculated. Apply the count to the same checkpointable eligibility set used during installation.

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.

Fixed in 74df70e. skip_checkpointing picks its evenly spaced layers only among non-swapped layers that expose gradient_checkpointing, the same set the planner probes, so every returned index is actually un-checkpointed.

…ed card, count only checkpointable layers, document the length bound

[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. You're on a roll.

Reviewed commit: 74df70e15b

ℹ️ 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 af28041 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the dh/s2-w6-skipauto branch October 21, 2026 07:49
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 21, 2026
… gc-skip tests (unslothai#14504)

`Repo tests (CPU, rest)` and `Repo tests (CPU, studio)` fail on main and
on every PR based on it. Three test files added by unslothai#14400 and unslothai#14404
trip the repo's own lint tests:

-
`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`:
skip guards on `torch.cuda.is_available()`, which
`tests/_zoo_aggressive_cuda_spoof.py` patches to True, so these tests
un-skip on the CPU runners:
  - `test_gpt_oss_bf16_load_in_4bit.py` lines 99 and 160;
  - `test_gpt_oss_bnb_checkpoint_layout.py` line 191;
  - `test_gc_skip_auto.py`, 7 guards.
-
`tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[10]`:
`test_gpt_oss_bnb_checkpoint_layout.py:362` opens a file without
`encoding`.

## Change
- The guards use `has_real_cuda()` from
`tests/_shared/real_accelerator.py`, as the other GPU tests do.
- The `open()` call names `encoding = "utf-8"`.

Test files only.

## Validation
- Both lint tests on CPU: 40 passed (they failed on main).
- On a GPU, the three edited files on main and on this branch: 78
passed, 2 failed on both sides. `has_real_cuda()` and
`torch.cuda.is_available()` agree on a real GPU, so the guards change
nothing there. The two failures are the same tests on both sides
(`test_bf16_checkpoint_loads_real_weights_in_4bit`,
`test_bf16_checkpoint_4bit_generate_matches_prefill`) and are not
touched here.
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…fixed list (#14518)

## Problem

The `Repo tests (CPU, fsdp2)` shard fails on main: 11 tests across the
gloo files that wrap `Trainer.__init__` with
`_install_wrapped_trainer_init` from
`tests/test_fsdp2_native_trainer_args_gloo.py` (for example #14494).
Every rank crashes the same way:

```
File "unsloth/models/_utils.py", line 5615, in _unsloth_trainer_init
    _size_auto_checkpoint_skip_for_trainer(self)
NameError: name '_size_auto_checkpoint_skip_for_trainer' is not defined
```

The harness runs the real `_unsloth_trainer_init` source from
`_utils.py` in a namespace that stubs the helpers it calls. That list is
written out by hand. #14404 added a call to
`_size_auto_checkpoint_skip_for_trainer`, which is not in the list. The
product is fine: the helper is defined at module level in `_utils.py`.

## Fix

Test only. The explicit stubs stay. On top of them, every free function
`_unsloth_trainer_init` calls that the namespace does not provide is
stubbed as well. Builtins, and names the wrapper binds itself
(assignments and in-function imports), are excluded. The next helper
added to the wrapper cannot take the shard down this way again.

## Verification

CPU torch 2.10, peft 0.21.2, accelerate 1.15.0, unsloth-zoo main. Files
run: `test_fsdp2_native_optim_reentry_gloo.py`,
`test_fsdp2_native_trainer_fsdp_clip_gloo.py`,
`test_fsdp2_native_subclass_optimizer_gloo.py` and
`test_fsdp2_native_trainer_args_gloo.py`.

- main: 5 failed, 12 passed (the `NameError` above).
- With this change: 17 passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant