Repository navigation
RMSNorm: restore in-place dX for pre-norm decoder norms - #13984
Conversation
#13888 gave every non-Gemma RMSNorm backward a fresh dX so a shared or caller-owned incoming grad stays intact, but that costs one activation at the backward peak. Pre-norm decoder norms (input, post-attention, pre-FF, final norm, unfused Qwen3 QK norm) only feed layers that return a fresh grad, so they pass reuse_grad = True and get the pre-#13888 kernel calls and peak memory. Every other caller keeps the fresh buffer.
|
@codex review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b198dabf46
ℹ️ 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".
| hidden_states = fast_rms_layernorm( | ||
| self.norm, hidden_states, gemma = IS_GEMMA, reuse_grad = True | ||
| ) |
There was a problem hiding this comment.
Keep the final norm gradient buffer private
LlamaModel_fast_forward exposes this normalized tensor directly as last_hidden_state, so it is not guaranteed to feed a layer whose backward creates a fresh gradient. For a non-Gemma base model, torch.autograd.grad(model(...).last_hidden_state, inputs, grad_outputs=go) can pass the caller-owned contiguous go straight to this RMSNorm; reuse_grad=True then overwrites it in place, silently corrupting a gradient tensor the caller may reuse. Keep reuse disabled for the public final norm, while retaining it for internal pre-norms whose consumers provide private buffers.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Valid, fixed in 6a3156a: the final norm now reuses the incoming gradient only when Unsloth's CausalLM forward runs the backbone without output_hidden_states (the head, or Unsloth's own GRPO / DPO hidden state losses, are the only readers). A plain base model call and output_hidden_states keep a private buffer, so a caller's grad_outputs is never overwritten. Test: test_final_norm_reuses_grad_only_under_the_causal_lm_head, which checks an external grad_outputs stays unmodified.
A base model hands the final norm's output out as last_hidden_state, so a caller's grad_outputs reached the norm backward and reuse_grad overwrote it. The CausalLM forwards (llama and mistral) now mark the backbone call when they are the only reader of that output: no output_hidden_states, and under UNSLOTH_RETURN_HIDDEN_STATES only with a last-token slice. Otherwise the final norm keeps its own dX buffer. Decoder pre-norms keep reuse_grad.
UNSLOTH_RETURN_HIDDEN_STATES is set only by Unsloth's own GRPO, DPO and GKD trainers and zoo's GRPO loss, which feed the hidden states to a chunked lm_head loss whose backward returns a fresh grad. Allow final-norm reuse there regardless of slicing, so those runs match the pre-#13888 peak. Only a plain base-model call and output_hidden_states keep the norm's own buffer. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
# Conflicts: # unsloth/kernels/rms_layernorm.py
…eturned to the caller (unslothai#14139) Follow-up to unslothai#13984. ## Problem unslothai#13984 lets the final RMSNorm write dX over the incoming gradient (`reuse_grad`) whenever `output_hidden_states` is false, on the premise that only lm_head or the fused CE loss read the norm's output. With `UNSLOTH_RETURN_HIDDEN_STATES=1` the CausalLM forward instead returns the normalized hidden states to the caller as `.logits`. The caller then owns that gradient, and can share it with another branch: for example `torch.autograd.grad(hidden + inputs_embeds, inputs_embeds, grad_outputs)` hands the same tensor to both inputs of the add. The norm's backward overwrote it, so the caller's `grad_outputs` changed (max 6.16 on a tiny Qwen3) and the shared branch's dX was off by 6.0. Forward outputs were identical. Unsloth's own GRPO / DPO / fused CE consumers are not affected: each hands the norm a fresh gradient (the zoo chunked log-softmax calls `autograd.grad`, the fused preference loss starts from `zeros_like`, fused CE multiplies out of place). But the variable is process wide, so once a GRPO trainer sets it, any later caller in the same process that reads the returned hidden states can hit this. ## Fix `_run_backbone` (used by the Llama-family CausalLM forward and `mistral.py`) only enables final-norm reuse when hidden states are not returned to the caller: neither `output_hidden_states` nor `UNSLOTH_RETURN_HIDDEN_STATES=1`. The decoder-layer norms are unchanged. ## Tests `tests/test_norm_backward_grad_alias.py`: new `test_returned_hidden_states_leave_caller_and_shared_grads_alone`, and unslothai#13984's own assertion for this path flipped. Current main: 2 failed, 42 passed. This branch: 44 passed (GPU-marked tests included). Peak memory is byte-identical to main for default SFT and for a GRPO-style returned-hidden-states loss on tiny Llama and Qwen3, so unslothai#13984's SFT memory saving is kept. Reuse on vs off on the default path stays bitwise identical in gradients, losses and generated tokens (4-bit and 16-bit, gradient checkpointing on and off, full finetuning).
#13888 made every non-Gemma
Fast_RMS_Layernorm.backwardwrite dX into a fresh buffer, so a shared or caller-owned incoming gradient is no longer overwritten. That buffer is one activation-sized tensor. When the norm backward runs at the step's peak, it raises peak memory. One example is a norm followed by a frozen projection.This adds
reuse_grad(default False) toFast_RMS_Layernormandfast_rms_layernorm:With
reuse_grad = True, a non-Gemma backward writes dX over dY, as before Fix RMSNorm and LayerNorm backward overwriting the incoming gradient #13888. Gemma and the compiled op are unchanged, since they already used a separate buffer.These pre-norm decoder norms pass it:
Their outputs only feed projections, RoPE or attention, whose backward returns a fresh gradient, so the default training path again makes the same kernel calls as before Fix RMSNorm and LayerNorm backward overwriting the incoming gradient #13888.
Every other caller keeps the fresh buffer and the Fix RMSNorm and LayerNorm backward overwriting the incoming gradient #13888 fix: patched
LlamaRMSNorm, generic norm forwards, and direct.apply.The
UNSLOTH_RMSNORM_SAVE_OUTPUTpath (RMSNorm: opt-in saving of the norm output instead of its input (UNSLOTH_RMSNORM_SAVE_OUTPUT) #13868) composes with this. Backward reads the saved Y, never dY. The fused Qwen3 QK norm + RoPE path (Fused Qwen3 q_norm / k_norm RMSNorm + RoPE Triton kernel (opt-in) #13890) is untouched.Peak memory for norm, frozen projection and backward (bf16, 4096 tokens, bytes above the pre-step allocation):
The same numbers hold with
UNSLOTH_RMSNORM_SAVE_OUTPUT=1. Gradients are bitwise identical across all arms.Tests:
test_rms_layernorm_reuse_grad_matches_and_saves_a_buffer(fp32/fp16/bf16, Gemma and non-Gemma, save-output on and off). It checks thatreuse_gradgives bitwise-identical dX and lowers the backward peak by exactly one activation for non-Gemma.Not covered: speed timing, full-size models, T4 and ROCm.