Skip to content

Frozen prefix skip: looped stacks, bypassed stacks, outer fullgraph compile, Qwen3-VL in-place writes - #18632

Merged
danielhanchen merged 6 commits into
mainfrom
kr4-frozen-prefix-skip
Nov 20, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
kr4-frozen-prefix-skip

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up fixes for #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 #18442 P1
Frozen-prefix skip: no per-forward plan walk when nothing can be skipped #18442 P2
Frozen-prefix skip: a planned stack the forward bypasses #18442 P1
Frozen-prefix skip: stand down under an outer torch.compile #18442 P1
Frozen-prefix skip: nested inputs that require grad #18442 P2
Frozen-prefix skip: in-place writes into the skipped hidden states (Qwen3-VL DeepStack) #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 #18442)

What broke

The frozen-prefix skip from #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 #18442)

What changed

The frozen-prefix skip (#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 #18442)

What broke

The frozen-prefix skip (#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 #18442)

What broke

The frozen-prefix skip (#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 #18442)

What broke

The frozen-prefix skip (#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 #18442)

What broke

The frozen-prefix skip (#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.

…per adapters' gradients

Recurrent-depth models (Ouro runs self.layers total_ut_steps times) feed the
frozen prefix from the trainable upper layers on every pass after the first.
The skip kept detaching those inputs and cutting layer k-1's output on each
pass, so the upper adapters only got the last pass's gradient (worst LoRA
grad relative error 1.07 on a 2-loop tiny Llama, loss unchanged).

The cut now releases the prefix hooks and restores the checkpointing flags
as soon as it fires; later passes run exactly as without the skip.
…ing the model

The plan runs before every training forward with gradient checkpointing.
It built the set of every trainable parameter in the model first, then
walked every layer of every stack, even when no stack can have a frozen
prefix: 6.4 ms per forward on a 36-layer PEFT LoRA model on CPU (other
reports: 6 to 23 ms up to 80 layers or 64 experts). Each stack is now
settled from its first trainable layer: a stack training layer 0 (adapters
everywhere) or nothing (a frozen vision tower) costs a short scan, and the
model-wide set is only built once a stack with k >= 1 is found. Same plan
in every case; 0.01 ms in the all-layers case.
…t an error

The plan can pick a stack the forward bypasses: training only the top vision
block and an untied head of a VLM, a text-only batch never enters the vision
tower. The cut then never fired and the end-of-forward check raised (and
disabled the skip), although nothing was skipped. The check now raises only
when the cut layer ran without being cut.
The skip registers and removes module hooks on every training forward.
Dynamo cannot trace that, so a training step compiled with fullgraph=True
around a model with the skip installed failed with
"setattr() on unsupported type" (cold and after an eager warmup). While
compiling, both hooks now return at once and the forward runs as without
the skip.
…nputs

The skip stands aside when the caller wants a gradient at an input, but it
only checked top-level arguments. transformers takes attention_mask as a
{layer type: mask} mapping; a mask requiring grad inside it was detached
below the cut and its gradient changed (relative L2 error 1.09 on a tiny
Qwen3), with loss and LoRA gradients unchanged. The check now walks the
nested inputs.
The cut replaced layer k-1's output with a leaf that requires grad. Models
that write into the hidden states between layers then fail: Qwen3-VL's
DeepStack (transformers 4.57) adds visual features in place after the first
decoder layers, so an image batch with the first trainable layer at index 3
or below raised "a leaf Variable that requires grad is being used in an
in-place operation" with reentrant and non-reentrant checkpointing.

The cut now subtracts a zero that requires grad in place: the result requires
grad but is not a leaf, values are unchanged bit for bit (-0.0 and NaN
included), and nothing is allocated. It also no longer keeps a full-size .grad
on a leaf after backward.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 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-20T13:56:56.760989Z 44eeebd 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 review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 44eeebd0c8

ℹ️ 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 9f5a4c4 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the kr4-frozen-prefix-skip branch November 20, 2026 15:24
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