Repository navigation
Gradient checkpointing: checkpoint_skip_layers = "auto" and UNSLOTH_GC_KEEP_LAYERS - #14404
Conversation
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.
Codex Review SummaryThis 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. |
…ing optimizer state [skip ci]
…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]
…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]
…ecoder card grads, plan device from any resident layer [skip ci]
…ount resident accumulated grads once, reserve the foreach AdamW workspace, drop the planner on an explicit value [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 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".
| # 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| max_seq = max( | ||
| rows, self.target_seq or getattr(self.model, "max_seq_length", None) or rows | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
| 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 [] |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
… 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.
…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.
Summary
checkpoint_skip_layers = Kkeeps 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:UNSLOTH_GC_KEEP_LAYERS = K | max | autosets 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.Losses match per step across arms.
Notes
max_memory_reserved()covers training from that point.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.