Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

RMSNorm: opt-in saving of the norm output instead of its input (UNSLOTH_RMSNORM_SAVE_OUTPUT) (#13868)

Daniel Han8c9dc1a3b0e8
diff --git a/tests/test_rmsnorm_save_output.py b/tests/test_rmsnorm_save_output.py
new file mode 100644
index 00000000000..429b0dfa313
--- /dev/null
+++ b/tests/test_rmsnorm_save_output.py
@@ -0,0 +1,164 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""UNSLOTH_RMSNORM_SAVE_OUTPUT: Fast_RMS_Layernorm saves its output Y instead of X and rebuilds
+normed = Y / W in backward, so the norm and the LoRA layer after it share one saved activation."""
+
+import pytest
+import torch
+
+from unsloth.kernels import rms_layernorm
+
+
+def test_guard_rejects_weights_y_cannot_be_divided_by():
+ ok = rms_layernorm._save_output_ok
+ w = torch.full((8,), 0.5)
+ assert ok(w, False, torch.bfloat16)
+ w2 = w.clone()
+ w2[3] = 0
+ assert not ok(w2, False, torch.bfloat16)
+ w3 = torch.zeros(8)
+ w3[1] = -1
+ assert not ok(w3, True, torch.bfloat16)
+ # fp16 Y goes subnormal long before bf16 / fp32 Y does.
+ w4 = torch.full((8,), 1e-4)
+ assert not ok(w4, False, torch.float16)
+ assert ok(w4, False, torch.bfloat16)
+ w5 = w.clone()
+ w5[0] = float("nan")
+ assert not ok(w5, False, torch.float32)
+
+
+def test_guard_cache_follows_in_place_updates():
+ w = torch.full((8,), 0.5)
+ assert rms_layernorm._save_output_ok(w, False, torch.bfloat16)
+ w.zero_()
+ assert not rms_layernorm._save_output_ok(w, False, torch.bfloat16)
+
+
+cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason = "needs CUDA")
+
+
+def _run(
+ x,
+ w,
+ gemma,
+ save_output,
+ monkeypatch,
+ enabled = True,
+):
+ monkeypatch.setattr(rms_layernorm, "_SAVE_OUTPUT", enabled)
+ x = x.detach().clone().requires_grad_(True)
+ saved = []
+
+ def pack(t):
+ saved.append(t)
+ return t
+
+ with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
+ y = rms_layernorm.Fast_RMS_Layernorm.apply(x, w, 1e-6, gemma, save_output)
+ g = torch.randn(y.shape, device = y.device, generator = torch.Generator(y.device).manual_seed(1))
+ y.backward(g.to(y.dtype))
+ return y, x.grad, saved
+
+
+def _ref_grad(
+ x,
+ w,
+ gemma,
+ eps = 1e-6,
+):
+ x64 = x.detach().double().requires_grad_(True)
+ w64 = w.double() + 1 if gemma else w.double()
+ y = x64 * torch.rsqrt(x64.pow(2).mean(-1, keepdim = True) + eps) * w64
+ g = torch.randn(y.shape, device = y.device, generator = torch.Generator(y.device).manual_seed(1))
+ y.backward(g.to(x.dtype).double())
+ return x64.grad
+
+
+@cuda
[email protected]("gemma", [False, True])
[email protected]("dtype", [torch.float16, torch.bfloat16, torch.float32])
[email protected]("dim", [64, 127, 1000, 4097])
+def test_save_output_grads_and_storage(gemma, dtype, dim, monkeypatch):
+ gen = torch.Generator("cuda").manual_seed(0)
+ x = (torch.randn(3, 37, dim, device = "cuda", generator = gen) * 2 + 0.3).to(dtype)
+ w = torch.randn(dim, device = "cuda", generator = gen) * 0.1 + (0 if gemma else 1)
+ w = w.to(dtype)
+ y0, dx0, saved0 = _run(x, w, gemma, False, monkeypatch)
+ y1, dx1, saved1 = _run(x, w, gemma, True, monkeypatch)
+ assert torch.equal(y0, y1)
+ # Old path saves X, new path saves the returned Y itself (shared storage, no extra bytes).
+ assert saved0[0].data_ptr() != y0.data_ptr()
+ assert saved1[0].data_ptr() == y1.data_ptr()
+ ref = _ref_grad(x, w, gemma)
+ err0 = (dx0.double() - ref).abs().max().item()
+ err1 = (dx1.double() - ref).abs().max().item()
+ scale = ref.abs().max().item()
+ # Y / W carries one rounding of Y: at most a few output ulps over the X path.
+ assert err1 <= 2 * err0 + 4 * torch.finfo(dtype).eps * scale, (err0, err1, scale)
+ assert torch.isfinite(dx1).all()
+
+
+@cuda
[email protected]("gemma", [False, True])
+def test_save_output_off_or_unsafe_is_bitwise_old_path(gemma, monkeypatch):
+ gen = torch.Generator("cuda").manual_seed(0)
+ x = torch.randn(2, 33, 256, device = "cuda", generator = gen).to(torch.bfloat16)
+ w = (torch.randn(256, device = "cuda", generator = gen) * 0.1 + (0 if gemma else 1)).to(
+ torch.bfloat16
+ )
+ y0, dx0, _ = _run(x, w, gemma, False, monkeypatch)
+ y1, dx1, saved = _run(x, w, gemma, True, monkeypatch, enabled = False)
+ assert torch.equal(dx0, dx1) and saved[0].data_ptr() != y1.data_ptr()
+ # A weight Y cannot be divided by falls back to saving X.
+ w_bad = w.clone()
+ w_bad[5] = -1 if gemma else 0
+ y2, dx2, _ = _run(x, w_bad, gemma, False, monkeypatch)
+ y3, dx3, saved = _run(x, w_bad, gemma, True, monkeypatch)
+ assert torch.equal(dx2, dx3) and saved[0].data_ptr() != y3.data_ptr()
+ w_train = w.clone().requires_grad_(True)
+ y4, _, saved = _run(x, w_train, gemma, True, monkeypatch)
+ assert saved[0].data_ptr() != y4.data_ptr()
+
+
+@cuda
+def test_lora_does_not_overwrite_a_saved_norm_output(monkeypatch):
+ from unsloth.kernels import fast_lora
+
+ x = torch.randn(2, 8, 128, device = "cuda", dtype = torch.float16)
+ w = torch.ones(128, device = "cuda", dtype = torch.float16)
+ for enabled in (False, True):
+ monkeypatch.setattr(rms_layernorm, "_SAVE_OUTPUT", enabled)
+ y = rms_layernorm.Fast_RMS_Layernorm.apply(
+ x.clone().requires_grad_(True), w, 1e-6, False, True
+ )
+ # LoRA_QKV / LoRA_MLP write dX into their input X in backward unless the norm saved it.
+ assert fast_lora._may_overwrite_input(y) is not enabled
+
+
+@cuda
+def test_views_of_a_saved_norm_output_are_not_overwritten(monkeypatch):
+ # The tiled MLP backward feeds the LoRA MLP chunk views of its saved input: split + unsqueeze.
+ from unsloth.kernels import fast_lora
+
+ x = torch.randn(2, 8, 128, device = "cuda", dtype = torch.float16)
+ w = torch.ones(128, device = "cuda", dtype = torch.float16)
+ for enabled in (False, True):
+ monkeypatch.setattr(rms_layernorm, "_SAVE_OUTPUT", enabled)
+ y = rms_layernorm.Fast_RMS_Layernorm.apply(
+ x.clone().requires_grad_(True), w, 1e-6, False, True
+ )
+ chunks = torch.split(y.view(-1, 128), [5, 11], dim = 0)
+ for chunk in chunks:
+ assert fast_lora._may_overwrite_input(chunk.unsqueeze(0)) is not enabled
+
+
+@cuda
+def test_guard_does_not_sync_inside_cuda_graph_capture():
+ w = torch.full((8,), 0.5, device = "cuda")
+ graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(graph):
+ # Inside capture the check would need .item(): fall back to saving X, cache nothing.
+ assert not rms_layernorm._save_output_ok(w, False, torch.bfloat16)
+ assert rms_layernorm._save_output_ok(w, False, torch.bfloat16)
diff --git a/unsloth/kernels/fast_lora.py b/unsloth/kernels/fast_lora.py
index fdb4b981c1a..b7ec6e119c6 100644
--- a/unsloth/kernels/fast_lora.py
+++ b/unsloth/kernels/fast_lora.py
@@ -73,6 +73,18 @@ def _has_activation_fake_quantizer(proj):
return False
+def _may_overwrite_input(X):
+ # Backward writes dX into X; not when an RMSNorm saved X (its output) for its own backward,
+ # including through a view of it (tiled MLP chunks).
+ if _is_compiling():
+ return True
+ base = X._base
+ return not (
+ getattr(X, "_unsloth_rmsnorm_saved", False)
+ or (base is not None and getattr(base, "_unsloth_rmsnorm_saved", False))
+ )
+
+
class LoRA_MLP(torch.autograd.Function):
"""
### LoRA weights
@@ -156,7 +168,7 @@ class LoRA_MLP(torch.autograd.Function):
_backward_function,
)
ctx.save_for_backward(gateA, gateB, upA, upB, downA, downB, X, e, g)
- ctx.inplace = inplace
+ ctx.inplace = inplace and _may_overwrite_input(X)
return i
@staticmethod
@@ -484,7 +496,7 @@ class LoRA_QKV(torch.autograd.Function):
VA,
VB,
)
- ctx.inplace = inplace
+ ctx.inplace = inplace and _may_overwrite_input(X)
return Q, K, V
@staticmethod
diff --git a/unsloth/kernels/rms_layernorm.py b/unsloth/kernels/rms_layernorm.py
index 2bd30a98c14..b31e4116158 100644
--- a/unsloth/kernels/rms_layernorm.py
+++ b/unsloth/kernels/rms_layernorm.py
@@ -83,7 +83,9 @@ def _rms_backward_row(
GEMMA: tl.constexpr,
dW_acc,
TRAIN_W: tl.constexpr,
+ FROM_Y: tl.constexpr,
):
+ # FROM_Y: X holds the forward output Y, and normed = Y / W (r still scales dX).
dY += row_idx * dY_row_stride
X += row_idx * X_row_stride
r += row_idx * r_row_stride
@@ -98,7 +100,11 @@ def _rms_backward_row(
W_row = tl.load(W + col_offsets, mask = mask, other = 0).to(tl.float32)
inv_var = tl.load(r).to(tl.float32)
- normed = X_row * inv_var
+ if FROM_Y:
+ # Masked lanes would be 0 / 0.
+ normed = tl.where(mask, X_row / (W_row + 1.0 if GEMMA else W_row), 0.0)
+ else:
+ normed = X_row * inv_var
if TRAIN_W:
# dW before the row sum so the fp32 dY row is not held across it (fewer registers, all programs resident).
if GEMMA:
@@ -138,6 +144,7 @@ def _rms_layernorm_backward(
LONG_INDEXING: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
TRAIN_W: tl.constexpr,
+ FROM_Y: tl.constexpr,
):
"""
Fast RMS Layernorm kernel for the backward pass
@@ -172,6 +179,7 @@ def _rms_layernorm_backward(
GEMMA,
dW_acc,
True,
+ FROM_Y,
)
tl.store(dW + pid * n_cols + col_offsets, dW_acc, mask = mask)
else:
@@ -192,6 +200,7 @@ def _rms_layernorm_backward(
GEMMA,
0.0,
False,
+ FROM_Y,
)
@@ -201,6 +210,7 @@ _rms_layernorm_backward = triton.heuristics(
"GEMMA": lambda args: bool(args["GEMMA"]),
"LONG_INDEXING": lambda args: bool(args["LONG_INDEXING"]),
"TRAIN_W": lambda args: bool(args["TRAIN_W"]),
+ "FROM_Y": lambda args: bool(args["FROM_Y"]),
}
)(_rms_layernorm_backward)
@@ -334,6 +344,7 @@ def _rms_backward_rows_block(
BLOCK_SIZE: tl.constexpr,
ROWS: tl.constexpr,
WARPS: tl.constexpr,
+ FROM_Y: tl.constexpr,
):
col_offsets = tl.arange(0, BLOCK_SIZE)
row_mask = rows < n_rows
@@ -349,7 +360,11 @@ def _rms_backward_rows_block(
W_row = tl.load(W + col_offsets, mask = col_mask, other = 0).to(tl.float32)
inv_var = tl.load(r + rows, mask = row_mask, other = 0).to(tl.float32)
- normed = X_rows * inv_var[:, None]
+ if FROM_Y:
+ normed = X_rows / (W_row[None, :] + 1.0 if GEMMA else W_row[None, :])
+ normed = tl.where(mask, normed, 0.0)
+ else:
+ normed = X_rows * inv_var[:, None]
if GEMMA:
dY_W = dY_rows * (W_row[None, :] + 1.0)
@@ -391,6 +406,7 @@ def _rms_layernorm_backward_rows(
WARPS: tl.constexpr,
LONG_INDEXING: tl.constexpr,
TRAIN_W: tl.constexpr,
+ FROM_Y: tl.constexpr,
):
pid = tl.program_id(0)
if LONG_INDEXING:
@@ -416,6 +432,7 @@ def _rms_layernorm_backward_rows(
BLOCK_SIZE,
ROWS,
WARPS,
+ FROM_Y,
)
col_offsets = tl.arange(0, BLOCK_SIZE)
tl.store(dW + pid * n_cols + col_offsets, dW_acc, mask = col_offsets < n_cols)
@@ -436,6 +453,7 @@ def _rms_layernorm_backward_rows(
BLOCK_SIZE,
ROWS,
WARPS,
+ FROM_Y,
)
@@ -709,6 +727,7 @@ def _rms_backward(
wrap,
multirow = None,
train_w = False,
+ from_y = False,
):
# Non-Gemma writes dX over dY (the kernel ignores dX); Gemma writes into dX.
n_rows, n_cols = dY.shape
@@ -742,6 +761,7 @@ def _rms_backward(
WARPS = WARPS,
LONG_INDEXING = long,
TRAIN_W = train_w,
+ FROM_Y = from_y,
),
device,
num_warps = num_warps,
@@ -778,6 +798,7 @@ def _rms_backward(
LONG_INDEXING = long,
BLOCK_SIZE = BLOCK_SIZE,
TRAIN_W = train_w,
+ FROM_Y = from_y,
),
device,
num_warps = num_warps,
@@ -807,6 +828,29 @@ def _rms_sum_partials(partials, W, wrap):
_eager_kernel = lambda kernel: kernel
+# Opt-in: save the output Y (which LoRA_QKV / LoRA_MLP already hold) instead of the input X and
+# recompute normed = Y / W in backward. Saves one T x D activation per norm; dX is no longer bitwise.
+_SAVE_OUTPUT = os.environ.get("UNSLOTH_RMSNORM_SAVE_OUTPUT", "0") == "1"
+
+
+def _save_output_ok(W, gemma, dtype):
+ # Y / W needs |W| (|1 + W| for Gemma) clear of 0 and fp16 Y not subnormal. Cached per weight version.
+ key = (W._version, W.data_ptr(), gemma, dtype)
+ cached = getattr(W, "_unsloth_save_output", None)
+ if cached is not None and cached[0] == key:
+ return cached[1]
+ if W.device.type == "cuda" and torch.cuda.is_current_stream_capturing():
+ # .item() would sync inside CUDA graph capture: save X for this call, check eagerly later.
+ return False
+ with torch.no_grad():
+ w = W.float() + 1.0 if gemma else W.float()
+ ok = bool((w.isfinite().all() & (w.abs().amin() >= 16 * torch.finfo(dtype).tiny)).item())
+ try:
+ W._unsloth_save_output = (key, ok)
+ except Exception:
+ pass
+ return ok
+
class Fast_RMS_Layernorm(torch.autograd.Function):
@staticmethod
@@ -816,6 +860,7 @@ class Fast_RMS_Layernorm(torch.autograd.Function):
W: torch.Tensor,
eps: float,
gemma: bool = False,
+ save_output: bool = False,
):
shape = X.shape
dim: int = shape[-1]
@@ -826,8 +871,22 @@ class Fast_RMS_Layernorm(torch.autograd.Function):
Y, r = _rms_forward(X, W, eps, gemma, _eager_kernel)
ctx.eps = eps
ctx.GEMMA = gemma
- ctx.save_for_backward(X, W, r)
- return Y.view(*shape)
+ Y = Y.view(*shape)
+ # save_output: the caller guarantees nothing writes into Y (an untracked Triton write would
+ # corrupt dX silently). Only frozen W: a trained W changes every step.
+ ctx.FROM_Y = (
+ save_output
+ and _SAVE_OUTPUT
+ and not ctx.needs_input_grad[1]
+ and _save_output_ok(W, gemma, Y.dtype)
+ )
+ ctx.save_for_backward(Y if ctx.FROM_Y else X, W, r)
+ if ctx.FROM_Y:
+ # LoRA_QKV / LoRA_MLP then do not overwrite Y with their dX, nor views of it (tiled MLP).
+ Y._unsloth_rmsnorm_saved = True
+ if Y._base is not None:
+ Y._base._unsloth_rmsnorm_saved = True
+ return Y
@staticmethod
def backward(ctx, dY: torch.Tensor):
@@ -835,6 +894,7 @@ class Fast_RMS_Layernorm(torch.autograd.Function):
dim: int = shape[-1]
dY = dY.reshape(-1, dim).contiguous()
X, W, r = ctx.saved_tensors
+ X = X.view(-1, dim)
dX = torch.empty_like(dY) if ctx.GEMMA else dY
with torch_gpu_device(dY.device):
dW = _rms_backward(
@@ -847,9 +907,10 @@ class Fast_RMS_Layernorm(torch.autograd.Function):
ctx.GEMMA,
_eager_kernel,
train_w = ctx.needs_input_grad[1],
+ from_y = ctx.FROM_Y,
)
dX = dX.view(*shape)
- return dX, dW, None, None
+ return dX, dW, None, None, None
# Compiled graphs take these ops: same kernels, fresh outputs (the Function writes dX over dY).
@@ -946,27 +1007,34 @@ if _TRACEABLE:
@torch.compiler.disable
-def _fast_rms_layernorm_untraced(X, W, eps, gemma):
- return Fast_RMS_Layernorm.apply(X, W, eps, gemma)
+def _fast_rms_layernorm_untraced(
+ X,
+ W,
+ eps,
+ gemma,
+ save_output = False,
+):
+ return Fast_RMS_Layernorm.apply(X, W, eps, gemma, save_output)
def fast_rms_layernorm(
layernorm,
X: torch.Tensor,
gemma: bool = False,
+ save_output: bool = False,
):
W: torch.Tensor = layernorm.weight
eps: float = (
layernorm.variance_epsilon if hasattr(layernorm, "variance_epsilon") else layernorm.eps
)
if not torch.compiler.is_compiling():
- return Fast_RMS_Layernorm.apply(X, W, eps, gemma)
+ return Fast_RMS_Layernorm.apply(X, W, eps, gemma, save_output)
if (
not _TRACEABLE
or X.device.type != "cuda"
or (X.dtype == torch.bfloat16 and not _BF16_TRACEABLE)
):
- return _fast_rms_layernorm_untraced(X, W, eps, gemma)
+ return _fast_rms_layernorm_untraced(X, W, eps, gemma, save_output)
shape = X.shape
Y, _ = torch.ops.unsloth.rms_layernorm(
X.reshape(-1, shape[-1]).contiguous(), W.contiguous(), eps, gemma
diff --git a/unsloth/models/gemma.py b/unsloth/models/gemma.py
index 83778ae0f64..849caa74b6c 100644
--- a/unsloth/models/gemma.py
+++ b/unsloth/models/gemma.py
@@ -118,7 +118,9 @@ def GemmaDecoderLayer_fast_forward(
hidden_states += residual
else:
residual = hidden_states
- hidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states, gemma = True)
+ hidden_states = fast_rms_layernorm(
+ self.input_layernorm, hidden_states, gemma = True, save_output = True
+ )
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states = hidden_states,
causal_mask = causal_mask,
@@ -133,7 +135,9 @@ def GemmaDecoderLayer_fast_forward(
hidden_states = residual + hidden_states
residual = hidden_states
- hidden_states = fast_rms_layernorm(self.post_attention_layernorm, hidden_states, gemma = True)
+ hidden_states = fast_rms_layernorm(
+ self.post_attention_layernorm, hidden_states, gemma = True, save_output = True
+ )
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
diff --git a/unsloth/models/gemma2.py b/unsloth/models/gemma2.py
index d45c2a816ec..6b142951cc3 100644
--- a/unsloth/models/gemma2.py
+++ b/unsloth/models/gemma2.py
@@ -315,7 +315,9 @@ def Gemma2DecoderLayer_fast_forward(
hidden_states += residual
else:
residual = hidden_states
- hidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states, gemma = True)
+ hidden_states = fast_rms_layernorm(
+ self.input_layernorm, hidden_states, gemma = True, save_output = True
+ )
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states = hidden_states,
causal_mask = causal_mask,
@@ -332,7 +334,7 @@ def Gemma2DecoderLayer_fast_forward(
residual = hidden_states
hidden_states = fast_rms_layernorm(
- self.pre_feedforward_layernorm, hidden_states, gemma = True
+ self.pre_feedforward_layernorm, hidden_states, gemma = True, save_output = True
)
hidden_states = self.mlp(hidden_states)
hidden_states = fast_rms_layernorm(
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 160cbad9f5c..7ee1001a42e 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -1068,7 +1068,7 @@ def LlamaDecoderLayer_fast_forward(
hidden_states += residual
else:
residual = hidden_states
- hidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states)
+ hidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states, save_output = True)
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states = hidden_states,
causal_mask = causal_mask,
@@ -1084,7 +1084,9 @@ def LlamaDecoderLayer_fast_forward(
hidden_states = residual + hidden_states
residual = hidden_states
- hidden_states = fast_rms_layernorm(self.post_attention_layernorm, hidden_states)
+ hidden_states = fast_rms_layernorm(
+ self.post_attention_layernorm, hidden_states, save_output = True
+ )
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states