Repository navigation
Skip the frozen bottom layers under gradient checkpointing when only upper layers are trained - #18442
Conversation
With adapters only on the upper layers (finetune_last_n_layers, layers_to_transform), the embedding output is made to require grad so reentrant checkpointing reaches the adapters, which also checkpoints, replays and backpropagates every frozen layer below for a gradient nothing reads. When every trainable parameter sits at or above layer k of one decoder stack (plus the output head), layers 0..k-1 now run once without a graph and layer k's input is the leaf that requires grad. Loss and gradients are bitwise unchanged. UNSLOTH_FROZEN_PREFIX_SKIP=0 turns it off.
Block swap streams the frozen blocks around their checkpoint replay, so the skip stays off there. A first trainable layer that checkpoint_skip_layers keeps out of checkpointing still takes the cut; the head parameter set is computed once.
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0f6396a3b2
ℹ️ 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".
…sitional or keyword
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
…ompile, Qwen3-VL in-place writes (unslothai#18632) Follow-up fixes for unslothai#18442, found while re-checking the PRs merged on 2026-11-19. One commit per fix; every fix has a test that fails on main and passes here. | Fix | Follows up | Severity | |---|---|---| | Frozen-prefix skip: looped / recurrent-depth stacks | unslothai#18442 | P1 | | Frozen-prefix skip: no per-forward plan walk when nothing can be skipped | unslothai#18442 | P2 | | Frozen-prefix skip: a planned stack the forward bypasses | unslothai#18442 | P1 | | Frozen-prefix skip: stand down under an outer torch.compile | unslothai#18442 | P1 | | Frozen-prefix skip: nested inputs that require grad | unslothai#18442 | P2 | | Frozen-prefix skip: in-place writes into the skipped hidden states (Qwen3-VL DeepStack) | unslothai#18442 | P1 | ## Tests (this branch vs main `54af93780b`, CPU) - New and changed tests: main 13 failed / 11 passed, this branch 24 passed. Each test loads the code of its own tree. - Neighbouring suites on this branch: frozen-prefix suites: 34 passed. - `prepush_gate.py` passes. ## Frozen-prefix skip: looped / recurrent-depth stacks (follows up unslothai#18442) #### What broke The frozen-prefix skip from unslothai#18442 assumes each decoder layer runs once per forward. Recurrent-depth models run the whole stack several times: Ouro (`ByteDance/Ouro-1.4B`, remote code, `modeling_ouro.py` line 592) loops `self.layers` `total_ut_steps` times (4 by default), and its `OuroDecoderLayer` is a `GradientCheckpointingLayer`, so the skip engages. With adapters only on the upper layers (`finetune_last_n_layers`, `layers_to_transform`) and gradient checkpointing, the skip detached the frozen prefix's inputs and cut layer k-1's output on every pass. From the second pass on, the prefix is fed by the trainable upper layers of the previous pass, so their gradient was dropped. The loss is unchanged, only the gradients are wrong, so nothing warns. Repro (CPU, tiny Llama with the stack run twice per forward, LoRA on layers 2 and 3, reentrant checkpointing, `enable_input_require_grads`), skip on vs off: | Arm | Loss | Worst LoRA grad relative error | |---|---|---| | main | 4.886710 vs 4.886710 | 1.07 | | this branch | 4.886710 vs 4.886710 | 0 | #### Fix `unsloth/models/_frozen_prefix.py`: the cut now fires once per forward. As soon as layer k-1's output has been replaced by the leaf, the prefix hooks are removed and the prefix layers get their checkpointing flags back. Later passes through the prefix run exactly as without the skip. The first pass still runs the frozen prefix once without a graph, so the speedup for normal (single-pass) models is unchanged. The end-of-forward restore is idempotent. #### Tests New `tests/test_frozen_prefix_skip_looped.py`: 1, 2 and 3 passes over the stack; the skip must engage, the loss must be bitwise equal and every LoRA gradient must match the skip-off reference, and the layers must be left with their flags and no hooks. The test loads `_frozen_prefix.py` from its own tree and asserts it. | Arm | transformers 4.57.6 | transformers 5.22.1 | |---|---|---| | main | 2 failed (2 and 3 passes), 2 passed | 2 failed, 2 passed | | this branch | all passed | all passed | The existing `tests/test_frozen_prefix_skip.py` passes on both arms. #### Not covered No GPU run and no real Ouro weights. The change only affects what happens after the cut, which single-pass models never reach. ## Frozen-prefix skip: no per-forward plan walk when nothing can be skipped (follows up unslothai#18442) #### What changed The frozen-prefix skip (unslothai#18442) plans before every training forward with gradient checkpointing on. The plan first builds the set of every trainable parameter in the model, then walks each decoder layer. In the common case, adapters on every layer, the first layer of each stack is trainable, so no frozen prefix can exist and the answer is always "no skip". The full walk still ran on every forward. Host time of the plan on CPU (Xeon Platinum 8559C), PEFT LoRA r=4 on all seven projections, 36 layers, 831 parameters, mean of 50 calls: | Arm | Plan per forward | |---|---| | main | 6.4 ms (of which `model.parameters()` on the PEFT tree: 4.1 ms) | | this branch | 0.01 ms | This runs before the first kernel of the forward, so it is not hidden when the GPU is idle at the start of a step (after a host sync). #### Fix `unsloth/models/_frozen_prefix.py`, `_plan`: each stack is settled from its first trainable layer before anything else. A stack that trains layer 0 (adapters everywhere), or nothing at all (a frozen vision tower), takes a short scan and is skipped. The set of every trainable parameter in the model is only built once a stack with k >= 1 is found. The plan is the same in every case: the old loop also skipped such stacks and only used the model-wide set to validate a k >= 1 stack. #### Tests New `tests/test_frozen_prefix_plan_fast_path.py`: with every layer trained, the plan returns no cut without calling `model.parameters()`. The same holds for a tiny Qwen2-VL with adapters on every text layer and a frozen vision tower. With adapters only on the upper layers it still returns the same cut (layer 2). A trainable norm outside the stack still turns the skip off. The test loads `_frozen_prefix.py` from its own tree and asserts it. | Arm | Result | |---|---| | main | 2 failed (the full walk ran, LLM and VLM), 3 passed | | this branch | 5 passed (transformers 4.57.6 and 5.22.1) | The existing `tests/test_frozen_prefix_skip.py` passes on both arms. #### Not covered No GPU step-time A/B. The saving is host time per forward; whether it shows in wall time depends on whether the GPU is idle when the forward starts. ## Frozen-prefix skip: a planned stack the forward bypasses (follows up unslothai#18442) #### What broke The frozen-prefix skip (unslothai#18442) picks the first stack whose trainable parameters start at layer k >= 1. The model's forward does not always run that stack. Take a VLM where only the top vision block and an untied `lm_head` are trained. The plan picks the vision tower, but a text-only batch never enters it. The cut on layer k-1 then never fired, and the end-of-forward check treated that as a failed cut. It raised `RuntimeError: Unsloth: the frozen-prefix skip could not mark the first trainable layer's input` and disabled the skip, although the forward had skipped nothing. Repro (CPU, tiny random `Qwen2VLForConditionalGeneration`, reentrant checkpointing, text-only batch): | Arm | Result | |---|---| | skip off | trains, `lm_head` grad norm 3.21 | | main, skip on | `RuntimeError` after the forward | | this branch, skip on | trains, loss and `lm_head` grad bitwise equal to skip off | Reproduced on transformers 4.57.6 and 5.22.1. #### Fix `unsloth/models/_frozen_prefix.py`: the cut hook records that layer k-1 ran. The end-of-forward check raises only when that layer ran without being cut. When the stack was bypassed, the forward is treated as not engaged: no error, no count, and flags and hooks are restored as before. Stacked on the looped-stack fix (one cut per forward), which rewrote the same hook. #### Tests New `tests/test_frozen_prefix_skip_bypassed_stack.py`. It asserts the plan really picks the vision tower. Two text-only steps must then match the skip-off loss and `lm_head` gradient bitwise, the engagement counters must stay unchanged, and the vision blocks must keep their flags and carry no hooks. The test loads `_frozen_prefix.py` from its own tree and asserts it. | Arm | transformers 4.57.6 | transformers 5.22.1 | |---|---|---| | main | 1 failed, 1 passed | 1 failed, 1 passed | | this branch | 2 passed | 2 passed | All frozen-prefix tests pass on this branch (16 passed). ## Frozen-prefix skip: stand down under an outer torch.compile (follows up unslothai#18442) #### What broke The frozen-prefix skip (unslothai#18442) registers and removes module hooks on every training forward. When the caller compiles a training step around the model with `torch.compile(..., fullgraph=True)`, Dynamo traces those hooks and cannot trace the hook registration. It fails with `Unsupported: setattr() on unsupported type` at `register_forward_pre_hook` inside the outer pre-hook. This happens on a cold call and also after an eager warmup. Without the skip installed, the same compiled step trains. Repro (CPU, two-layer checkpointed `GradientCheckpointingLayer` stack, bottom layer frozen, `backend="eager"` so only Dynamo is involved, `fullgraph=True, dynamic=True`): | Arm | Cold | After eager warmup | |---|---|---| | skip not installed | trains | trains | | main, skip installed | `Unsupported` | `Unsupported` | | this branch, skip installed | trains, grad bitwise equal | trains, grad bitwise equal | #### Fix `unsloth/models/_frozen_prefix.py`: both model hooks return immediately while `torch.compiler.is_compiling()`, so the forward runs as without the skip. Eager forwards still engage it. #### Tests New `tests/test_frozen_prefix_skip_outer_compile.py`: an eager control that engages the skip. A fullgraph compiled forward and backward, cold and warm, must match the uninstalled compiled run bitwise and leave no hooks or changed flags. The test loads `_frozen_prefix.py` from its own tree and asserts it. | Arm | Result | |---|---| | main | 2 failed (cold, warm), 2 passed | | this branch | 4 passed (torch 2.14.1 with transformers 4.57.6 and 5.22.1, torch 2.10.0) | The existing `tests/test_frozen_prefix_skip.py` passes on both arms. ## Frozen-prefix skip: nested inputs that require grad (follows up unslothai#18442) #### What broke The frozen-prefix skip (unslothai#18442) stands aside when the caller wants a gradient at an input, but it only looked at top-level arguments. transformers also accepts `attention_mask` as a `{layer type: mask}` mapping. A float mask requiring grad inside that mapping was missed. The skip then detached it on the frozen layers below the cut, and its gradient changed. Loss and LoRA gradients stay bitwise equal, so nothing else shows it. Repro (CPU, tiny Qwen3, LoRA on layer 2, non-reentrant checkpointing, `attention_mask={"full_attention": bias}` with `bias.requires_grad=True`): relative L2 error of `bias.grad`, skip on vs off: | Arm | Mask gradient error | |---|---| | main | 1.087850 | | this branch | 0 (the skip stands aside) | #### Fix `unsloth/models/_frozen_prefix.py`: the input check walks nested inputs (`torch.utils._pytree.tree_leaves` over args and kwargs) instead of the top level only. A mapping without grad still engages the skip. Stacked on the outer-compile fix, which edits the lines just above. #### Tests New `tests/test_frozen_prefix_skip_nested_inputs.py`: a mask mapping without grad still engages the skip. A mask mapping requiring grad must make the skip stand aside, with loss, mask gradient and LoRA gradients bitwise equal to skip off. The test loads `_frozen_prefix.py` from its own tree and asserts it. | Arm | transformers 4.57.6 | transformers 5.22.1 | |---|---|---| | main | 1 failed, 2 passed | 1 failed, 2 passed | | this branch | 3 passed | 3 passed | ## Frozen-prefix skip: in-place writes into the skipped hidden states (Qwen3-VL DeepStack) (follows up unslothai#18442) #### What broke The frozen-prefix skip (unslothai#18442) replaced layer k-1's output with `hidden.detach().requires_grad_(True)`, a leaf that requires grad. Reentrant checkpointing needs layer k's input to require grad, but models that write into the hidden states between layers then fail. Qwen3-VL's DeepStack on transformers 4.57 adds visual features in place after the first decoder layers (`hidden_states[visual_pos_masks, :] = local_this`). With the first trainable text layer at index 3 or below, an image batch raised: ``` RuntimeError: a leaf Variable that requires grad is being used in an in-place operation. ``` This happened with both reentrant and non-reentrant checkpointing. transformers 5.22 clones before the write, so the crash is specific to 4.57, but any model that writes in place between layers hits it. Repro (CPU, tiny random `Qwen3VLForConditionalGeneration`, transformers 4.57.6, text layers 2 and 3 trainable, image batch): | Arm | `use_reentrant=False` | `use_reentrant=True` | |---|---|---| | skip off | loss 5.5245 | loss 5.5245 | | main, skip on | `RuntimeError` | `RuntimeError` | | this branch, skip on | loss 5.5245, grads bitwise equal | loss 5.5245, grads bitwise equal | #### Fix `unsloth/models/_frozen_prefix.py`, `_leaf`: the cut subtracts, in place, a zero-dimensional zero that requires grad. The result requires grad but is not a leaf, so later in-place writes are allowed. Subtracting +0.0 is exact for every value, including -0.0, NaN and inf, so the values are unchanged bit for bit. No full-size tensor is allocated, and no full-size `.grad` is left on a leaf after backward. If the output cannot be written in place, for example because it has overlapping memory, the cut falls back to a copy. Stacked on the looped-stack and bypassed-stack fixes, which also edit the cut hook. #### Tests New `tests/test_frozen_prefix_skip_inplace_between_layers.py`: - the cut is exact for -0.0, 0.0, NaN and inf, requires grad, and is not a leaf; - a toy stack that writes in place between layers, with reentrant and non-reentrant checkpointing; - the tiny Qwen3-VL image batch above. Each case must engage the skip and match skip off bitwise. The test loads `_frozen_prefix.py` from its own tree and asserts it. | Arm | transformers 4.57.6 | transformers 5.22.1 | |---|---|---| | main | 5 failed, 1 passed | 3 failed (Qwen3-VL already clones there), 3 passed | | this branch | 6 passed | 6 passed | All frozen-prefix tests pass on this branch. ## Not proven here Recompile count and step time under the default block compile on GPU, and a run with real Qwen3-VL weights.
…qa floor, block SDPA cache tag (unslothai#18631) Follow-up fixes for unslothai#18488, unslothai#18453, unslothai#18462, found while re-checking the PRs merged on 2026-11-19. One commit per fix; every fix has a test that fails on main and passes here. | Fix | Follows up | Severity | |---|---|---| | Attention dispatch: automatic saved attention only inside Unsloth's checkpoint | unslothai#18488 | P2 | | ROCm SDPA self-check: no enable_gqa on torch without it | unslothai#18453 | P2 | | Block SDPA align guard: cache tag also under the override | unslothai#18462 | P2 | ## Tests (this branch vs main `54af93780b`, CPU) - New and changed tests: main 8 failed / 16 passed, this branch 24 passed. Each test loads the code of its own tree. - Neighbouring suites on this branch: attention dispatch, ROCm SDPA check and block SDPA guard suites: 61 passed, 5 skipped. - `prepush_gate.py` passes. ## Attention dispatch: automatic saved attention only inside Unsloth's checkpoint (follows up unslothai#18488) #### Summary Follow-up to unslothai#18488. With `UNSLOTH_GC_SAVE_ATTENTION` unset, automatic saved attention now routes a long training call only where a saved-attention frame can exist. That means under Unsloth's smart checkpoint (`use_gradient_checkpointing = "unsloth"`) and, when the call is traced, only inside Unsloth's own compiled block. #### What broke unslothai#18488 routes every unpacked SDPA training call at or above the threshold through `unsloth_zoo.saved_attention.saved_attention_call`. The zoo creates frames only inside `UnslothCheckpointFunction` (zoo `gradient_checkpointing.py:2074`). With `use_gradient_checkpointing = True` or `False`, `apply_unsloth_gradient_checkpointing` unpatches it, so no frame ever exists. `saved_attention_call` is `@torch.compiler.disable`d and with no frame it just runs the plain call. Inside a compiled decoder block (per-block compile is on by default for FastLanguageModel on torch >= 2.11), each long attention call therefore becomes a graph break that saves nothing. Under a user's `torch.compile(..., fullgraph=True)` it raises `Unsupported: Skip calling torch.compiler.disable()'d function`. This only happens where zoo turns on automatic mode: T4 and A100 from 8K tokens, L4 from 16K. #### Repro (CPU, automatic mode simulated with a threshold of 16, 32-token call, no smart checkpoint) | arm | default compile | `fullgraph=True` | |---|---|---| | automatic mode off (before unslothai#18488) | 0 graph breaks | compiles | | main | 3 graph break records (`Skip calling torch.compiler.disable()'d function`), no frame active | `Unsupported` | | this branch | 0 graph breaks | compiles | #### Fix `_auto_saves_attention` now also requires `_saved_attention_frames_possible()`: - `torch.utils.checkpoint.CheckpointFunction` is `UnslothCheckpointFunction`. Dynamo cannot read a Function class's name, so this read goes through `_constant_probe`. The patch is installed at `get_peft_model` / load time, before any trace. - When traced, `unsloth.models._block_compile._IN_COMPILED_REGION[0]` must be set. That flag marks Unsloth's own block (`fullgraph=False`, where a break is legal) and not a user's compile. zoo's sequence tiling reads the same flag. - In automatic mode the setting must still be `auto` when the call is made. `UNSLOTH_GC_SAVE_ATTENTION=0` set after `import unsloth` stops zoo's frames (`new_saved_attention_frame`), but before this change it did not stop the routing, so it still produced a graph break per layer inside Unsloth's own block. The explicit `=1` / `offload` setting (min_seq None) is unchanged. #### Tests New `tests/test_attention_dispatch_saved_attention_scope.py` (CPU): - automatic mode routes only under the smart checkpoint; - a user's compile has 0 graph breaks with and without the smart checkpoint, and `fullgraph=True` compiles; - inside Unsloth's block under the smart checkpoint the call is still routed; - the explicit setting still routes; - `UNSLOTH_GC_SAVE_ATTENTION=0` / `false` set after import stops routing and leaves 0 graph breaks inside Unsloth's block. `tests/test_attention_dispatch_saved_attention.py`: the two automatic-mode routing tests now install `UnslothCheckpointFunction`, as a real "unsloth" run does. Command (per worktree, unsloth_zoo main on `PYTHONPATH`): `python -m pytest -o addopts= -m "not server and not native_mxc" -p no:cacheprovider -q tests/test_attention_dispatch_saved_attention_scope.py tests/test_attention_dispatch_saved_attention.py`. Each arm imports its own tree. | arm | result | |---|---| | main (635532f) | 6 failed, 14 passed | | this branch | 20 passed | Wider suites (`tests/*attention*.py`, `tests/test_sdpa*.py`, `tests/utils/test_rocm_sdpa_check.py`): main 2 failed / 255 passed / 302 skipped. This branch: 2 failed / 261 passed / 302 skipped. The same two failures in `test_flash_attention_sub_config_fallback.py` show up on main. #### Not proven here - No GPU run. Step time for `use_gradient_checkpointing = True` at 8K on an A100 or T4 (main vs this branch) needs a real card. The smart-checkpoint path is unchanged, so unslothai#18488's measured gains still apply. - Layers that "unsloth" checkpointing leaves unwrapped (frozen bottom layers skipped by unslothai#18442) still reach the routed call with no frame. This change does not cover them. ## ROCm SDPA self-check: no enable_gqa on torch without it (follows up unslothai#18453) #### Summary Follow-up to unslothai#18453. On torch 2.4, the declared floor, the ROCm SDPA self-check refused AOTriton flash for every Unsloth attention call on an RDNA GPU. The kernel was never the cause: the check sent an argument that torch 2.4 does not have. #### What broke The flash child in `unsloth/utils/rocm_sdpa_check.py` runs a `segments_gqa` case that calls `F.scaled_dot_product_attention(..., enable_gqa=True)`. torch added `enable_gqa` in 2.5. On 2.4 the call raises `TypeError: scaled_dot_product_attention() got an unexpected keyword argument 'enable_gqa'`. The child records any exception other than "No available kernel" or out of memory as a failed kernel case, so the report says `ok: false` and `rocm_sdpa_verdict` refuses flash for that device. Unsloth itself never passes `enable_gqa` when SDPA lacks it (`SDPA_HAS_GQA` in `attention_dispatch.py`), so no real call can reach that layout there. #### Repro (CPU) The real child script runs in a subprocess. CUDA calls are mapped to CPU (torch's CPU flash kernel, which is correct), and `F.scaled_dot_product_attention` is replaced by one that rejects `enable_gqa`, as torch 2.4's operator does. | arm | flash child report | |---|---| | main (635532f) | `ok: false`, ran 8, every failure is `segments_gqa ...: unexpected keyword argument 'enable_gqa'` | | this branch | `ok: true`, ran 4 (expanded K / V segments, fp16 and bf16, head dims 64 and 128) | #### Fix When `enable_gqa` is not in `F.scaled_dot_product_attention.__doc__`, the child drops the `segments_gqa` case. That is the same test `attention_dispatch` uses. The expanded K / V and masked cases still run, so a broken kernel is still refused. #### Tests New `tests/utils/test_rocm_sdpa_check_no_gqa.py` (CPU). Command (per worktree): `python -m pytest -o addopts= -m "not server and not native_mxc" -p no:cacheprovider -q tests/utils/test_rocm_sdpa_check_no_gqa.py tests/utils/test_rocm_sdpa_check.py`. Each arm imports its own tree. | arm | result | |---|---| | main | 1 failed, 24 passed, 2 skipped | | this branch | 25 passed, 2 skipped | #### Not proven here - No ROCm torch 2.4 hardware run, and no claim about which RDNA archs torch 2.4 offers AOTriton flash on. Where it does not offer flash, this change makes no difference. - torch >= 2.5 keeps the `segments_gqa` case unchanged. ## Block SDPA align guard: cache tag also under the override (follows up unslothai#18462) #### What broke unslothai#18462 adds the cache tag `unsloth/efficient-backward-guard` so that graphs compiled without the efficient-backward guard are not served again. The patched SDPA lowering is not part of the FX / AOT cache key. `UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1` returned before adding that tag. On CUDA torch < 2.14, a run with the override therefore has the same cache key as a run of the same Unsloth version from before the tag existed. The version string is 2026.11.7 both before and after unslothai#18462. That older run compiled the efficient backward without the guard. A user who set the override as the workaround for the `attn_bias is not correctly aligned` fault, and kept it after updating, keeps being served the faulting backward from a warm cache. The PR's own evidence notes the override was not a reliable workaround once a failing run had warmed the cache. #### Fix `unsloth/models/_block_compile.py`, `_sdpa_alignment_without_guard`: under the override on an affected torch, add the same cache tag before returning. The lowering stays stock as before. Torch 2.14+ and ROCm are unchanged. #### Tests New `tests/test_block_sdpa_align_guard_override_cache_tag.py` (CPU, no compile): with the override set, the lowering must stay untouched. The tag must be added exactly once on an affected torch and not on 2.14+. The test loads `_block_compile.py` from its own tree and asserts it. | Arm | Result | |---|---| | main | 1 failed (`torch_lt_2_14`), 2 passed | | this branch | 3 passed on torch 2.14.1; on torch 2.4.1 (no `cache_key_tag`) the tag tests skip with that reason | `tests/test_block_sdpa_efficient_backward_guard.py` passes on both arms. #### Not covered No warm-cache GPU run of the fault itself. ## Not proven here Step time and memory of long-sequence SFT with and without automatic saved attention; ROCm hardware (gfx1151 / gfx942) for the self-check; torch 2.14 on GPU for the align guard.
…nslothai#18745) ## Problem Under pipeline parallel, the frozen-prefix skip from unslothai#18442 cuts the graph at the first activation the later stage receives from the stage before it. Every stage except the last then trains nothing. On Kaggle 2xT4, Gemma-4 PP=2 losses drift from the 1 GPU run after the warmup steps. E4B 4-bit is 0.81 off at step 6 and E2B 4-bit 0.91 off at step 5. Root cause: - On stage 1, the layers that stage 0 owns are `_PPPassThrough` stand-ins with no parameters. - `_frozen_prefix._plan` therefore sees stage 1's first own layer as "the first trainable layer" and detaches its input. That input is the activation from stage 0. - The gradient never reaches stage 0, so its decoder-layer LoRA (19.17M of 34.88M trainable parameters on E4B) never updates. - 1 GPU, DDP and FSDP2 train layer 0, so the skip never engages there. That is why only PP drifted. - The step-1 gradient norm shows it directly: 2.78 under PP vs 5.12 on 1 GPU (E4B 4-bit). ## Fix - `_PPPassThrough` carries `_unsloth_pipeline_stand_in = True`. - `_plan` makes no cut, on any layer stack, while the model holds a stand-in. A later stage would otherwise cut at the activations it receives, and a non-last stage leaves its forward by raising, past the hook cleanup. This works whether the stages are split before or after `get_peft_model`. - Off the pipeline path nothing changes. ## Results Kaggle 2xT4, fp16, unsloth main 15a985f / zoo 9b3fccb, 25 steps, same harness / data / seed. Each cell is the max over steps of |PP loss - median 1 GPU loss|, all from one kernel: | | 1 GPU A/A noise | main PP | this PR PP | step-1 grad_norm, 1 GPU / main / this PR | | --- | --- | --- | --- | --- | | Gemma-4 E4B 4-bit | 0.0165 | 0.810 | 0.0085 | 5.12 / 2.78 / 4.68 | | Gemma-4 E2B 4-bit | 0.0227 | 0.914 | 0.219 (step 4) | 94.3 / 6.50 / 11.85 | - With the fix, the skip makes 0 cuts on both ranks. On main, rank 1 cut 200 forwards. - E2B still sits 0.219 off at step 4. By step 25 the gap is about 0.04. Its 1 GPU arm has a step-1 gradient spike (grad_norm 94.3), which looks like the fp16-sensitive spot from unslothai#18294 on the 1 GPU side. That is separate from this fix and was not isolated here. - Ruled out on the same kernels: - the fp16 scaler: PP with `UNSLOTH_RETURN_LOGITS=1` (no fused CE) drifted the same; - the 1F1B default: GPipe drifted the same; - the NF4 dequant cache: it never engaged. ## Tests - `tests/test_pp_frozen_prefix_gloo.py`: tiny Gemma-4, PP=2 over CPU gloo, GPipe and 1F1B, against one process. It fails on main (rank 1 cuts 8 forwards, gradient error 2.11) and passes here (0 cuts, gradients within 4.4e-4). - Existing frozen-prefix and PP suites: 107 passed / 1 skipped, the same on main and here. - On transformers 4.57.6 the new file skips (no Gemma-4 there). The other frozen-prefix suites pass. ## Not covered - The GPU proof ran the two changed files overlaid on a main install, not an install of this branch. - Only Gemma-4 E2B / E4B 4-bit, fp16 on T4, PP=2 ran on GPU. Not run: bf16, 16-bit or larger models, PP above 2, and several stages per GPU. - Under PP the skip is now off on every stage. A PP run that trains only the top layers loses the skip's saving there.
Summary
With adapters only on the upper layers (
finetune_last_n_layers,layers_to_transform), every frozen decoder layer below the first adapter was still checkpointed, replayed and backpropagated: the embedding output is forced to require grad, so autograd walks the whole frozen prefix. On B200 a frozen layer's attention ran 3 times per step on main and once with this change.New
unsloth/models/_frozen_prefix.py, installed where_unsloth_install_pretrain_detectoris installed (llama.py,vision.py). It engages only when every trainable parameter sits at or above layer k (k >= 1) of one decoder stack (or in an untied output head): layers below k then run once without a graph and layer k's input becomes the leaf that receives the gradient. It stays off with block swap, without gradient checkpointing, and when the caller passesinputs_embedsthat require grad.UNSLOTH_FROZEN_PREFIX_SKIP=0turns it off.Results
Colab L4, Llama-3.2-3B 4-bit,
finetune_last_n_layers=8, seq 2048, batch 2, 3 base and 3 head runs interleaved (median, spread):Step-0 loss bitwise equal in all 6 runs; later steps differ by 2-3e-4, the same as base vs base (nondeterministic GPU backward).
Correctness on B200 (real Unsloth, 5 configs: Qwen3 with "unsloth" and True checkpointing, fp16, 4-bit, Gemma3 through
FastModel): loss and every LoRA gradient bitwise equal to main.Tests
tests/test_frozen_prefix_skip.py(9 tests: frozen layers run once and grads match, trainable below the cut keeps the full backward, adapter on layer 0 / no-grad forward untouched,inputs_embedsrequiring grad keep their gradient, no checkpointing / block swap untouched), passing on transformers 4.57.6, 5.22.1 and 5.23.0. Existing gradient checkpointing suites: 161 passed / 3 skipped on head and base.Not covered
T4 / A100 / G4 timing; multi-GPU, pipeline parallel and block swap (the skip stays off there by design); GRPO / DPO end to end.