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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix RMSNorm and LayerNorm backward overwriting the incoming gradient (#13888)
Daniel Han1b8737bf5ed8
diff --git a/tests/test_norm_backward_grad_alias.py b/tests/test_norm_backward_grad_alias.pynew file mode 100644index 00000000000..7e484a99299--- /dev/null+++ b/tests/test_norm_backward_grad_alias.py@@ -0,0 +1,81 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++# incoming grads may be shared by nodes or passed through grad_outputs; do not overwrite them++import pytest+from real_accelerator import has_real_cuda+import torch+++def _rms_fp64(x, W, gemma):+ x = x.double()+ W = W.double() + (1.0 if gemma else 0.0)+ return x * torch.rsqrt(x.square().mean(-1, keepdim = True) + 1e-6) * W+++def _ln_fp64(x, W, b):+ x, W, b = x.double(), W.double(), b.double()+ return torch.nn.functional.layer_norm(x, x.shape[-1:], W, b, 1e-6)+++def _graphs(norm, shape, device, dtype):+ def user_grad(x, go, reference):+ out = torch.autograd.grad(norm(x), x, go)[0]+ x64 = x.detach().double().requires_grad_()+ return out, torch.autograd.grad(reference(x64), x64, go.double())[0]++ def add_self(x, go, reference):+ out = torch.autograd.grad(norm(x) + x, x, go)[0]+ x64 = x.detach().double().requires_grad_()+ return out, torch.autograd.grad(reference(x64) + x64, x64, go.double())[0]++ def two_norms_sum(x, go, reference):+ out = torch.autograd.grad(norm(x) + norm(2 * x), x, go)[0]+ x64 = x.detach().double().requires_grad_()+ return out, torch.autograd.grad(reference(x64) + reference(2 * x64), x64, go.double())[0]++ return {"user_grad": user_grad, "add_self": add_self, "two_norms_sum": two_norms_sum}+++_TOLERANCE = {torch.float32: 1e-4, torch.float16: 1e-2, torch.bfloat16: 1e-1}+++def _check(norm, reference, dtype):+ torch.manual_seed(0)+ shape = (3, 5, 256)+ for name, graph in _graphs(norm, shape, "cuda", dtype).items():+ x = torch.randn(shape, device = "cuda", dtype = dtype).requires_grad_()+ go = torch.randn(shape, device = "cuda", dtype = dtype)+ go_before = go.clone()+ dX, dX64 = graph(x, go, reference)+ assert torch.equal(go, go_before), f"{name}: incoming grad was overwritten"+ error = (dX.double() - dX64).abs().max().item()+ assert error <= _TOLERANCE[dtype], f"{name}: max error vs fp64 {error}"++[email protected](not has_real_cuda(), reason = "CUDA Triton kernels required")[email protected]("gemma", [False, True])[email protected]("save_output", [False, True])[email protected]("train_weight", [False, True])[email protected]("dtype", [torch.float32, torch.float16, torch.bfloat16])+def test_rms_layernorm_backward_leaves_shared_grad_alone(gemma, save_output, train_weight, dtype):+ from unsloth.kernels.rms_layernorm import Fast_RMS_Layernorm++ W = (1.0 + 0.1 * torch.randn(256, device = "cuda")).to(dtype).requires_grad_(train_weight)+ norm = lambda x: Fast_RMS_Layernorm.apply(x, W, 1e-6, gemma, save_output)+ _check(norm, lambda x: _rms_fp64(x, W, gemma), dtype)++[email protected](not has_real_cuda(), reason = "CUDA Triton kernels required")[email protected]("train_weight", [False, True])[email protected]("dtype", [torch.float32, torch.float16, torch.bfloat16])+def test_layernorm_backward_leaves_shared_grad_alone(train_weight, dtype):+ from unsloth.kernels.layernorm import Fast_Layernorm++ W = (1.0 + 0.1 * torch.randn(256, device = "cuda")).to(dtype).requires_grad_(train_weight)+ b = (0.1 * torch.randn(256, device = "cuda")).to(dtype).requires_grad_(train_weight)+ norm = lambda x: Fast_Layernorm.apply(x, W, b, 1e-6)+ _check(norm, lambda x: _ln_fp64(x, W, b), dtype)diff --git a/unsloth/kernels/layernorm.py b/unsloth/kernels/layernorm.pyindex 66b63d98674..f5b34cd68ba 100644--- a/unsloth/kernels/layernorm.py+++ b/unsloth/kernels/layernorm.py@@ -53,10 +53,10 @@ def layernorm_forward(W_row = tl.load(W + col_offsets, mask = mask, other = 0).to(tl.float32)mean_X = tl.sum(X_row, axis = 0) / n_cols- # (X[0] - mean) == -mean, so mask it out.+ # mask invalid lanes because subtraction turns loaded zeros into -mean.XX = tl.where(mask, X_row - mean_X, 0)row_var = tl.sum(XX * XX, axis = 0) / n_cols- # Explicit float32 scalar to ensure correct type promotion on HIP/ROCm.+ # explicit float32 scalar ensures correct type promotion on HIP/ROCm.eps_f32 = tl.full((), eps, tl.float32)inv_var = tl.math.rsqrt(row_var + eps_f32)tl.store(r, inv_var)@@ -68,9 +68,10 @@ def layernorm_forward(@triton.jit-def _layernorm_backward_row(dY, X, W_row, r, mu, row_idx, col_offsets, mask, n_cols: tl.constexpr):- # Approximately follows karpathy/llm.c doc/layernorm/layernorm.md- # Per torchtune's Fp32LayerNorm, all modules are in float32.+def _layernorm_backward_row(+ dY, dX, X, W_row, r, mu, row_idx, col_offsets, mask, n_cols: tl.constexpr+):+ # based on karpathy/llm.c; float32 matches torchtune's Fp32LayerNorm.dY_row = tl.load(dY + col_offsets, mask = mask, other = 0).to(tl.float32)X_row = tl.load(X + col_offsets, mask = mask, other = 0).to(tl.float32)@@ -80,20 +81,22 @@ def _layernorm_backward_row(dY, X, W_row, r, mu, row_idx, col_offsets, mask, n_cdY_W = dY_row * W_rowdX_row = dY_W - tl.sum(dY_W, axis = 0) / n_cols - normed * tl.sum(dY_W * normed, axis = 0) / n_colsdX_row = dX_row * inv_var- tl.store(dY + col_offsets, dX_row, mask = mask)+ tl.store(dX + col_offsets, dX_row, mask = mask)return dY_row, normed@triton.jitdef layernorm_backward(dY,+ dX,X,W,b,r,mu,- dY_row_stride: tl.constexpr, # n_cols- X_row_stride: tl.constexpr, # n_cols+ dY_row_stride: tl.constexpr,+ dX_row_stride: tl.constexpr,+ X_row_stride: tl.constexpr,n_cols: tl.constexpr,eps: tl.constexpr,LONG_INDEXING: tl.constexpr,@@ -107,6 +110,7 @@ def layernorm_backward(W_row = tl.load(W + col_offsets, mask = mask, other = 0).to(tl.float32)_layernorm_backward_row(dY + row_idx * dY_row_stride,+ dX + row_idx * dX_row_stride,X + row_idx * X_row_stride,W_row,r,@@ -118,11 +122,11 @@ def layernorm_backward()-# dW / dB follow flash-linear-attention's layer_norm_bwd_kernel_row (fla/modules/norm/layernorm.py,-# MIT licence, Copyright (c) 2023-2026 Songlin Yang, Yu Zhang, Zhiyuan Li).+# MIT 2023-2026 Songlin Yang et al.: dW/dB follow flash-linear-attention's layer_norm_bwd_kernel_row@triton.jitdef layernorm_backward_dw(dY,+ dX,X,W,r,@@ -132,6 +136,7 @@ def layernorm_backward_dw(n_rows,rows_per_program,dY_row_stride: tl.constexpr,+ dX_row_stride: tl.constexpr,X_row_stride: tl.constexpr,n_cols: tl.constexpr,LONG_INDEXING: tl.constexpr,@@ -152,6 +157,7 @@ def layernorm_backward_dw(row_idx = i.to(tl.int64)dY_row, normed = _layernorm_backward_row(dY + row_idx * dY_row_stride,+ dX + row_idx * dX_row_stride,X + row_idx * X_row_stride,W_row,r,@@ -273,17 +279,20 @@ class Fast_Layernorm(torch.autograd.Function):n_rows, n_cols = dY.shapedevice = dY.devicetrain_w, train_b = ctx.needs_input_grad[1], ctx.needs_input_grad[2]- LONG_INDEXING = long_indexing(dY, X, block = ctx.BLOCK_SIZE)+ # do not write into dY because autograd may share it with other nodes or the caller+ dX = torch.empty_like(dY)+ LONG_INDEXING = long_indexing(dY, dX, X, block = ctx.BLOCK_SIZE)if not (train_w or train_b):with torch_gpu_device(device):_launch(layernorm_backward,(n_rows,),- (dY, X, W, b, r, mu),- 6,+ (dY, dX, X, W, b, r, mu),+ 7,dict(dY_row_stride = dY.stride(0),+ dX_row_stride = dX.stride(0),X_row_stride = X.stride(0),n_cols = n_cols,eps = ctx.eps,@@ -294,10 +303,10 @@ class Fast_Layernorm(torch.autograd.Function):num_warps = ctx.num_warps,enable_fp_fusion = True,)- return dY.view(*shape), None, None, None+ return dX.view(*shape), None, None, Noneprograms, rows_per_program = _dw_programs(device, n_rows, ctx.num_warps)- # Every program stores its partial row, so empty suffices unless nothing launches.+ # every program stores its partial row, so empty works unless no program launchesalloc = torch.empty if n_rows > 0 else torch.zerospartials = alloc((train_w + train_b, programs, n_cols), dtype = torch.float32, device = device)dW = torch.empty(n_cols, dtype = W.dtype, device = device) if train_w else None@@ -308,10 +317,11 @@ class Fast_Layernorm(torch.autograd.Function):_launch(layernorm_backward_dw,(programs,),- (dY, X, W, r, mu, partials[0], partials[-1], n_rows, rows_per_program),- 7,+ (dY, dX, X, W, r, mu, partials[0], partials[-1], n_rows, rows_per_program),+ 8,dict(dY_row_stride = dY.stride(0),+ dX_row_stride = dX.stride(0),X_row_stride = X.stride(0),n_cols = n_cols,LONG_INDEXING = LONG_INDEXING,@@ -332,7 +342,7 @@ class Fast_Layernorm(torch.autograd.Function):device,enable_fp_fusion = True,)- return dY.view(*shape), dW, dB, None+ return dX.view(*shape), dW, dB, Nonedef _dw_programs(device, n_rows, num_warps):diff --git a/unsloth/kernels/rms_layernorm.py b/unsloth/kernels/rms_layernorm.pyindex b31e4116158..6348975dae4 100644--- a/unsloth/kernels/rms_layernorm.py+++ b/unsloth/kernels/rms_layernorm.py@@ -85,15 +85,11 @@ def _rms_backward_row(TRAIN_W: tl.constexpr,FROM_Y: tl.constexpr,):- # FROM_Y: X holds the forward output Y, and normed = Y / W (r still scales dX).+ # with FROM_Y, X holds Y and normed = Y / W; r still scales dX.dY += row_idx * dY_row_strideX += row_idx * X_row_strider += row_idx * r_row_stride-- if GEMMA:- dX += row_idx * dX_row_stride- else:- dX = dY+ dX += row_idx * dX_row_stridedY_row = tl.load(dY + col_offsets, mask = mask, other = 0).to(tl.float32)X_row = tl.load(X + col_offsets, mask = mask, other = 0).to(tl.float32)@@ -101,12 +97,12 @@ def _rms_backward_row(inv_var = tl.load(r).to(tl.float32)if FROM_Y:- # Masked lanes would be 0 / 0.+ # masked lanes would divide 0 by 0.normed = tl.where(mask, X_row / (W_row + 1.0 if GEMMA else W_row), 0.0)else:normed = X_row * inv_varif TRAIN_W:- # dW before the row sum so the fp32 dY row is not held across it (fewer registers, all programs resident).+ # accumulate dW before the row sum to free the fp32 dY row and keep all programs resident.if GEMMA:dW_acc += dY_row * normedelse:@@ -372,15 +368,12 @@ def _rms_backward_rows_block(dY_W = dY_rows * W_row[None, :]rowsum_dY_normed = _row_dot_in_row_kernel_order(dY_W, normed, ROWS, WARPS)- # Spelled as in the one-row kernel: an explicit fma here turns -0 into +0 on sm75.+ # match one-row arithmetic because its fused multiply-add turns -0 into +0 on sm75.output = (inv_var / n_cols)[:, None] * (n_cols * dY_W - normed * rowsum_dY_normed[:, None])- if GEMMA:- tl.store(dX + rows[:, None] * dX_row_stride + col_offsets[None, :], output, mask = mask)- else:- tl.store(dY + rows[:, None] * dY_row_stride + col_offsets[None, :], output, mask = mask)- # Masked rows load zeros, so they add nothing; dead code unless TRAIN_W.+ tl.store(dX + rows[:, None] * dX_row_stride + col_offsets[None, :], output, mask = mask)+ # masked rows contribute zero; this dW path is dead unless TRAIN_W.if not GEMMA:- # The forward multiplies W by normed rounded to W's dtype.+ # forward multiplies W by normed rounded to W's dtype.normed = normed.to(W.dtype.element_ty).to(tl.float32)return tl.sum(dY_rows * normed, axis = 0)@@ -569,8 +562,8 @@ def _multirow_self_check(device, dtype, W_dtype, n_cols, eps, gemma, multirow):results = []for rows in (False, multirow):Y, r = _rms_forward(X, W, eps, gemma, _eager_kernel, rows)- dX = dY.clone()- _rms_backward(dY.clone() if gemma else dX, dX, X, W, r, eps, gemma, _eager_kernel, rows)+ dX = torch.empty_like(dY)+ _rms_backward(dY, dX, X, W, r, eps, gemma, _eager_kernel, rows)results.append((Y, r, dX))return all(torch.equal(_bits(a), _bits(b)) for a, b in zip(*results))@@ -729,7 +722,6 @@ def _rms_backward(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.shapedevice = dY.deviceif multirow is None:@@ -882,7 +874,7 @@ class Fast_RMS_Layernorm(torch.autograd.Function):)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).+ # LoRA_QKV and LoRA_MLP use this marker to preserve Y and its tiled views.Y._unsloth_rmsnorm_saved = Trueif Y._base is not None:Y._base._unsloth_rmsnorm_saved = True@@ -895,7 +887,8 @@ class Fast_RMS_Layernorm(torch.autograd.Function):dY = dY.reshape(-1, dim).contiguous()X, W, r = ctx.saved_tensorsX = X.view(-1, dim)- dX = torch.empty_like(dY) if ctx.GEMMA else dY+ # allocate dX because autograd may share dY with other nodes or the caller.+ dX = torch.empty_like(dY)with torch_gpu_device(dY.device):dW = _rms_backward(dY,@@ -913,7 +906,7 @@ class Fast_RMS_Layernorm(torch.autograd.Function):return dX, dW, None, None, None-# Compiled graphs take these ops: same kernels, fresh outputs (the Function writes dX over dY).+# compiled graphs use these ops with the same kernels as the Function._TRACEABLE = hasattr(torch.library, "triton_op") and hasattr(torch.library, "wrap_triton")@@ -956,7 +949,7 @@ if _TRACEABLE:def _rms_layernorm_op(X: torch.Tensor, W: torch.Tensor, eps: float, gemma: bool) -> Tuple[torch.Tensor, torch.Tensor]:- # Called eagerly (outside a compiled graph) the launch needs X's device made current.+ # eager launches outside compiled graphs need X's device made current.with torch_gpu_device(X.device):return _rms_forward(X, W, eps, gemma, _traced_kernel)@@ -971,10 +964,9 @@ if _TRACEABLE:train_w: bool,) -> Tuple[torch.Tensor, torch.Tensor]:dX = torch.empty_like(dY)- # Non-Gemma rewrites its dY argument, so it gets a copy.with torch_gpu_device(dY.device):dW = _rms_backward(- dY if gemma else dX.copy_(dY),+ dY,dX,X,W,@@ -984,7 +976,7 @@ if _TRACEABLE:_traced_kernel,train_w = train_w,)- # Empty dW = frozen (ops return tensors only).+ # empty dW represents a frozen weight because ops return tensors only.return dX, dW if train_w else W.new_empty(0)def _rms_setup_context(ctx, inputs, output):