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):
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 |
|---|---|---|
|
the input, a floating-point array |
required |
|
the shape of the last dimensions, which are normalized together: an int or a tuple of ints |
required |
|
a weight per element of the normalized shape, in the input's dtype |
|
|
a bias per element of the normalized shape, in the input's dtype |
|
|
added to the mean square or the variance |
|
batch_norm:
Argument |
Meaning |
Default |
|---|---|---|
|
the input, of shape (batch, channels, ...) |
required |
|
a mean and a variance per channel: what evaluation normalizes by, and what training updates |
|
|
a weight and a bias per channel, in the input's dtype |
|
|
normalize by the batch's own statistics |
|
|
the weight of the batch's statistic in the updated running statistics: a number |
|
|
added to the variance |
|
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:
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())
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:
# 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)
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:
# 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())
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:
# 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': 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 |
|---|---|---|
|
the square root and the division are one library function within |
PyTorch on CUDA and MPS |
|
|
PyTorch's CPU kernel for float16 and bfloat16 |
|
Welford's method under any merging of blocks |
PyTorch on CUDA |
|
the mean subtracted first, the two products in either order |
PyTorch's CPU kernel for a non-contiguous input, and CUDA |
|
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:
# 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()})
{'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), astorch.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 todtype(default: the input's format), a floating-point format.weighthas the normalized shape and the input's dtype (None: 1).epsis 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 asmeanbounds 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 isrms_norm_algorithm(rsqrt_ulps=...).xandweightmay 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), astorch.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 todtype(default: the input's format), a floating-point format.weightandbiashave the normalized shape and the input's dtype (None: 1 and 0).epsis 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 arelayer_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,weightandbiasmay 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.outputis the exactbias + weight * (x - mean) / sqrt(var + eps)per element, rounded once todtype(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 hasrunning_meanandrunning_var, each(1 - momentum) * running + momentum * statisticwith the channel's mean and its unbiased variance, exact fractions rounded once. In evaluation the mean and the variance arerunning_meanandrunning_var.weight,biasand the running statistics have one element per channel and the input's dtype.epsandmomentumare 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 asmeanandvarbound the two-pass method,epsadded, a square root and a division,alphathe reciprocal root times the weight,betathe bias lessmean * alpha, andx * alpha + beta, each product before a sum fused into it or rounded first. The other kernels arebatch_norm_algorithm's methods.xand 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 gradientgrad:grad_x, andgrad_weightwhere a weight is given.Each element is the exact value rounded once.
grad_xis a signed square root of a fraction of the slice's exact sums, rounded by integers.grad_weightadds 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.gradmust havex's shape.x,weightandgradmay 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 gradientgrad:grad_x, andgrad_weightandgrad_biaswhere they are given.Each element is the exact value rounded once.
grad_xis a signed square root of a fraction of the slice's exact sums, rounded by integers.grad_weightadds 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_biasis the exact sum ofgradover 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 bfloat16xthat kernel takes its steps in the dtype, whichcompute=the dtype describes. A slice with a value that is not finite among its elements, gradients or weights has NaN gradients.gradmust havex's shape.x,weight,biasandgradmay 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'soutputfor its gradientgrad:grad_x, andgrad_weightandgrad_biaswhere they are given.Each element is the exact value rounded once:
grad_xandgrad_weightare signed square roots of fractions of the channel's exact sums, rounded by integers, andgrad_biasis the channel's exact sum ofgrad.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 bfloat16x, that kernel takes its steps in the dtype, whichcompute=the dtype describes. In training a channel with a value that is not finite among its elements, gradients or weight has NaN gradients; in evaluationgrad_xandgrad_weightfollow IEEE's rules element by element.gradmust havex's shape.x, the parameters andgradmay also be earlier results.
See also#
sqrt and rsqrt, the reciprocal square root.
Algorithms for the named algorithms.
The proofs: rms_norm.md, layer_norm.md, and batch_norm.md.