mean#
A mean is a sum divided by the number of elements added. Layer normalization takes the mean of each token's features, global average pooling the mean of each channel's pixels, and most losses the mean over a batch. A floating-point mean rounds in two places: at each addition, as any sum does, and at the division.
In ExactRef, er.mean(x, axis=None, *, keepdims=False), also
er.statistics.descriptive.location.mean, is the mean over the dimensions
in axis, as in torch.mean. It takes floating-point and complex inputs. A
complex mean averages the real parts and the imaginary parts separately. To
check an implementation's output, pass it to covers(), as the examples
below do.
Each output element is the exact sum divided by the count, rounded once to the output format: the reference.
The tolerance says per element how far a correct implementation's
output can be from the reference. It covers an implementation that adds the
elements in the compute format, divides the sum by the count there,
and rounds the quotient to the output format. The compute format is float32
for inputs narrower than float32, as in PyTorch, and the input's format
otherwise. The additions are normal accumulation by default, as for
sum, and tolerance(standard="any_order") allows any order, as a
GPU's parallel reduction needs.
The tolerance allows for every rounding in the lower row.
PyTorch's CUDA kernel does not divide: it multiplies the sum by 1 / n
rounded to the compute format.
A rounded reciprocal shows how to check it.
Arguments#
Argument |
Meaning |
Default |
|---|---|---|
|
the input: floating-point or complex; integer and bool inputs raise |
required |
|
the dimensions to reduce: an int, a tuple of ints, or None for all |
|
|
keep the reduced dimensions with size 1 |
|
|
the output format, of the input's kind |
the input's format |
|
the rounding mode of the reference and of a correct implementation's final rounding into the output format |
|
|
what a result past the output format's range becomes: |
each format's own rule |
|
the number of threads the call computes on; no result depends on it |
the performance cores on Apple Silicon, else the physical cores, as PyTorch picks |
Examples#
Layer normalization starts from the mean of each token's features. Here are 1024 tokens with 4096 float32 features each, the hidden size of Llama 3 8B:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# 1024 tokens of 4096 features
x = torch.randn(1024, 4096, generator=g) * 2 + 0.5
# ExactRef's result: one mean per token
r = er.mean(x, axis=1)
print("shape:", r.rounded.shape)
# Could a correct implementation produce PyTorch's output?
print("covered:", r.covers(x.mean(dim=1)).all())
shape: (1024,)
covered: True
16-bit inputs#
PyTorch adds bfloat16 and float16 values in float32 and divides there,
which is the default compute format. A kernel that keeps its sum in float16 instead
stops adding small values once the sum is large. Take one value of 1 and
4096 values of 1/256. The exact mean is 17/4097, but a float16 sum stops
growing at 8, because 8 + 1/256 rounds back to 8. Pass compute= the
format such a kernel adds in:
import numpy as np
# One value of 1 and 4096 values of 1/256, in float16
values = np.array([1.0] + [2.0**-8] * 4096, dtype=np.float16)
r16 = er.mean(values)
print("reference:", r16.rounded.tolist())
# PyTorch's CPU adds in float32
print("PyTorch covered:", r16.covers(torch.from_numpy(values).mean()).all())
# A loop that keeps the sum in float16, then divides in float16
total = np.float16(0)
for v in values:
total = total + v
stalled = total / np.float16(len(values))
print("float16 loop:", float(stalled))
# Outside the default tolerance, inside the one for float16 steps
print("covered:", r16.covers(stalled).all())
print("covered with float16 steps:", r16.covers(stalled, compute="float16").all())
reference: 0.004150390625
PyTorch covered: True
float16 loop: 0.001953125
covered: False
covered with float16 steps: True
Special values#
The mean of no elements is NaN, as in PyTorch: a loss averaged over the tokens a mask keeps is NaN when the mask keeps none. Infinities and NaN follow IEEE rules on the exact sum:
# Per-token losses for 8 sequences of 512 tokens, and a mask that keeps none
losses = torch.rand(8, 512, generator=g)
kept = losses[torch.zeros(8, 512, dtype=torch.bool)]
print("no tokens kept:", er.mean(kept).rounded.tolist())
# One infinite value, then both infinities
inf = float("inf")
print("with inf:", er.mean(er.asarray([1.0, inf], "float32")).rounded.tolist())
print("inf and -inf:", er.mean(er.asarray([-inf, inf], "float32")).rounded.tolist())
no tokens kept: nan
with inf: inf
inf and -inf: nan
A rounded reciprocal#
PyTorch's CUDA kernel multiplies the sum by 1 / n rounded to the compute
format. That rounding is not one of the mean's
boundaries, so er.mean can reject a correct output of
that kernel. Check it as the chain it computes: the sum, then the
product with the rounded reciprocal. Here that arithmetic runs on the CPU,
for the mean over the three color channels of 8 normalized images of 224
by 224 pixels:
# 8 normalized images: 3 color channels of 224 by 224 pixels
images = torch.randn(8, 3, 224, 224, generator=g)
# The sum over the channels times 1/3 rounded to float32, as CUDA computes the mean
third = torch.tensor(1 / 3, dtype=torch.float32)
gray = images.sum(dim=1) * third
# er.mean has no rounding of 1/3
print("covered by er.mean:", er.mean(images, axis=1).covers(gray).all())
# The chain: the sum, then the product with the rounded reciprocal
chain = er.multiply(er.sum(images, axis=1), third.item())
print("covered by the chain:", chain.covers(gray).all())
covered by er.mean: False
covered by the chain: True
For bfloat16 and float16 inputs that kernel sums in float32. The chain is
then er.multiply(er.sum(x, axis, dtype="float32"), r, dtype=d), with r
the reciprocal rounded to float32 and d the input's format.
Backward#
er.mean.backward(x, grad, axis=None, keepdims=False), or
r.backward(grad), returns grad_x. At every element of x it is the
gradient of the output that element was averaged into, divided by the
count. Each element is that quotient rounded once, and its tolerance is
divide's:
# The gradient of each token's mean
gy = torch.randn(1024, generator=g)
# PyTorch's autograd, on a copy that records gradients
x_ = x.clone().requires_grad_()
x_.mean(dim=1).backward(gy)
# ExactRef's gradient, held by name
gb = er.mean.backward(x, gy, axis=1)
print("outputs:", list(gb.rounded))
print("grad_x covered:", gb["grad_x"].covers(x_.grad).all())
outputs: ['grad_x']
grad_x covered: True
Full specification#
er.mean#
- mean(x, axis=None, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The mean over
axis(None: every dimension; an int or a tuple of ints), keeping the reduced dimensions as 1 withkeepdims.Each output element is the exact sum divided by the number of reduced elements, rounded once to
dtype(default: the input dtype), which must be of the input's kind. Floating-point and complex inputs; integer and bool inputs raise, as in PyTorch. A complex mean takes its real and imaginary parts separately. The mean of no elements is NaN.tolerance()bounds PyTorch's CPU method: the sum accumulated in the compute format, assumbounds it under either standard, then one division by the count, rounded there, then the rounding to the output. An implementation that multiplies the sum by a rounded1 / count, as CUDA does, is the chainmultiply(sum(x, dtype=compute), reciprocal, dtype=d)withreciprocalthat rounded value.xmay also be an earlier result. Proof:proofs/mean.md.
er.mean.backward#
- backward(x, grad, axis=None, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
mean(x, axis, keepdims=keepdims)for the output gradientgrad.grad_xholds, at every element ofx, the gradient of the output it was averaged into divided by the number of reduced elements, inx's dtype: the exact quotient rounded once.tolerance()bounds that one division, asdividebounds it.gradmust have the output's shape.xandgradmay also be earlier results.
See also#
sum, whose additions the mean shares.
divide and reciprocal, whose division the gradient is.
PyTorch equivalents:
torch.meanon a CPU and on CUDA.