Repository navigation
Frozen prefix skip: looped stacks, bypassed stacks, outer fullgraph compile, Qwen3-VL in-place writes - #18632
Merged
Merged
Conversation
…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.
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. |
Member
Author
|
@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". |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
Tests (this branch vs main
54af93780b, CPU)prepush_gate.pypasses.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.pyline 592) loopsself.layerstotal_ut_stepstimes (4 by default), and itsOuroDecoderLayeris aGradientCheckpointingLayer, 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: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.pyfrom its own tree and asserts it.The existing
tests/test_frozen_prefix_skip.pypasses 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:
model.parameters()on the PEFT tree: 4.1 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 callingmodel.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.pyfrom its own tree and asserts it.The existing
tests/test_frozen_prefix_skip.pypasses 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_headare 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 raisedRuntimeError: Unsloth: the frozen-prefix skip could not mark the first trainable layer's inputand disabled the skip, although the forward had skipped nothing.Repro (CPU, tiny random
Qwen2VLForConditionalGeneration, reentrant checkpointing, text-only batch):lm_headgrad norm 3.21RuntimeErrorafter the forwardlm_headgrad bitwise equal to skip offReproduced 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 andlm_headgradient bitwise, the engagement counters must stay unchanged, and the vision blocks must keep their flags and carry no hooks. The test loads_frozen_prefix.pyfrom its own tree and asserts it.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 withUnsupported: setattr() on unsupported typeatregister_forward_pre_hookinside 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
GradientCheckpointingLayerstack, bottom layer frozen,backend="eager"so only Dynamo is involved,fullgraph=True, dynamic=True):UnsupportedUnsupportedFix
unsloth/models/_frozen_prefix.py: both model hooks return immediately whiletorch.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.pyfrom its own tree and asserts it.The existing
tests/test_frozen_prefix_skip.pypasses 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_maskas 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}withbias.requires_grad=True): relative L2 error ofbias.grad, skip on vs off:Fix
unsloth/models/_frozen_prefix.py: the input check walks nested inputs (torch.utils._pytree.tree_leavesover 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.pyfrom its own tree and asserts it.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: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):use_reentrant=Falseuse_reentrant=TrueRuntimeErrorRuntimeErrorFix
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.gradis 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:Each case must engage the skip and match skip off bitwise. The test loads
_frozen_prefix.pyfrom its own tree and asserts it.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.