Skip to content

RMSNorm: restore in-place dX for pre-norm decoder norms - #13984

Merged
danielhanchen merged 4 commits into
mainfrom
dh/rmsnorm-reuse-grad
Oct 16, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
dh/rmsnorm-reuse-grad

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

#13888 made every non-Gemma Fast_RMS_Layernorm.backward write 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) to Fast_RMS_Layernorm and fast_rms_layernorm:

Peak memory for norm, frozen projection and backward (bf16, 4096 tokens, bytes above the pre-step allocation):

hidden before #13888 main this PR
2048 57,986,560 68,174,848 57,986,560
4096 114,814,464 135,283,712 114,814,464
8192 228,470,272 269,501,440 228,470,272

The same numbers hold with UNSLOTH_RMSNORM_SAVE_OUTPUT=1. Gradients are bitwise identical across all arms.

Tests:

  • New test_rms_layernorm_reuse_grad_matches_and_saves_a_buffer (fp32/fp16/bf16, Gemma and non-Gemma, save-output on and off). It checks that reuse_grad gives bitwise-identical dX and lowers the backward peak by exactly one activation for non-Gemma.
  • The existing norm, save-output and QK norm + RoPE tests pass.

Not covered: speed timing, full-size models, T4 and ROCm.

#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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-16T12:23:26.922247Z 7704abc New commits
🔒 Security Review ⚠️ Failed 2026-10-16T08:03:11.814463Z b198dab PR opened
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/llama.py
Comment on lines +1507 to +1509
hidden_states = fast_rms_layernorm(
self.norm, hidden_states, gemma = IS_GEMMA, reuse_grad = True
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 6a3156a426

ℹ️ 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".

# Conflicts:
#	unsloth/kernels/rms_layernorm.py
@danielhanchen
danielhanchen merged commit 133489e into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/rmsnorm-reuse-grad branch October 16, 2026 13:48
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 18, 2026
…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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant