REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Normalize RMS with stable accumulation and autograd

RMS normalization rescales by the root mean square and differs from centering-based layer normalization.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Normalize RMS with stable accumulation and autograd →

Your task

Compute x / sqrt(mean(x**2,last_axis,keepdim=True)+eps) times a learned last-axis weight. Do not subtract the mean. Accumulate in float32 for float16/bfloat16/float32 input and float64 for float64 input, cast the normalized values back to x.dtype, then multiply weight. Require a nonempty last axis, weight shape [D] and finite eps>0. Return a new differentiable tensor without changing inputs.

Starter

import torch


def rms_normalize(x, weight, eps=1e-6):
    return None
Inspect the worked answer
import math
import torch


def rms_normalize(x, weight, eps=1e-6):
    if x.ndim < 1 or x.shape[-1] == 0 or weight.shape != x.shape[-1:]:
        raise ValueError('one learned weight per last-axis feature required')
    if not math.isfinite(eps) or eps <= 0:
        raise ValueError('positive finite epsilon required')
    working = x if x.dtype == torch.float64 else x.float()
    mean_square = working.square().mean(dim=-1, keepdim=True)
    normalized = working * torch.rsqrt(mean_square + eps)
    return normalized.to(x.dtype) * weight

About this algorithm

How Normalize RMS with stable accumulation and autograd works

The idea

RMS normalization divides each feature vector by its root mean square, the square root of the average of its squared entries, and then multiplies by a learned weight per feature. Unlike layer normalization it does not subtract the mean and has no bias: it changes the vector's scale and leaves its direction alone, which is cheaper and works well in transformers.

The careful part is the arithmetic. Squares overflow quickly in half precision, where the largest finite value is about 65504, so the Lab squares and averages in float32 and casts the normalized result back to the input dtype before applying the weight. eps sits inside the square root, so an all-zero vector gives zero output and finite gradients.

How it works

  1. Validate that weight has shape [D] matching the last axis of x, and that eps is finite and positive.
  2. Promote x to float32 with x.float() unless it is already float64, and call the result working.
  3. Compute mean_square = working.square().mean(dim=-1, keepdim=True).
  4. Multiply working by torch.rsqrt(mean_square + eps).
  5. Cast the normalized values back to x.dtype and multiply by weight.

What it costs

Time
O(number of elements)
Parameters
D weights, no bias
vs LayerNorm
no mean subtraction

One pass squares and averages each vector and one rescales it; skipping the mean subtraction is what makes it cheaper than layer normalization.

Where it is used

  • Zhang and Sennrich proposed it in 'Root Mean Square Layer Normalization' (2019).
  • Meta's Llama reference code normalizes x.float(), casts back with type_as(x) and then multiplies by the weight, the same order as this Lab.
  • PyTorch includes it as torch.nn.RMSNorm from version 2.4.

Watch out for

  • Subtracting the mean first, which turns it into layer norm: a constant vector of 2s must come out as 1s here, not 0s.
  • Squaring in float16: 1000 squared is far above the float16 maximum, becomes infinity, and the normalized output collapses to zero.
  • Dropping eps or putting it outside the root: an all-zero row then gives NaN outputs or NaN gradients.