std#
A standard deviation is the square root of a variance: how far values spread around their mean, in the values' own unit. Normalization layers divide by it, and so does standardizing a feature to zero mean and unit spread.
In ExactRef, er.std(x, axis=None, *, correction=1, keepdims=False), also
er.statistics.descriptive.dispersion.std, is the standard deviation over
the dimensions in axis, as in torch.std. It returns two
named outputs, std and mean, as var returns var and
mean, and takes the same correction. It takes floating-point and complex
inputs. A complex input's standard deviation is the root of its variance,
which is real.
Each std element is the square root of the exact variance, rounded once:
the reference. ExactRef never rounds the variance on the way. The
square root of var's output rounds twice, and can land on the neighboring
float, so it is not always std:
Rounding the variance first can push its root past the midpoint between two floats.
The tolerance covers var's two-pass method followed by one square
root, each step rounded in the compute format, then the rounding to
the output format. The square root is correctly rounded by default. ulps,
an option of tolerance() and covers(), allows a root that is off by
more. As for var, the bound grows with the count, and past 8,388,608
elements per output with float32 steps there is none. Where the count less
the correction is 0 or less, the value is infinity, or NaN where every
element equals the mean.
Where a reduction leaves several outputs, and on CUDA, PyTorch computes each
variance by Welford's method instead. The algorithm std_welford
describes that, as var_welford does for var
(Welford's method).
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#
Layer normalization divides each token's features by their spread. Here
are 1024 tokens with 4096 float32 features each. A reduction with several
outputs, one per token, takes PyTorch's CPU through Welford's method with
float64 accumulators, so check it with std_welford() and
compute="float64". On CUDA, use the default compute format.
import torch
import exactref as er
from exactref.statistics.descriptive.dispersion import std_welford
# 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 standard deviation per token
r = er.std(x, axis=1)
print("outputs:", list(r.rounded))
# std_welford's covers() takes the output first, then std's arguments
print("covered:", std_welford().covers(torch.std(x, 1), x, 1, compute="float64").all())
outputs: ['std', 'mean']
covered: True
std is not sqrt(var)#
The square root of var's output, for the same tokens, differs from std
on some of them:
# Each token's std, and the root of each token's rounded variance
once = r.rounded["std"].tolist()
twice = er.sqrt(er.var(x, axis=1)["var"]).rounded.tolist()
print("tokens where the two differ:", sum(a != b for a, b in zip(once, twice)), "of 1024")
tokens where the two differ: 126 of 1024
One output#
A reduction to a single output takes PyTorch's CPU through two passes: the mean in the input's format, then the squared distances, their sum, the division, and the root in float64. The default tolerance covers it:
# A million float32 values, reduced to one output
y = torch.randn(1 << 20, generator=g) * 3 + 0.5
ry = er.std(y)
print("reference:", ry["std"].rounded.tolist())
print("tolerance:", ry["std"].tolerance().tolist())
print("covered:", ry["std"].covers(torch.std(y)).all())
reference: 2.999878406524658
tolerance: 0.10384249687194824
covered: True
With float32 steps over a million elements, the bound is wide: about 3.5%
of the value here. compute="float64" assumes every step in float64, the mean
included, and is a far tighter check. PyTorch rounds its mean to float32,
so on data whose mean is many thousand times its spread, that check can
reject PyTorch's output.
Backward#
er.std.backward(x, grad, axis=None, correction=1, keepdims=False), or
r.backward(grad), returns grad_x:
grad * (x - mean) / ((count - correction) * std) at every element, the
exact value rounded once. Where the standard deviation is 0 the gradient is
0, as PyTorch sets it. The tolerance covers PyTorch's formula on the
forward's result: grad / (2 * std), then var's gradient for that
quotient.
# 512 tokens of 768 features, and the gradient of each token's std
h = torch.randn(512, 768, generator=g)
gy = torch.randn(512, generator=g)
# PyTorch's autograd, on a copy that records gradients
h_ = h.clone().requires_grad_()
torch.std(h_, 1).backward(gy)
# ExactRef's gradient, held by name
gb = er.std.backward(h, gy, axis=1)
print("outputs:", list(gb.rounded))
print("grad_x covered:", gb["grad_x"].covers(h_.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.std#
- std(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 standard deviation over
axis(None: every dimension; an int or a tuple of ints), with the outputsstdandmean, keeping the reduced dimensions as 1 withkeepdims.Each element of
stdis the square root of the exact variance (var's value, with the samecorrection) rounded once todtype(default: the input's format, or its parts' format for a complex input), a floating-point format. The variance is one exact fraction and its root is rounded by integers, so no cancellation and no double rounding touch it:stdis not always the square root ofvar's rounded output. Where the count less the correction is 0 or less, the value is infinity, or NaN where every deviation is 0.meanismean's output. Floating-point and complex inputs; integer and bool inputs raise.tolerance()bounds the two-pass method in the compute format, asvarbounds it, followed by one square root there (correctly rounded;ulpswidens it) and the rounding to the output. PyTorch's reduction to a single output on a CPU rounds its mean to the input's format and takes the other steps in float64; the default compute format holds it, andcompute="float64", which holds the mean in float64, does not where the mean is large beside the spread. Welford's running method, which PyTorch uses for several outputs, isstd_welford.xmay also be an earlier result. Proof:proofs/std.md.
er.std.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
std(x, axis, correction=correction, keepdims=keepdims)'sstdoutput for its gradientgrad.grad_x = grad * (x - mean) / ((count - correction) * std)at every element ofx, inx's dtype: the exact value rounded once, a signed square root of a fraction rounded by integers. Where the standard deviation is 0 the gradient is 0, as PyTorch sets it.tolerance()bounds PyTorch's formula in the compute format:grad / (2 * result)on the forward's result, set to 0 where the result is 0, thenvar's gradient formula on that quotient. 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#
var: the variance, and Welford's method.
sqrt and rsqrt: the root's own rounding, and
ulps.var algorithms:
std_welford.PyTorch equivalents:
torch.stdon a CPU and on CUDA.