"""Custom Triton GPU kernels (arch-autotuned), opt-in per run. Currently: a fused RMSNorm (forward + backward). Many HF models implement RMSNorm in eager PyTorch — `x * rsqrt(mean(x^2)+eps) * weight` — which launches several kernels and re-reads the activation from HBM multiple times. The fused Triton kernel does it in ONE pass per row, which is a real bandwidth win on consumer/Blackwell GPUs whose stock fused norms lag the datacenter parts. Safety: install_custom_rmsnorm() runs a numeric self-test on the live GPU and only patches if the kernel matches eager within tolerance — otherwise it leaves the model untouched (correctness over speed). Gated by AUTOSLM_CUSTOM_RMSNORM=1; default off. """ from __future__ import annotations import os def _build(): """Build the Triton kernels + autograd Function lazily (import triton/torch only on demand).""" import torch import triton import triton.language as tl # RMSNorm normalizes over the hidden dim (≤ ~8k), which fits ONE Triton block — so use a # single masked block (BLOCK a tl.constexpr power-of-2 ≥ N, set per call). NO runtime-bound # Python loop: Triton needs compile-time loop bounds, and a runtime `range(0,N,BLOCK)` fails # to compile (which would silently fall back to eager). num_warps is the per-arch autotune axis. @triton.autotune( configs=[triton.Config({}, num_warps=w) for w in (2, 4, 8, 16)], key=["BLOCK"], ) @triton.jit def _rmsnorm_fwd(X, W, Y, RSTD, stride, N, eps, BLOCK: tl.constexpr): row = tl.program_id(0) cols = tl.arange(0, BLOCK) mask = cols < N x = tl.load(X + row * stride + cols, mask=mask, other=0.0).to(tl.float32) w = tl.load(W + cols, mask=mask, other=0.0).to(tl.float32) rstd = 1.0 / tl.sqrt(tl.sum(x * x) / N + eps) tl.store(RSTD + row, rstd) tl.store(Y + row * stride + cols, (x * rstd * w).to(Y.dtype.element_ty), mask=mask) @triton.autotune( configs=[triton.Config({}, num_warps=w) for w in (2, 4, 8, 16)], key=["BLOCK"], ) @triton.jit def _rmsnorm_bwd_dx(DY, X, W, RSTD, DX, stride, N, BLOCK: tl.constexpr): row = tl.program_id(0) cols = tl.arange(0, BLOCK) m = cols < N dy = tl.load(DY + row * stride + cols, mask=m, other=0.0).to(tl.float32) x = tl.load(X + row * stride + cols, mask=m, other=0.0).to(tl.float32) w = tl.load(W + cols, mask=m, other=0.0).to(tl.float32) rstd = tl.load(RSTD + row) c = tl.sum(dy * w * x) / N * (rstd * rstd * rstd) dx = dy * w * rstd - x * c tl.store(DX + row * stride + cols, dx.to(DX.dtype.element_ty), mask=m) class _FusedRMSNorm(torch.autograd.Function): @staticmethod def forward(ctx, x, weight, eps): shape = x.shape x2 = x.reshape(-1, shape[-1]).contiguous() n_rows, N = x2.shape y = torch.empty_like(x2) rstd = torch.empty(n_rows, dtype=torch.float32, device=x.device) BLOCK = triton.next_power_of_2(N) _rmsnorm_fwd[(n_rows,)](x2, weight, y, rstd, x2.stride(0), N, eps, BLOCK=BLOCK) ctx.BLOCK = BLOCK ctx.save_for_backward(x2, weight, rstd) ctx.eps = eps return y.reshape(shape) @staticmethod def backward(ctx, dy): x2, weight, rstd = ctx.saved_tensors shape = dy.shape dy2 = dy.reshape(-1, shape[-1]).contiguous() n_rows, N = dy2.shape dx = torch.empty_like(dy2) _rmsnorm_bwd_dx[(n_rows,)](dy2, x2, weight, rstd, dx, dy2.stride(0), N, BLOCK=ctx.BLOCK) # dweight (RMSNorm gain): sum over rows of dy * x_hat. Frozen in LoRA, but return it # for generality so autograd is correct if the gain is ever trainable. x_hat = x2.float() * rstd[:, None] dweight = (dy2.float() * x_hat).sum(0).to(weight.dtype) return dx.reshape(shape), dweight, None return _FusedRMSNorm _FUSED = None def fused_rmsnorm(x, weight, eps: float): global _FUSED if _FUSED is None: _FUSED = _build() return _FUSED.apply(x, weight, eps) def _self_test() -> bool: """Numeric parity vs eager RMSNorm on the live GPU (fwd + dx). True iff within tolerance.""" import torch if not torch.cuda.is_available(): return False torch.manual_seed(0) for N in (1536, 4096): x = torch.randn(8, N, device="cuda", dtype=torch.bfloat16, requires_grad=True) w = torch.randn(N, device="cuda", dtype=torch.bfloat16) eps = 1e-6 ref = x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + eps) * w.float() out = fused_rmsnorm(x, w, eps) if not torch.allclose(out.float(), ref, atol=2e-2, rtol=2e-2): print(f"[custom-rmsnorm] self-test FAILED fwd N={N}; falling back to eager") return False g = torch.randn_like(out) (out.float() * g.float()).sum().backward() dx_custom = x.grad.clone() x.grad = None (ref * g.float()).sum().backward() if not torch.allclose(dx_custom.float(), x.grad.float(), atol=3e-2, rtol=3e-2): print(f"[custom-rmsnorm] self-test FAILED dx N={N}; falling back to eager") return False x.grad = None print("[custom-rmsnorm] self-test passed (fwd+dx parity)") return True def install_custom_rmsnorm() -> bool: """Monkeypatch transformers RMSNorm modules to the fused Triton kernel, IFF the self-test passes. Gated by AUTOSLM_CUSTOM_RMSNORM=1. Returns True if installed.""" if os.environ.get("AUTOSLM_CUSTOM_RMSNORM", "0") in ("0", "false", "False"): return False try: if not _self_test(): return False import torch.nn as nn import transformers.models # noqa: F401 (ensure model modules importable) patched = 0 # Patch any *RMSNorm nn.Module subclass that exposes `.weight` + `.variance_epsilon`. import gc for obj in gc.get_objects(): try: if ( isinstance(obj, nn.Module) and obj.__class__.__name__.endswith("RMSNorm") and hasattr(obj, "weight") ): eps = getattr(obj, "variance_epsilon", getattr(obj, "eps", 1e-6)) w = obj.weight def _fwd(self, hidden, _w=w, _eps=eps): return fused_rmsnorm(hidden, _w, _eps) obj.forward = _fwd.__get__(obj, obj.__class__) patched += 1 except Exception: continue print(f"[custom-rmsnorm] installed on {patched} RMSNorm modules") return patched > 0 except Exception as e: print("[custom-rmsnorm] install skipped:", e) return False