rms_norm, layer_norm, and batch_norm#

A normalization rescales a group of activations to a standard size: it subtracts their mean, divides by their standard deviation, and applies a learned weight and bias. layer_norm does this to each token's features, and batch_norm to each channel over a batch. rms_norm divides by the root of the mean square and subtracts no mean. Transformers run one before or after every block, and most convolutional networks one after every convolution.

In ExactRef they are er.rms_norm(x, normalized_shape, weight, eps), er.layer_norm(x, normalized_shape, weight, bias, eps), and er.batch_norm(x, running_mean, running_var, weight, bias, training, momentum, eps), with the arguments of torch.nn.functional's. They are also under er.nn.normalization. Each output element is the reference: the exact value rounded once. To check another implementation's output against it, use covers(), as in the examples below.

ExactRef forms the exact sums of each group's elements and of their squares. From those, every output is a float plus a signed square root of a fraction, and ExactRef rounds that with integer arithmetic, so it never runs out of precision. eps and momentum enter at their exact values.

The tolerance says, per element, how far a correct implementation's output can be from the reference. A correct implementation takes the steps of PyTorch's CPU kernel in the compute format (float32 for inputs narrower than float32, else the input format):

reference b + w (x - mean) / sqrt(var + eps), exactly rounded once tolerance mean, var every step rounded 1 / sqrt(var + eps) a sum, a root, a division x - mean rounded times that rounded times w, plus b fused, or rounded twice Every step is in the compute format; the result is then rounded to the output. rms_norm has no mean and no bias: the mean of the squares stands for var. batch_norm works per channel and folds the last three steps into x * alpha + beta.

The steps of layer_norm, with how rms_norm and batch_norm differ.

Most of the tolerance comes from the mean and the variance, because a long row has many additions to round. layer_norm's kernel computes them by Welford's method, which updates a running mean element by element and then merges blocks of elements. The bound for that method is far wider than one run's error; var explains the method. batch_norm's kernel takes two passes, the mean first and then the squared deviations from it.

Arguments#

rms_norm and layer_norm:

Argument

Meaning

Default

x

the input, a floating-point array

required

normalized_shape

the shape of the last dimensions, which are normalized together: an int or a tuple of ints

required

weight

a weight per element of the normalized shape, in the input's dtype

None: 1

bias (layer_norm)

a bias per element of the normalized shape, in the input's dtype

None: 0

eps

added to the mean square or the variance

rms_norm: None, the machine epsilon of the format the kernel computes in, as in PyTorch; layer_norm: 1e-5

batch_norm:

Argument

Meaning

Default

x

the input, of shape (batch, channels, ...)

required

running_mean, running_var

a mean and a variance per channel: what evaluation normalizes by, and what training updates

None

weight, bias

a weight and a bias per channel, in the input's dtype

None: 1 and 0

training

normalize by the batch's own statistics

False

momentum

the weight of the batch's statistic in the updated running statistics: a number

0.1

eps

added to the variance

1e-5

All three also take dtype, rounding, overflow, and workers by keyword, as every operation does.

Examples#

A vision transformer such as ViT-B/16 normalizes 197 tokens of 768 features per image. Here is that layer_norm for 2 images in float32, checked against PyTorch's:

Code
import numpy as np
import torch
import torch.nn.functional as F
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The activations, and the layer's weight and bias
x = torch.randn(2, 197, 768, generator=g) * 2 + 0.5
weight, bias = torch.randn(768, generator=g) + 1, torch.randn(768, generator=g)

# ExactRef's result
r = er.layer_norm(x, 768, weight, bias)
out = F.layer_norm(x, [768], weight, bias)
# Could a correct implementation produce PyTorch's output?
print("covered:", r.covers(out).all())

# The median tolerance, in float32 steps of each element
steps = [t / abs(float(np.spacing(np.float32(v)))) for t, v in zip(r.tolerance().scalars(), r.rounded.scalars())]
print("median tolerance, in steps:", sorted(steps)[len(steps) // 2])
# How many of PyTorch's elements are the reference itself
same = sum(a == b for a, b in zip(r.rounded.scalars(), out.flatten().tolist()))
print("equal to the reference:", same, "of", out.numel())
Output
covered: True
median tolerance, in steps: 3588.0
equal to the reference: 167694 of 302592

The tolerance is a few thousand steps because it holds for every way Welford's method can round on these rows. One run of PyTorch's kernel lands on the reference more than half the time.

The normal answer#

layer_norm's normal(), its normal answer, follows PyTorch's CPU kernel step by step. It merges Welford's blocks as that kernel does with its narrowest vectors: 4 lanes for float32, 2 for float64. On an ARM CPU, PyTorch's float32 and float64 layer_norm without a weight and a bias is exactly this answer:

Code
# The same activations, normalized without a weight and a bias
plain = er.layer_norm(x, 768)
# The normal answer against PyTorch's output, bit for bit
same = plain.normal().identical(er.asarray(F.layer_norm(x, [768])))
print("PyTorch's output is the normal answer:", same)
Output
PyTorch's output is the normal answer: True

Builds that fuse the weight's product into the bias's sum, and x86 builds, which merge wider vectors, differ slightly. The tolerance covers them.

rms_norm#

Llama 3 8B normalizes 4096 features per token with rms_norm and eps=1e-5. Here it is for 128 tokens:

Code
# The tokens' hidden states, and the layer's weight
h = torch.randn(128, 4096, generator=g)
w = torch.rand(4096, generator=g) + 0.5

# ExactRef's result, with Llama's eps
rr = er.rms_norm(h, 4096, w, 1e-5)
print("covered:", rr.covers(F.rms_norm(h, [4096], w, 1e-5)).all())
Output
covered: True

batch_norm in training#

In training, batch_norm normalizes each channel by the batch's own statistics and updates the running ones. The result then has three named outputs: output, and the new running_mean and running_var. Here is the first stage of a ResNet, 64 channels of 56 by 56, for a batch of 8 images:

Code
# The images, and a weight and a bias per channel
images = torch.randn(8, 64, 56, 56, generator=g) * 2 + 1
wc, bc = torch.randn(64, generator=g) + 1, torch.randn(64, generator=g)
running_mean, running_var = torch.zeros(64), torch.ones(64)

# ExactRef's result, from the running statistics before the update
rb = er.batch_norm(images, running_mean, running_var, wc, bc, training=True)
# PyTorch updates its running statistics in place
outb = F.batch_norm(images, running_mean, running_var, wc, bc, training=True)

# covers() takes the named outputs as a dict and answers for each
covered = rb.covers({"output": outb, "running_mean": running_mean, "running_var": running_var})
print({name: found.all() for name, found in covered.items()})
Output
{'output': True, 'running_mean': True, 'running_var': True}

In evaluation, batch_norm normalizes by the running_mean and running_var it is given, and the result has the output alone. momentum must be a number. A torch.nn.BatchNorm2d with momentum=None keeps a cumulative average by giving F.batch_norm the momentum 1 / num_batches_tracked, so pass that number. Training takes more than one value per channel, as in PyTorch.

Other kernels#

PyTorch's other kernels take other steps, and each is a named algorithm of er.nn.normalization:

Algorithm

What differs

Whose it is

rms_norm_algorithm(rsqrt_ulps=c)

the square root and the division are one library function within c steps

PyTorch on CUDA and MPS

layer_norm_algorithm(folded=True)

x * r + (-r * mean) before the weight and the bias

PyTorch's CPU kernel for float16 and bfloat16

layer_norm_algorithm(welford=True)

Welford's method under any merging of blocks

PyTorch on CUDA

batch_norm_algorithm(centered=True)

the mean subtracted first, the two products in either order

PyTorch's CPU kernel for a non-contiguous input, and CUDA

batch_norm_algorithm(welford=True)

the statistics by Welford's method

PyTorch on CUDA

layer_norm_algorithm and batch_norm_algorithm take rsqrt_ulps too, and the methods combine: layer_norm_algorithm(welford=True, rsqrt_ulps=2.5) describes CUDA's layer_norm. For float16 and bfloat16, PyTorch's CPU kernels round their steps to the dtype in batch_norm's training, forward and backward, and in layer_norm's backward: check those with compute= the dtype.

Special values#

A row with an infinity or a NaN gives what PyTorch's steps give by IEEE rules. layer_norm makes the whole row NaN, and so does rms_norm for a NaN. An infinity takes rms_norm's mean square to infinity, so the infinite element becomes NaN and every finite element beside it 0. The gradients of such a row are NaN. batch_norm in training does the same for a channel: one value that is not finite makes the channel's gradients NaN.

In evaluation, batch_norm uses the running statistics instead of the channel's own, so a NaN or an infinity in x changes only its own output element and its channel's grad_weight, and grad_x does not depend on x. An infinite running mean makes x - mean infinite, or NaN where x is an infinity of the same sign.

Backward#

r.backward(grad) gives grad_x, and grad_weight and grad_bias where a weight and a bias are given, each element the exact value rounded once. The tolerance covers PyTorch's CPU backward kernels' steps. Here it checks autograd's gradients for the vision transformer's layer_norm above:

Code
# Copies that record gradients, and the gradient of the output
xs, ws, bs = (v.clone().requires_grad_() for v in (x, weight, bias))
grad = torch.randn(2, 197, 768, generator=g)

# PyTorch's autograd
F.layer_norm(xs, [768], ws, bs).backward(grad)

# ExactRef's gradients, held by name
b = er.layer_norm(x, 768, weight, bias).backward(grad)
# Each gradient against autograd's
covered = b.covers({"grad_x": xs.grad, "grad_weight": ws.grad, "grad_bias": bs.grad})
print({name: found.all() for name, found in covered.items()})
Output
{'grad_x': True, 'grad_weight': True, 'grad_bias': True}

Full specification#

er.rms_norm#

rms_norm(x, normalized_shape, weight=None, eps=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Root-mean-square normalization over the last dimensions, which must have the shape normalized_shape (an int or a tuple of ints), as torch.nn.functional.rms_norm.

Each output element is the exact weight * x / sqrt(mean(x**2) + eps), the mean over its slice of the normalized shape, rounded once to dtype (default: the input's format), a floating-point format. weight has the normalized shape and the input's dtype (None: 1). eps is taken by its exact value; None is PyTorch's default, the machine epsilon of the format the kernel computes in (float32's for float16 and bfloat16). The value is a signed square root of a fraction of exact sums and is rounded by integers, exactly where it is rational. Floating-point inputs.

tolerance() bounds PyTorch's CPU sequence in the compute format: the squares, their mean as mean bounds it under either standard, eps (rounded to the compute format) added, a square root and a division, each element times that reciprocal root, and the product with the weight, each rounded. A kernel whose reciprocal square root is one library function is rms_norm_algorithm(rsqrt_ulps=...). x and weight may also be earlier results. Proof: proofs/rms_norm.md.

er.layer_norm#

layer_norm(x, normalized_shape, weight=None, bias=None, eps=1e-5, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Layer normalization over the last dimensions, which must have the shape normalized_shape (an int or a tuple of ints), as torch.nn.functional.layer_norm.

Each output element is the exact bias + weight * (x - mean) / sqrt(var + eps), the mean and the variance (with the count as its divisor) over its slice of the normalized shape, rounded once to dtype (default: the input's format), a floating-point format. weight and bias have the normalized shape and the input's dtype (None: 1 and 0). eps is taken by its exact value. The value is a dyadic plus a signed square root of a fraction of exact sums, rounded by integers: exactly where the root is rational, and otherwise from an enclosure that always decides it. Floating-point inputs.

tolerance() bounds PyTorch's CPU sequence for float32 and float64 in the compute format: the mean and the variance by Welford's method over that kernel's merge tree, eps (rounded to the compute format) added, a square root and a division, each element less the mean, times that reciprocal root, and times the weight plus the bias, that last product fused into the sum or rounded first. The other kernels are layer_norm_algorithm's methods. normal() is that sequence with every step rounded once and Welford's blocks merged as PyTorch's CPU kernel merges them at its narrowest vector (4 lanes up to float32's precision, 2 above), the ARM builds' for float32 and float64 (their 16-bit kernel merges two runs a block, which the bounds hold). x, weight and bias may also be earlier results. Proof: proofs/layer_norm.md.

er.batch_norm#

batch_norm(x, running_mean=None, running_var=None, weight=None, bias=None, training=False, momentum=0.1, eps=1e-5, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Batch normalization over each channel (dimension 1), as torch.nn.functional.batch_norm.

output is the exact bias + weight * (x - mean) / sqrt(var + eps) per element, rounded once to dtype (default: the input's format), a floating-point format. In training the mean and the variance (with the count as its divisor) are the channel's own, over the batch and the dimensions after the channels, and with running statistics given the result also has running_mean and running_var, each (1 - momentum) * running + momentum * statistic with the channel's mean and its unbiased variance, exact fractions rounded once. In evaluation the mean and the variance are running_mean and running_var. weight, bias and the running statistics have one element per channel and the input's dtype. eps and momentum are taken by their exact values. Floating-point inputs; training takes more than one value per channel.

tolerance() bounds PyTorch's CPU sequence for a contiguous or channels-last input in the compute format: the statistics as mean and var bound the two-pass method, eps added, a square root and a division, alpha the reciprocal root times the weight, beta the bias less mean * alpha, and x * alpha + beta, each product before a sum fused into it or rounded first. The other kernels are batch_norm_algorithm's methods. x and the parameters may also be earlier results. Proof: proofs/batch_norm.md.

The backwards#

backward(x, grad, normalized_shape, weight=None, eps=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Gradients of rms_norm(x, normalized_shape, weight, eps) for the output gradient grad: grad_x, and grad_weight where a weight is given.

Each element is the exact value rounded once. grad_x is a signed square root of a fraction of the slice's exact sums, rounded by integers. grad_weight adds one such root per slice, with different fractions; a sum that is exactly 0 or exactly rational is found by the roots' classes and rounded as a fraction, and any other is irrational and is rounded from enclosures refined until the rounding is certain. tolerance() bounds PyTorch's CPU backward, which differentiates the composite: the gradients of the two products, of the reciprocal square root, of the mean, and of the squares, each an operation of this library in the compute format. A slice with a value that is not finite among its elements, gradients or weights has NaN gradients. grad must have x's shape. x, weight and grad may also be earlier results.

backward(x, grad, normalized_shape, weight=None, bias=None, eps=1e-5, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Gradients of layer_norm(x, normalized_shape, weight, bias, eps) for the output gradient grad: grad_x, and grad_weight and grad_bias where they are given.

Each element is the exact value rounded once. grad_x is a signed square root of a fraction of the slice's exact sums, rounded by integers. grad_weight adds one such root per slice, with different fractions; a sum that is exactly 0 or exactly rational is found by the roots' classes and rounded as a fraction, and any other is irrational and is rounded from enclosures refined until the rounding is certain. grad_bias is the exact sum of grad over the slices. tolerance() bounds PyTorch's CPU backward kernel, each of its steps in the compute format on Welford's mean and the reciprocal root as the forward's model holds them; for a float16 or bfloat16 x that kernel takes its steps in the dtype, which compute= the dtype describes. A slice with a value that is not finite among its elements, gradients or weights has NaN gradients. grad must have x's shape. x, weight, bias and grad may also be earlier results.

backward(x, grad, running_mean=None, running_var=None, weight=None, bias=None, training=False, eps=1e-5, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Gradients of batch_norm's output for its gradient grad: grad_x, and grad_weight and grad_bias where they are given.

Each element is the exact value rounded once: grad_x and grad_weight are signed square roots of fractions of the channel's exact sums, rounded by integers, and grad_bias is the channel's exact sum of grad. tolerance() bounds PyTorch's CPU backward kernel, each of its steps in the compute format on the statistics and the reciprocal root as the forward's model holds them; in training, for a float16 or bfloat16 x, that kernel takes its steps in the dtype, which compute= the dtype describes. In training a channel with a value that is not finite among its elements, gradients or weight has NaN gradients; in evaluation grad_x and grad_weight follow IEEE's rules element by element. grad must have x's shape. x, the parameters and grad may also be earlier results.

See also#