var#
A variance measures how far values spread around their mean: the squared distances from the mean, summed and divided by the count. Batch normalization, layer normalization, and feature standardization divide by its square root. It is easy to compute badly. When the mean is large beside the spread, the textbook formula, the mean of the squares less the square of the mean, subtracts two nearly equal numbers.
In ExactRef, er.var(x, axis=None, *, correction=1, keepdims=False), also
er.statistics.descriptive.dispersion.var, is the variance over the
dimensions in axis, as in torch.var. It returns two
named outputs, var and mean, so it also stands for
torch.var_mean. correction is subtracted from the count in the divisor:
1 gives the sample variance, PyTorch's default, and 0 the population
variance. It takes floating-point and complex inputs. A complex input's
variance is real: the variance of the real parts plus that of the imaginary
parts.
Each var element is the exact variance rounded once: the
reference. ExactRef forms it from the exact sums of the elements and
of their squares, so no cancellation touches it, however large the mean.
The mean output is mean's.
The tolerance covers the two-pass method. It takes the mean first, then the sum of the squared distances from it, then divides by the count less the correction, each step rounded in the compute format. PyTorch's CPU computes a float32 or float64 variance this way when the reduction leaves a single output. It takes the steps after the mean in float64, which the tolerance also covers. The bound grows with the count. Past 8,388,608 elements per output with float32 steps, or 2**52 with float64 steps, there is none, and the tolerance is infinite. With float16 steps the limit is 1,024 elements, and with bfloat16 steps 128.
PyTorch's other variance kernels use Welford's method. It updates a running
mean and a running sum of squared distances with each element, and merges
blocks computed apart. Its error grows with the count and with how large
the mean is beside the spread, so it has its own algorithm,
var_welford:
er.var's tolerance covers the two-pass method, and var_welford's covers
Welford's.
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 |
|
|
what the count is reduced by in the divisor: an integer, or a fraction with a denominator of at most 2**20, such as |
|
|
keep the reduced dimensions with size 1 |
|
|
the format of the |
the input's format, or its parts' for a complex input |
|
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#
An initialization check takes the variance of a whole weight matrix. Here is a float32 weight of the size of GPT-2's MLP layers, 3072 by 768, reduced to one output:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# A weight of 3072 by 768, initialized with standard deviation 0.02
w = torch.randn(3072, 768, generator=g) * 0.02
# ExactRef's result: two named outputs
r = er.var(w)
print("outputs:", list(r.rounded))
# Could a correct implementation produce PyTorch's variance, and its mean?
print("var covered:", r["var"].covers(w.var()).all())
print("mean covered:", r["mean"].covers(w.mean()).all())
outputs: ['var', 'mean']
var covered: True
mean covered: True
A large mean#
The reference does not lose the variance to a large mean. Here are 65,536 float64 readings near 1e8 with a spread of about 1. The textbook formula cancels to a wrong answer, and PyTorch's two passes do not:
# 65,536 float64 readings near 1e8, with a spread of about 1
readings = torch.randn(65536, generator=g, dtype=torch.float64) + 1e8
rr = er.var(readings)
print("reference:", rr["var"].rounded.tolist())
# The textbook formula: the mean of the squares less the square of the mean,
# times n / (n - 1) for the sample variance
n = readings.numel()
textbook = ((readings * readings).mean() - readings.mean() ** 2) * n / (n - 1)
print("textbook covered:", rr["var"].covers(textbook).all())
# PyTorch's two passes
print("PyTorch covered:", rr["var"].covers(readings.var()).all())
reference: 1.0028973851179956
textbook covered: False
PyTorch covered: True
Special values#
Where the count less the correction is 0 or less, there is nothing to divide by. ExactRef follows PyTorch: infinity, or NaN where every element equals the mean. So one sample's variance with the default correction is NaN, and so is the variance of no elements:
# Three values with correction 3, one value, and no values
three = er.asarray([1.0, 2.0, 4.0], "float32")
print("correction 3:", er.var(three, correction=3)["var"].rounded.tolist())
print("one element:", er.var(er.asarray([5.0], "float32"))["var"].rounded.tolist())
print("no elements:", er.var(er.asarray([], "float32"))["var"].rounded.tolist())
correction 3: inf
one element: nan
no elements: nan
Welford's method#
PyTorch's CPU uses Welford's method with float64 accumulators where a
reduction leaves more than one output, such as the variance of each row,
and for every bfloat16 and float16 variance. CUDA uses it with float32
accumulators for float32 and narrower inputs. Check these with
var_welford(), with compute="float64" for the CPU and the default for
CUDA. Its covers() takes the output first, then var's arguments:
from exactref.statistics.descriptive.dispersion import var_welford
# 256 rows of 4096 float32 values, and PyTorch's variance of each row
rows = torch.randn(256, 4096, generator=g) * 2 + 0.5
out = rows.var(dim=1)
# Welford's method with float64 accumulators
print("covered:", var_welford().covers(out, rows, 1, compute="float64").all())
covered: True
On data with a large mean the two methods part ways. PyTorch's Welford
kernel lands outside the two-pass tolerance on rows of readings near 1e8,
and inside var_welford's:
# 64 rows of 1000 float64 readings near 1e8, and PyTorch's variance of each row
far = torch.randn(64, 1000, generator=g, dtype=torch.float64) + 1e8
far_out = far.var(dim=1)
print("covered by er.var:", er.var(far, 1)["var"].covers(far_out).all())
print("covered by var_welford:", var_welford().covers(far_out, far, 1, compute="float64").all())
covered by er.var: False
covered by var_welford: True
var_welford's bounds hold for any way of merging blocks, so they are
wide. With float32 accumulators, as on CUDA, the bound for one
batch-normalization channel of 64 by 56 by 56 standard normal values is
about ten times the variance itself.
var algorithms has its full
specification.
Backward#
er.var.backward(x, grad, axis=None, correction=1, keepdims=False), or
r.backward(grad), returns grad_x, the gradient for the var output:
2 * grad * (x - mean) / (count - correction) at every element, rounded
once. The tolerance covers PyTorch's formula,
(2 / (count - correction)) * grad * (x - mean), with each step rounded in
the compute format:
# The gradient of each row's variance
gy = torch.randn(256, generator=g)
# PyTorch's autograd, on a copy that records gradients
rows_ = rows.clone().requires_grad_()
rows_.var(dim=1).backward(gy)
# ExactRef's gradient, held by name
gb = er.var.backward(rows, gy, axis=1)
print("outputs:", list(gb.rounded))
print("grad_x covered:", gb["grad_x"].covers(rows_.grad).all())
outputs: ['grad_x']
grad_x covered: True
PyTorch's float16 and bfloat16 autograd rounds each step of that formula to
the dtype. Pass compute= the dtype to covers() there. The default takes
the steps in float32 and can reject those gradients.
Full specification#
er.var#
- var(x, axis=None, *, correction=1, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The variance over
axis(None: every dimension; an int or a tuple of ints), with the outputsvarandmean, keeping the reduced dimensions as 1 withkeepdims.varis the sum of the squared deviations from the mean divided by the count lesscorrection(1: the sample variance, as in PyTorch; 0: the population variance; any integer, or a fraction with a denominator of at most 2**20, such as 0.5). Each element is that exact value rounded once todtype(default: the input's format, or its parts' format for a complex input), a floating-point format. It is formed as one fraction from the exact sums of the elements and of their squares, so no cancellation touches it. A complex input's variance is real: its real and imaginary parts' variances added. Where the count less the correction is 0 or less, the value is infinity, or NaN where every deviation is 0, as PyTorch gives.meanismean's output. Floating-point and complex inputs; integer and bool inputs raise.tolerance()bounds the two-pass method in the compute format: the mean asmeanbounds it, then each deviation, its square, their sum in any order, and one division. That covers PyTorch's reduction to a single output on the CPU. The bound grows with the count, and there is none where twice the count times the unit roundoff of the compute format is above 1 (8,388,608 elements in float32) or the format has fewer than 8 bits of precision. Welford's running method, which PyTorch uses elsewhere, isvar_welford.xmay also be an earlier result. Proof:proofs/var.md.
er.var.backward#
- backward(x, grad, axis=None, *, correction=1, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
var(x, axis, correction=correction, keepdims=keepdims)'svaroutput for its gradientgrad.grad_x = 2 * grad * (x - mean) / (count - correction)at every element ofx, inx's dtype: the exact value rounded once.tolerance()bounds PyTorch's formula in the compute format,(2 / (count - correction)) * grad * (x - mean)with that scalar rounded to the dtype, as products of this library on the mean's result. For a float16 or bfloat16xPyTorch's CPU kernel takes the steps in the dtype, whichcompute=the dtype describes.gradis real and must have the output's shape.xandgradmay also be earlier results.
See also#
mean, which is the second output and the first pass.
std, the square root of the variance.
var algorithms:
var_welford.PyTorch equivalents:
torch.varandtorch.var_meanon a CPU and on CUDA.