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:

variance exact variance var's output root exact root root of var's output midpoint std sqrt of var

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

x

the input: floating-point or complex; integer and bool inputs raise TypeError

required

axis

the dimensions to reduce: an int, a tuple of ints, or None for all

None

correction

what the count is reduced by in the divisor: an integer, or a fraction with a denominator of at most 2**20, such as 0.5

1

keepdims

keep the reduced dimensions with size 1

False

dtype

the format of the std output, a floating-point format

the input's format, or its parts' for a complex input

rounding

the rounding mode of the reference and of a correct implementation's final rounding into the output format

er.Rounding.NEAREST_EVEN

overflow

what a result past the output format's range becomes: "ieee", "saturate", or "nan"

each format's own rule

workers

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.

Code
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())
Output
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:

Code
# 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")
Output
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:

Code
# 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())
Output
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.

Code
# 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())
Output
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 outputs std and mean, keeping the reduced dimensions as 1 with keepdims.

Each element of std is the square root of the exact variance (var's value, with the same correction) rounded once to dtype (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: std is not always the square root of var's rounded output. Where the count less the correction is 0 or less, the value is infinity, or NaN where every deviation is 0. mean is mean's output. Floating-point and complex inputs; integer and bool inputs raise.

tolerance() bounds the two-pass method in the compute format, as var bounds it, followed by one square root there (correctly rounded; ulps widens 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, and compute="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, is std_welford. x may 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)'s std output for its gradient grad.

grad_x = grad * (x - mean) / ((count - correction) * std) at every element of x, in x'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, then var's gradient formula on that quotient. For a float16 or bfloat16 x PyTorch's CPU kernel takes the steps in the dtype, which compute= the dtype describes. grad is real and must have the output's shape. x and grad may also be earlier results.

See also#