Algorithms#
An operation's result gives rounded, the exact answer rounded once to the
output format, and a tolerance: per element, how far a correct
implementation's output can be from rounded. That tolerance covers every
implementation that rounds only where the operation requires. Some
implementations fix one order of additions, accumulate in another format, run
on GPU tensor cores, or round a scalar operand to a format first. Others take
different steps: a fused attention kernel that rounds in extra places,
Welford's running variance, a reciprocal square root as one library
function, or a Fourier transform by one known plan of passes.
A named algorithm describes one such way of computing an operation, with its
own bounds measured from the operation's rounded.
An algorithm's tolerance(), finite_range(), may_be(), and covers()
work as a result's do. Their inputs may be earlier
results, passed in place of arrays as in a chain, and their
standard option is a result's, for the additions the algorithm does not
fix: "normal", the default, for normal accumulation (index order,
or SIMD lanes side by side), or "any_order" for any order of
additions at all.
Algorithms in the Guide explains when to use one. This page gives each constructor and class in full: the matmul algorithms, the tensor-core algorithms, the attention algorithm, the held-scalar algorithms, the reciprocal, elementary function, sqrt, rsqrt, var, softmax, and normalization algorithms, the FFT algorithms, their base classes, and the accumulation methods they build on.
matmul algorithms#
A matmul algorithm describes a kernel by its order of additions and its
accumulator format. When a kernel's order is known exactly, run() gives the
output that kernel must produce, bit for bit, and the algorithm's bounds can
be tighter than the operation's own tolerance.
Take a float32 kernel that splits each sum into blocks of 256 products, as a split-K kernel does: within a block it adds the rounded products in order, then it adds the block sums in order. Here it is written in PyTorch so the example runs anywhere, and it computes one attention head's query projection: 128 tokens of hidden size 4096 times a 4096 by 128 weight.
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The layer's input, and the weight slice of one head, in float32
x = torch.randn(128, 4096, generator=g)
w = torch.randn(4096, 128, generator=g) / 64
def split_k(a, b, block):
"""The kernel under test: in each block of the inner dimension, the
products rounded to float32 and added in order; then the block sums
added in order."""
out = None
for start in range(0, a.shape[1], block):
# The block's first product, then each next product added to it
part = a[:, start:start + 1] * b[start:start + 1]
for k in range(start + 1, start + block):
part = part + a[:, k:k + 1] * b[k:k + 1]
# The block's sum added to the running total
out = part if out is None else out + part
return out
# The algorithm that describes this kernel: products rounded to float32, blocks of 256
blocked = er.linalg.products.matmul_blocked("float32", 256, fma=False)
print("name:", blocked.name)
print("description:", blocked.description)
# run() emulates the kernel's order exactly: a correct kernel matches it bit for bit
emulated = blocked.run(x, w)
print("kernel matches run():", emulated.identical(er.asarray(split_k(x, w, 256))))
# The operation's reference: the exact product rounded once to float32
r = er.matmul(x, w)
# How many elements of the emulated output differ from it
differ = sum(e != f for e, f in zip(emulated.encodings(), r.rounded.encodings()))
print(f"differs from rounded: {100 * differ / emulated.size:.0f}%")
# The largest tolerance of the algorithm, and of the operation itself
print(f"algorithm's tolerance: {max(blocked.tolerance(x, w).scalars()):.3g}")
print(f"operation's own tolerance: {max(r.tolerance().scalars()):.3g}")
# The algorithm's bound for any inputs with 4096 products per element
print("error model:", blocked.error_model(4096))
name: matmul_blocked
description: Blocked summation of products rounded to float32, accumulated in float32, in blocks of 256
kernel matches run(): True
differs from rounded: 91%
algorithm's tolerance: 5.83e-05
operation's own tolerance: 0.000582
error model: 1.62e-05 * sum over k of |A[i,k] * B[k,j]| + 2.88e-42
The kernel matches run() bit for bit, yet in 91% of the elements it differs
from rounded. Over 4,096 products, a kernel that adds in a fixed order
mostly misses the correctly rounded answer, so a bit-for-bit comparison with
rounded would fail this correct kernel. The algorithm's tolerance is about
10 times smaller than the operation's own, because it allows for this one
order only. The error model is the bound as a formula in the inputs, for the
sum before its final rounding to the output format. It holds for any matrices
with 4,096 products per output element.
The constructors live in er.linalg.products:
- matmul_sequential(format: Format | str, *, fma: bool = True, accumulator_rounding: Rounding = Rounding.NEAREST_EVEN) MatmulAlgorithm#
Products added one at a time in index order, in
format.
- matmul_pairwise(format: Format | str, *, fma: bool = True, accumulator_rounding: Rounding = Rounding.NEAREST_EVEN) MatmulAlgorithm#
Products summed as a balanced binary tree, in
format.
- matmul_blocked(format: Format | str, block_size: int, *, fma: bool = True, accumulator_rounding: Rounding = Rounding.NEAREST_EVEN) MatmulAlgorithm#
Products summed sequentially in blocks of
block_size, then the block sums sequentially, informat.
- matmul_exact_accumulation(format: Format | str, *, accumulator_rounding: Rounding = Rounding.NEAREST_EVEN) MatmulAlgorithm#
Products summed exactly (a long accumulator), then rounded once to
format.
- matmul_slots16(format: Format | str, *, accumulator_rounding: Rounding = Rounding.NEAREST_EVEN) MatmulSlots16#
Products rounded to
formatand summed in 16 magnitude slots (MatmulSlots16).
Each returns an algorithm object with these methods. A MatmulAlgorithm
adds by one accumulation method: a summation order,
such as sequential or pairwise, whose depth is the most roundings any one
term passes through.
- class MatmulAlgorithm#
One fully specified matmul: each output element's k products, exact (fused multiply-add) or rounded to the accumulator format, summed by one accumulation method in that format, rounding to nearest (
accumulator_rounding: ties to even or away), then rounded to the output format (roundinginrunand the queries). Real floating-point inputs only.- run(A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Array#
This algorithm's output, emulated exactly (on the
roundedvalues of operands that are earlier results).
- error_model(k: int) ErrorModel#
The bound on the accumulated sum of k products, before the output rounding: the summation bound's growth factor and constant (
proofs/foundations.md, Lemma 2), rounded up to 128 bits. Raises ValueError where depth times u reaches 1, where that bound is not finite.
- covers(output, A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) Array#
Where this algorithm can produce
output, asResult.coversdescribes; the other arguments aretolerance's.
- finite_range(A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output of this algorithm per element, as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the other arguments aretolerance's.
- tolerance(A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) Array#
Worst-case
|output - matmul(A, B).rounded|per element over this algorithm's finite outputs, asResult.tolerancedescribes.AandBmay be earlier results; their tolerances are then taken withstandardandflush_to_zero(which change nothing for arrays).overflowis the implementation's overflow mode, as inmatmul, andworkersthe number of threads, as inResult.tolerance.
- class MatmulSlots16#
The 16-slot matmul (
proofs/matmul.md, The 16-slot algorithm): per output element, each product rounded to the accumulator format (to nearest,accumulator_rounding: ties to even or away), the finite products split by magnitude into 16 slots of one sixteenth of the format's precision each (in binades below the largest finite product; anything smaller goes to the last slot), each slot adding its values in increasing magnitude, alternating positive and negative values, and the slot sums then added from the smallest slot up; products that are not finite join that sum last, by IEEE rules. Real floating-point inputs only.
Tensor-core algorithms#
A tensor-core algorithm gives the bounds of a matmul or gemm that runs on GPU
tensor cores, from one MMAStep: what one tensor-core
instruction does to a block of products.
Tensor-core algorithms in the
Guide checks one on a layer's product, explains the step's parameters, and
lists Blackwell's values.
- class MMAStep(products: int, fraction_bits: int, exponent_floor: int, split: int)#
One tensor-core step (
proofs/foundations.md, Lemma T): up toproductsexact products and the float32 accumulator, aligned to the largest exponent (not belowexponent_floor), each truncated tofraction_bitsbits below it, added exactly, and the sum truncated to float32. The values are measured per GPU and input format (Khattak and Mikaitis, "Accurate Models of NVIDIA Tensor Cores", arXiv 2512.07004).splitstates how the kernels being checked split a sum into pieces: every piece but one holds a multiple ofsplitproducts (1: any split). CUTLASS splits K on multiples of 128 / element bits (8 for 16-bit inputs); a multiple ofproductscosts no extra steps. Each piece is summed in full steps: every step but the piece's last takesproductsproducts, as a tensor-core instruction takes a fixed number (zero padding counts among them). A kernel whose steps take fewer is outside this model.
- matmul_mma(step: MMAStep, *, reduction: Format | str | None = None) MatmulMMA#
A tensor-core matmul with
step's parameters (MatmulMMA).
- gemm_mma(step: MMAStep, *, reduction: Format | str | None = None) GemmMMA#
A tensor-core gemm with
step's parameters (GemmMMA).
- class MatmulMMA#
A tensor-core matmul (
proofs/matmul.md, Algorithms;proofs/foundations.md, Lemma T): each output element's products added by chains of tensor-core steps withstep's parameters, the chains' results optionally rounded to nearest inreduction(split-K partial sums in a lower precision) and added in float32 in any order, then rounded to the output format. Inputs: float16, bfloat16, or float32 holding tf32 values (round_to_tf32, rounding as the kernel converts); a float32 input must be an array, not an earlier result, whose stored values need not be tf32 values (float16 and bfloat16 earlier results are taken). It has norun(): kernels split and order the steps as they choose.standard="any_order"gives the same bound as the normal standard;flush_to_zero=Trueraises ValueError, as tensor-core steps keep subnormal values.- covers(output, A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) Array#
Where this algorithm can produce
output, asResult.coversdescribes; the other arguments aretolerance's.
- finite_range(A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output of this algorithm per element, as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the other arguments aretolerance's.
- tolerance(A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) Array#
Worst-case
|output - matmul(A, B).rounded|per element over this algorithm's finite outputs, asResult.tolerancedescribes.AandBmay be earlier results; their tolerances are then taken withstandardandflush_to_zero(which change nothing for arrays).overflowis the implementation's overflow mode, as inmatmul, andworkersthe number of threads, as inResult.tolerance.
- class GemmMMA#
A tensor-core gemm (
proofs/gemm.md, Tensor cores;proofs/foundations.md, Lemma T):matmul_mma's products, then alpha applied once and beta C added in a float32 epilogue rounding to nearest, then the rounding to the output format. Real inputs: A and B float16, bfloat16, or float32 holding tf32 values (the tensor cores multiply them in their own promoted format, whatever C's is), with float32 A and B arrays, not earlier results; C in a format float32 holds, as the epilogue holds it, and it may be any earlier result; alpha and beta must be float32 values; each batch's products on their own (it takes noreduce_batch). Norun();standard="any_order"gives the same bound as the normal standard;flush_to_zero=Trueraises ValueError, as tensor-core steps keep subnormal values.- tolerance(A, B, C, *, alpha=1, beta=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) Array#
Worst-case
|output - gemm(A, B, C, alpha=alpha, beta=beta).rounded|per element over this algorithm's finite outputs, asResult.tolerancedescribes;overflowis the implementation's overflow mode, as ingemm.
- finite_range(A, B, C, *, alpha=1, beta=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element, as
Result.finite_rangedescribes.
- may_be(kind: str, A, B, C, *, alpha=1, beta=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes.
- covers(output, A, B, C, *, alpha=1, beta=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, standard: str = 'normal', flush_to_zero: bool = False, workers: int | None = None) Array#
Where this algorithm can produce
output, asResult.coversdescribes.
Attention algorithms#
An attention algorithm describes the extra roundings of a fused attention kernel, such as FlashAttention's softmax over blocks of keys, and gives the bounds of any kernel that rounds there and at attention's required rounding steps (boundaries). Attention algorithms in the Guide checks PyTorch's CPU flash kernel with one and lists the methods for PyTorch's kernels.
The algorithm's methods take attention's arguments and a result's options,
among them
compute, the compute format a kernel rounds to and adds in along
the way (float32 by default for inputs narrower than float32, else the input
format), and ulps, how far functions such as exp may be off, in units in
the last place of the compute format. They give bounds per named output: the
forward's output and logsumexp, and the backward's grad_query,
grad_key, and grad_value.
- class AttentionAlgorithm(*, online_softmax: bool = False, block_size: int | None = None, exp2: bool = False, weights: Format | str | None = None, accumulate: Format | str | None = None, bias: Format | str | None = None, reciprocal: bool = False, backward_blocks: tuple[int, int] | None = None, exp_ulps: int | Fraction | None = None, mma: MMAStep | None = None, scale_ds: bool = False, rounded_p: bool = False, grouped_heads: bool = False, split_kv: int | None = None, fast_log: bool = False, probabilities: bool = False)#
A fused-kernel way of computing attention, described by its extra rounding points.
The reference is unchanged (
scaled_dot_product_attention); an algorithm has only bounds (tolerance()and the other viewsfinite_range(),may_be()andcovers(), each with abackward_form): how far an implementation that rounds at the required boundaries and at these points can be from the correct answer. It has norun(), because kernels differ in details these methods leave open. Methods, any combination:online_softmax: keys processed in blocks with a running maximum and sum, rescaling earlier partial sums byexp(old max - new max). Withblock_sizeNone, any blocking and order; otherwise at most ceil(S /block_size) blocks of at mostblock_sizekeys (as kernels split the keys: every block full but one), in any order.exp2: weights computed asexp2of logits in base-2 units (the scale times log2(e), and mask values times log2(e), held in the compute format withinulps).weights: the weights rounded to this format before the value product (and in the backward, P and dS before their products).accumulate: every accumulation in this format instead of the compute format.bias: float-mask values rounded to this format before they are added (a kernel computing ALiBi biases in lower precision).probabilities: the forward forms each probability, the weight divided by the row sum (or times its reciprocal withreciprocal), rounds it in the compute format (and toweightsif given), and then sums the probabilities times the values, with no division after: PyTorch's math path, which computessoftmaxand then its product with the values, withreciprocalon the CPU (its softmax multiplies by the row sum's reciprocal) and without it on CUDA. That path computes half-precision inputs in float32 (compute="float32") and pre-scales Q and K by the square root of the scale (pass the pre-scaled values with scale 1). Not withonline_softmax(orsplit_kv); the backward is unchanged, as its model already forms and rounds P.reciprocal: normalization by multiplying with the row sum's reciprocal, rounded once, instead of dividing: for the output, and for the backward's probabilities (PyTorch's CPU softmax and its CPU flash kernel do this). That kernel's forward for bfloat16 and float16 inputs also needsexp_ulps.exp_ulps: for a kernel with an approximate exp, each key's softmax exponential (exp, or exp2 withexp2) within this many ulps instead of the call'sulps, and where the exact result is below the compute format's smallest normal value, within that value of it (an exp that returns 0 or a wrongly encoded subnormal there). The logsumexp's log, online softmax's rescaling factors and the backward keepulps.mma: anMMAStep: the products' sums (the scores and the value sums, and in the backward the scores, dP and the three gradients' sums) by tensor-core steps with its parameters (proofs/foundations.md, Lemma T), in float32. The row sums and the backward's D keep the compute format. Needsweightsequal to the inputs' format (float16 or bfloat16), which P and dS are rounded to before their products; not withaccumulateorbackward_blocks.standard="normal"gives the any-order bound, and every row's bound is the step-by-step program's.split_kv: keys per split, a positive int, for a forward that cuts each row's keys into splits of this many consecutive keys (the last may be shorter), as FlashAttention-2's split-KV kernels do. Each split is an online softmax of its own (online_softmaxis required), whose value sums are normalized by its own row sum in the compute format and whose logsumexp is computed as the forward's. The splits are merged in the compute format: with M the largest split logsumexp, the logsumexp islog(sum exp(lse_i - M)) + Mand the outputsum exp(lse_i - logsumexp) O_i, rounded at each step, exp and log withinulps, sums in any order (as FlashAttention-2 merges). Every row's bound is the step-by-step program's.fast_log: the forward's logsumexp takes the log of the row sum withinulpsulps of the larger of its result and 1, as a fast logarithm does that is accurate in absolute terms near 1 (CUDA's__logf, which FlashAttention-2 calls); withsplit_kv, each split's log too.scale_ds: the backward multiplies dS by the scale, rounded once in the compute format, before its rounding toweights(cuDNN's and PyTorch's memory-efficient kernels), so grad_query and grad_key are not scaled after their sums (noscale_gradientsrounding). Not withbackward_blocks.rounded_p: the backward forms dS from P already rounded toweights(PyTorch's memory-efficient kernel). Needsweights.grouped_heads: the backward rounds each query head's grad_key and grad_value (each batch copy's too) to the output format, then adds them in the compute format in any order and rounds once more (PyTorch's fused kernels with grouped or broadcast key and value heads).standard="normal"gives the any-order bound; not withbackward_blocks.backward_blocks:(query_block, key_block), two positive ints, for a fused backward kernel that adds the gradients' products block by block into gradients held in the output format: grad_key and grad_value are rounded to it after each block ofquery_blockqueries (each query head of a group in turn), grad_query after each block ofkey_blockkeys, and the scale is applied to each block. This replaces those gradients' nested output roundings and, for grad_query and grad_key, thescale_gradientsrounding. Fused backward only (backward_tolerancewithoutandlogsumexp); a broadcast query, or a key or value broadcast across batch dimensions, raises ValueError (pass full-size inputs).
backward_tolerancegiven the forward's roundedoutandlogsumexpdescribes a fused backward kernel: it recomputesP = exp(logit - logsumexp)and takesD = sum grad * out. Without them it describes a backward that recomputes the softmax, as PyTorch's math path does.online_softmaxapplies to the forward only.Every input of
toleranceandbackward_tolerance,outandlogsumexpincluded, may also be an earlier result, asResultdescribes. The bounds are proven inproofs/attention_algorithms.md.- tolerance(query, key, value, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
Worst-case
|output - reference|per element ofoutputandlogsumexp, over this algorithm's finite outputs (Result.tolerance).The arguments are
scaled_dot_product_attention's (overflowthe implementation's overflow mode);compute,ulps,flush_to_zero,standardandworkersare as inResult.tolerance. Withonline_softmax,standard="normal"gives the any-order bound.
- finite_range(query, key, value, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
Per output, the lowest and highest finite output of this algorithm, as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, query, key, value, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
Per output, where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the other arguments aretolerance's.
- covers(outputs: dict, query, key, value, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
For each output named in
outputs({"output": ..., "logsumexp": ...}, either or both), where this algorithm can produce that value, asResult.coversdescribes; the other arguments aretolerance's.
- backward_tolerance(query, key, value, grad, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, out=None, logsumexp=None, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
Worst-case
|gradient - reference|per element ofgrad_query,grad_keyandgrad_value, over this algorithm's finite outputs. Given the forward's roundedoutandlogsumexp(any values of the right shapes; a non-finite logsumexp or output gives an infinite bound where it is used), for a fused backward kernel; without them, for a backward that recomputes the softmax.compute,ulps,flush_to_zero,standardandworkersare as inResult.tolerance.
- backward_finite_range(query, key, value, grad, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, out=None, logsumexp=None, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
Per gradient, the lowest and highest finite output of this algorithm, as
Result.finite_rangedescribes; the arguments arebackward_tolerance's.
- backward_may_be(kind: str, query, key, value, grad, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, out=None, logsumexp=None, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
Per gradient, where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the other arguments arebackward_tolerance's.
- backward_covers(gradients: dict, query, key, value, grad, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, out=None, logsumexp=None, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
For each gradient named in
gradients(grad_query,grad_key,grad_value), where this algorithm can produce that value, asResult.coversdescribes; the other arguments arebackward_tolerance's.
Held-scalar algorithms#
A held-scalar algorithm describes an add or a multiply that rounds each
scalar operand, and add's alpha, to a format before the operation, as
PyTorch's CPU kernels do.
alpha and scalar operands
checks PyTorch's add and mul with them and maps its kernels onto held.
- add_held_scalar(held: Format | str | Sequence[Format | str]) AddHeldScalar#
addwith each scalar operand andalphafirst rounded toheld, or to each format of a sequence in turn (AddHeldScalar).
- multiply_held_scalar(held: Format | str | Sequence[Format | str]) MultiplyHeldScalar#
multiplywith each scalar operand first rounded toheld, or to each format of a sequence in turn (MultiplyHeldScalar).
- class AddHeldScalar#
addwith each scalar operand andalphafirst rounded to nearest even toheld(proofs/add.md, Held scalars), asMultiplyHeldScalarrounds a scalar operand; thenadd's model runs on the held values.heldis"operand"(the array operands' promoted format),"compute"(the compute format, the queries'compute), a format, or a sequence of these rounded to in turn, as inMultiplyHeldScalar. The bounds are measured fromadd's reference, with the scalars as given;normal()is the normal answer at the held values. Real and complex floating-point inputs; an earlier result of shape () as the scalar raises ValueError. No backward and norun().PyTorch's CPU
addrounds a scalar operand andalphato the dtype first:"operand"for float32, complex64 and float16 (where PyTorch converts a float64 value to float16 in one rounding, asMultiplyHeldScalarsays),("float32", "operand")for bfloat16 and("complex64", "operand")for complex32, which PyTorch converts a float64 or complex128 value to through float32 or complex64. Withalphaother than 1, its bfloat16 and complex32 kernels, and its float16 kernel for some elements (of a short broadcast row), also storealpha * yin the dtype before the addition, a rounding this model does not have:add's chainadd(x, multiply(y, alpha, dtype=...))withalphaso rounded, whichany_ofcombines withadd.- tolerance(x, y, *, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - add(x, y, alpha=alpha).rounded|per element over this algorithm's finite outputs, asResult.tolerancedescribes; the arguments areadd's (overflowthe implementation's overflow mode) andResult.tolerance's.
- finite_range(x, y, *, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element, as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, y, *, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the other arguments aretolerance's.
- covers(output, x, y, *, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output, asResult.coversdescribes; the other arguments aretolerance's.
- normal(x, y, *, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, flush_to_zero: bool = False, workers: int | None = None) Array#
add's normal answer (Result.normal) with each scalar operand andalphaheld.
- class MultiplyHeldScalar#
multiplywith each scalar operand first rounded to nearest even toheld(proofs/multiply.md, Held scalars). A scalar operand is onemultiplytakes by its value: a Python scalar,FloatValueorComplexValue, or an array of shape () beside an operand with dimensions; a complex one is rounded part by part, and a value pastheld's range gives an infinity (NaN in a format without one), as a cast does. Thenmultiply's model runs on the held value.heldis"operand"(the array operands' promoted format),"compute"(the compute format, the queries'compute) or a format: for complex inputs a complex format, or the format of the parts. It may also be a sequence (list or tuple) of these, the scalar then rounded to each in turn, as an implementation that converts it through another format first does:("float32", "operand"). The bounds are measured frommultiply's reference, with the scalar as given, so the tolerance holds the scalar's rounding;normal()is the normal answer at the held value. Real and complex floating-point inputs; an earlier result of shape () as the scalar raises ValueError (the chainmultiply(s, 1, dtype=...)holds it, andmultiplytakes that). No backward and norun().PyTorch's CPU
mulrounds a scalar operand first, in a format that depends on the scalar's position:float16 and bfloat16 with the scalar as mul's second argument (
x * s,s * xwith a Python scalars,torch.mul(x, s)):"compute"(float32, which it computes in).float16 and bfloat16 with the scalar first (
torch.mul(s, x),s0d * xwith a tensors0dof shape ()): the dtype,"operand"for float16 and("float32", "operand")for bfloat16, which PyTorch converts a float64 value to through float32.float32 and complex64 in either position:
"operand".complex32 in either position:
("complex64", "operand"), as PyTorch converts a complex128 or float64 value to complex32 through complex64.
"operand"for float16 holds where PyTorch converts a float64 value to float16 in one rounding, as on aarch64 (Linux and macOS), where c10::Half converts from the platform's own half type; elsewhere, x86_64 included, c10::Half converts from float32, so the float64 value reaches float16 through float32:("float32", "operand").- tolerance(x, y, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - multiply(x, y).rounded|per element over this algorithm's finite outputs, asResult.tolerancedescribes; the arguments aremultiply's (overflowthe implementation's overflow mode) andResult.tolerance's.
- finite_range(x, y, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element, as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, y, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the other arguments aretolerance's.
- covers(output, x, y, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output, asResult.coversdescribes; the other arguments aretolerance's.
reciprocal algorithms#
er.reciprocal describes 1 / x rounded once. reciprocal_estimate
describes PyTorch's bfloat16 kernel on a Linux ARM CPU, which computes some
elements with Arm's reciprocal estimate, a hardware approximation accurate
to about 8 bits, instead.
PyTorch equivalents
says when it applies.
- reciprocal_estimate() ReciprocalEstimate#
The algorithm
ReciprocalEstimate: PyTorch's bfloat16reciprocalon a Linux ARM CPU.
- class ReciprocalEstimate#
PyTorch's bfloat16
reciprocalon a Linux ARM CPU: per element eitherreciprocal's value, correctly rounded (the kernel's scalar path), or Arm's reciprocal estimate ofxrounded to bfloat16 (its vector path,vrecpeq_f32: about 8 bits, up to 1.18 steps from the exact value). Which path an element takes depends on its position, the input's strides and the threads, and the two values are at most one step apart.coversandmay_behold where either path's do;toleranceandfinite_rangeare for the range holding both. The bounds are measured fromreciprocal's reference; withflush_to_zerothe estimate is the one with flush to zero (FPCR.FZ). The backward forms bound PyTorch's formula-grad * (result * result)on either path's result, each product rounded to bfloat16. bfloat16 inputs and outputs only;computeis bfloat16 and there is noulps. Norun()and no normal answer: the path depends on positions and threads (proofs/reciprocal.md, Arm's reciprocal estimate).- backward_covers(output, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient can be
output's value; the arguments afteroutputarebackward_tolerance's.
- backward_finite_range(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite gradient per element (each part of a complex element); the arguments are
backward_tolerance's.
- backward_may_be(kind: str, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient may be
kind; the arguments afterkindarebackward_tolerance's.
- backward_tolerance(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over the finite gradients of PyTorch's formula on this algorithm's result, the reference being the operation's backward'srounded; the arguments are the backward's andResult.tolerance's.
- covers(output, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output's value, asResult.coversdescribes; the arguments afteroutputaretolerance's.
- finite_range(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element (each part of a complex element), as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the arguments afterkindaretolerance's.
- tolerance(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over this algorithm's finite outputs, the reference being the operation'srounded, asResult.tolerancedescribes; the arguments are the operation's andResult.tolerance's.
Elementary function algorithms#
For a complex input, er.exp, er.log, and the other elementary functions
describe the sequence of real functions and rounded steps that PyTorch's
Linux CPU kernel computes. These algorithms describe the other kernels'
sequences, one method each, named for what it does. The pages
exp, expm1, log, and log1p,
tanh, and
sigmoid say which kernel computes
which. expm1_algorithm(difference=True) also takes real inputs: it
describes an expm1 computed as exp(x) - 1 from 0.1 in magnitude, as on
MPS.
- exp_algorithm(*, fused: bool = False, products: bool = False, ulps=None) FunctionAlgorithm#
A complex
expby another sequence (FunctionAlgorithm):fused, the Windows CPU's (MSVC's), whosec exp(x)for each part is one library routine, orproducts, MPS's:exp(x)as one library value with no scaling, so an infinity past the format, timescos(y)andsin(y), with no special case buty = 0.
- expm1_algorithm(*, difference: bool = False, ulps=None) FunctionAlgorithm#
A complex
expm1by another sequence (FunctionAlgorithm):difference, MPS's.
- log_algorithm(*, hypot: bool = False, sqrt_sum: bool = False, norm_log1p: bool = False, ulps=None) FunctionAlgorithm#
A complex
logby another sequence (FunctionAlgorithm):hypot, the macOS CPU's and CUDA's, which loses the real part next to the unit circle,sqrt_sum, MPS's, ornorm_log1p, the Windows CPU's (MSVC's).
- log1p_algorithm(*, squares: bool = False, direct: bool = False, norm_log1p: bool = False, ulps=None) FunctionAlgorithm#
A complex
log1pby another sequence (FunctionAlgorithm):squares, the macOS CPU's and CUDA's,direct, MPS's, ornorm_log1p, the Windows CPU's (the standard formula over MSVC's log).
- tanh_algorithm(*, double_angle: bool = False, kahan: bool = False, quotient: bool = False, sinh_beta: bool = False, ulps=None) FunctionAlgorithm#
A complex
tanhby another sequence (FunctionAlgorithm):double_angle, the macOS CPU's,kahan, CUDA's,quotient, MPS's, orsinh_beta, the Windows CPU's (MSVC's, Kahan's form in another order, its sinh one library routine).
- sigmoid_algorithm(*, scaled: bool = False, divided: bool = False, fused: bool = False, ulps=None) FunctionAlgorithm#
A complex
sigmoidby another sequence (FunctionAlgorithm):scaled, CUDA's,divided, MPS's, orfused, the Windows CPU's (the standard formula over MSVC's exp).
- class FunctionAlgorithm#
An elementary function of a complex input computed by another sequence of real library functions and rounded operations than the standard one, which is PyTorch's Linux CPU kernel's. The reference is the operation's own; the algorithm has bounds (
tolerance(),finite_range(),may_be()andcovers()): how far an implementation of this sequence can be from the exact value, each real library function within itsulpsunits in the last place in the compute format and each operation rounded, or fused into the sum that follows it.ulps, here or in a query, replaces every function's default. Complex inputs only, but forexpm1'sdifference, which also takes real inputs: Metal's real kernel is the library function below 0.1 in magnitude andexp(x) - 1from there. MPS's methods (exp'sproducts, expm1'sdifference, log'ssqrt_sum, sigmoid'sdivided, and tanh'squotient) take Metal's special values: a part their formula takes through a NaN may be NaN beside the reference. log1p'sdirect, MPS's too, gives the reference's own special values. MPS runs a complex32 kernel in float16, whichcompute="float16"describes. Norun()and no normal answer: the library functions fix no rounding sequence.- backward_covers(output, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient can be
output's value; the arguments afteroutputarebackward_tolerance's.
- backward_finite_range(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite gradient per element (each part of a complex element); the arguments are
backward_tolerance's.
- backward_may_be(kind: str, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient may be
kind; the arguments afterkindarebackward_tolerance's.
- backward_tolerance(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over the finite gradients of PyTorch's formula on this algorithm's result, the reference being the operation's backward'srounded; the arguments are the backward's andResult.tolerance's.
- covers(output, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output's value, asResult.coversdescribes; the arguments afteroutputaretolerance's.
- finite_range(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element (each part of a complex element), as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the arguments afterkindaretolerance's.
- tolerance(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over this algorithm's finite outputs, the reference being the operation'srounded, asResult.tolerancedescribes; the arguments are the operation's andResult.tolerance's.
sqrt algorithms#
er.sqrt describes a complex square root by the method the C libraries
share. sqrt_polar describes one computed through an angle, as CUDA's is.
The polar method checks a value with
it.
- sqrt_polar(ulps=None) SqrtPolar#
The algorithm
SqrtPolar: a complexsqrtby the polar method, each library function within itsulps.
- class SqrtPolar#
A complex
sqrtby the polar method, as PyTorch's CUDA kernels compute it:r = sqrt(hypot(a, b))andth = atan2(b, a) / 2, thenr * cos(th)andr * sin(th), each library function within itsulpsunits in the last place in the compute format and each product rounded (proofs/sqrt.md, sqrt_polar). The defaults are NVIDIA's documented accuracies: hypot and atan2 within 7/2 for a compute format of float32's precision or less and 5/2 for float64, cos and sin within 5/2, and a correctly rounded square root;ulps, here or in a query, replaces all of them. The bounds are measured fromsqrt's reference. The smaller part is only as accurate as the larger: beside the negative real axis the real part can be off by many units of its own last place, and can be negative. Where a part ofzis not finite the value issqrt's own. The backward forms bound PyTorch's formulagrad / (2 * conj(result))on this algorithm's result. Complex inputs only. Norun(), no normal answer and no error model: the library functions fix no rounding sequence, and the error depends on the angle.- backward_covers(output, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient can be
output's value; the arguments afteroutputarebackward_tolerance's.
- backward_finite_range(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite gradient per element (each part of a complex element); the arguments are
backward_tolerance's.
- backward_may_be(kind: str, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient may be
kind; the arguments afterkindarebackward_tolerance's.
- backward_tolerance(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over the finite gradients of PyTorch's formula on this algorithm's result, the reference being the operation's backward'srounded; the arguments are the backward's andResult.tolerance's.
- covers(output, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output's value, asResult.coversdescribes; the arguments afteroutputaretolerance's.
- finite_range(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element (each part of a complex element), as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the arguments afterkindaretolerance's.
- tolerance(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over this algorithm's finite outputs, the reference being the operation'srounded, asResult.tolerancedescribes; the arguments are the operation's andResult.tolerance's.
rsqrt algorithms#
er.rsqrt describes the square root followed by its reciprocal, each
rounded. rsqrt_direct describes one library function in their place, as
CUDA's rsqrtf is. A one-step rsqrt
checks a value with it. rsqrt_estimate describes PyTorch's bfloat16
kernel on a Linux ARM CPU, which computes some elements with Arm's
reciprocal estimate of the rounded square root.
- rsqrt_direct(ulps=None) RsqrtDirect#
The algorithm
RsqrtDirect:1 / sqrt(x)by one library function withinulps.
- class RsqrtDirect#
rsqrtby one library function: a value of the compute format withinulpsunits in the last place of the exact1 / sqrt(x), then the rounding to the output (proofs/rsqrt.md, rsqrt_direct).ulpsdefaults to 5/2 for a compute format of float32's precision or less and to 3/2 for float64, NVIDIA's documented accuracy of CUDA'srsqrtfandrsqrt(2 and 1 units from the correctly rounded result); a query's ownulpsreplaces it. The bounds are measured fromrsqrt's reference. The backward forms bound PyTorch's formula(-0.5 * grad) * result**3on this algorithm's result. Real, integer and bool inputs. Norun()and no normal answer: a one-step function fixes no rounding sequence.- error_model(compute: Format | str, dtype: Format | str | None = None) ErrorModel#
The bound for a compute format and an output format (default: the compute format):
ulpsunits of the compute format and half a unit of the output format, each relative to|1 / sqrt(x)|, with the subnormal ranges' units as the absolute term.
- backward_covers(output, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient can be
output's value; the arguments afteroutputarebackward_tolerance's.
- backward_finite_range(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite gradient per element (each part of a complex element); the arguments are
backward_tolerance's.
- backward_may_be(kind: str, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient may be
kind; the arguments afterkindarebackward_tolerance's.
- backward_tolerance(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over the finite gradients of PyTorch's formula on this algorithm's result, the reference being the operation's backward'srounded; the arguments are the backward's andResult.tolerance's.
- covers(output, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output's value, asResult.coversdescribes; the arguments afteroutputaretolerance's.
- finite_range(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element (each part of a complex element), as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the arguments afterkindaretolerance's.
- tolerance(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over this algorithm's finite outputs, the reference being the operation'srounded, asResult.tolerancedescribes; the arguments are the operation's andResult.tolerance's.
- rsqrt_estimate() RsqrtEstimate#
The algorithm
RsqrtEstimate: PyTorch's bfloat16rsqrton a Linux ARM CPU.
- class RsqrtEstimate#
PyTorch's bfloat16
rsqrt(andx.pow(-0.5)) on a Linux ARM CPU: per element eitherrsqrt's two roundings in bfloat16 (the kernel's scalar path), or Arm's reciprocal estimate of the rounded square root, itself rounded to bfloat16 (its vector path,sqrt().reciprocal()withvrecpeq_f32: the square root rounded to float32 and then to bfloat16; up to 1.70 steps from the exact value). Which path an element takes depends on its position, the input's strides and the threads, and the two values are at most one step apart.coversandmay_behold where either path's do;toleranceandfinite_rangeare for the range holding both. The bounds are measured fromrsqrt's reference; withflush_to_zeroa subnormal input reads as zero and the estimate is the one with flush to zero (FPCR.FZ). The backward forms bound PyTorch's formula(-0.5 * grad) * result**3on either path's result, the cube as two products, each step rounded to bfloat16. bfloat16 inputs and outputs only;computeis bfloat16 and there is noulps. Norun()and no normal answer: the path depends on positions and threads (proofs/rsqrt.md, Arm's reciprocal estimate).- backward_covers(output, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient can be
output's value; the arguments afteroutputarebackward_tolerance's.
- backward_finite_range(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite gradient per element (each part of a complex element); the arguments are
backward_tolerance's.
- backward_may_be(kind: str, x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient may be
kind; the arguments afterkindarebackward_tolerance's.
- backward_tolerance(x, /, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over the finite gradients of PyTorch's formula on this algorithm's result, the reference being the operation's backward'srounded; the arguments are the backward's andResult.tolerance's.
- covers(output, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output's value, asResult.coversdescribes; the arguments afteroutputaretolerance's.
- finite_range(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element (each part of a complex element), as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the arguments afterkindaretolerance's.
- tolerance(x, /, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per element (each part of a complex element) over this algorithm's finite outputs, the reference being the operation'srounded, asResult.tolerancedescribes; the arguments are the operation's andResult.tolerance's.
var algorithms#
er.var and er.std describe the two-pass method: the mean first, then the
squared deviations from it. var_welford describes Welford's running
method, which PyTorch uses for most reductions, and std_welford the square
root of its result. They take the same queries.
Welford's method checks outputs with
them.
- var_welford() VarWelford#
The algorithm
VarWelford:varby Welford's running method, under any merging of blocks.
- class VarWelford#
varby Welford's running method: each element updates a running mean and a running sum of squared deviations, and blocks computed apart are merged by Chan's formula, with the accumulators in the compute format (proofs/var.md, var_welford). PyTorch computes a variance this way wherever a reduction leaves more than one output: on the CPU with float64 accumulators for every dtype, socompute="float64"there (a 16-bit result is then converted through float32, which the bounds allow), and on CUDA with float32 accumulators for float32 and narrower dtypes, the default compute format. The bounds are measured fromvar's reference and cover the sequential method and any merging of blocks. Welford's error grows with the count and with the mean over the spread, so the bounds do too: they are worst-case bounds, and far wider than the two-pass method's on data with a large mean. Where the count times the unit roundoff of the compute format is above 1/16 there is no bound. Norun(), no normal answer and no error model: the rounding sequence depends on the merging, and the error on the data.- tolerance(x, axis=None, *, correction=1, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - var(x, axis).rounded.var|per element over this algorithm's finite outputs, asResult.tolerancedescribes; the arguments arevar's andResult.tolerance's.
- finite_range(x, axis=None, *, correction=1, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element, as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, axis=None, *, correction=1, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the arguments afterkindaretolerance's.
- covers(output, x, axis=None, *, correction=1, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output's value, asResult.coversdescribes; the arguments afteroutputaretolerance's.
- std_welford() StdWelford#
The algorithm
StdWelford:stdas the square root of Welford's variance.
- class StdWelford#
stdas the square root of Welford's variance (VarWelford), the root in the compute format and the result rounded to the output: PyTorch's reduction wherever it leaves more than one output, withcompute="float64"on a CPU and the default compute format on CUDA. The bounds are measured fromstd's reference. Norun()and no normal answer.
Softmax algorithms#
er.softmax, er.log_softmax, and er.logsumexp each describe one
sequence of steps. These algorithms describe the steps other kernels take
instead, and softmax_algorithm takes any of its methods together.
softmax and log_softmax and
logsumexp say which kernel takes
which.
- softmax_algorithm(*, reciprocal: bool = False, stored_exp: bool = False, products: bool = False, ulps=None) SoftmaxAlgorithm#
softmaxby another kernel's steps (SoftmaxAlgorithm): any ofreciprocal,stored_expandproducts.
- log_softmax_algorithm(*, stored_sum: bool = False, ulps=None) SoftmaxAlgorithm#
log_softmaxby another kernel's steps (SoftmaxAlgorithm):stored_sum.
- class SoftmaxAlgorithm#
softmaxorlog_softmaxby another kernel's steps (RowAlgorithm).softmax:reciprocal(the sum's reciprocal rounded once per row, then a product per element: PyTorch's CPU kernel for the last dimension, and MPS),stored_exp(any exponential may be rounded to the output's format before it is added or divided: PyTorch's CPU kernel for another dimension in float16 or bfloat16) andproducts(the backward asgrad * result - result * S: CUDA's).log_softmax:stored_sum(the sum and its logarithm rounded to the output's format first: PyTorch's CPU kernel for the last dimension in float16 or bfloat16). The kernel runs in the output's format:dtype's, else the input's, and for a backward the input's. The queries take nokeepdims.- backward_covers(output, x, grad, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient can be
output's value; the arguments afteroutputarebackward_tolerance's.
- backward_finite_range(x, grad, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite gradient per element; the arguments are
backward_tolerance's.
- backward_may_be(kind: str, x, grad, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient may be
kind; the arguments afterkindarebackward_tolerance's.
- backward_tolerance(x, grad, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - op.backward(x, grad, axis).rounded.grad_x|per element over the finite gradients of this algorithm's formula on its forward's result; the arguments are the backward's andResult.tolerance's.
- covers(output, x, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output's value, asResult.coversdescribes; the arguments afteroutputaretolerance's.
- finite_range(x, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element, as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the arguments afterkindaretolerance's.
- tolerance(x, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - op(x, axis).rounded|per element over this algorithm's finite outputs, asResult.tolerancedescribes; the arguments are the operation's andResult.tolerance's.
- logsumexp_algorithm(*, hypot: bool = False, sqrt_sum: bool = False, ulps=None) LogsumexpAlgorithm#
A complex
logsumexpwhose logarithm is another sequence (LogsumexpAlgorithm):hypot, the macOS CPU's and CUDA's, orsqrt_sum, MPS's.
- class LogsumexpAlgorithm#
logsumexpof a complex input with another complex logarithm than glibc's (RowAlgorithm):hypotorsqrt_sum, aslog_algorithmnames them.- backward_covers(output, x, grad, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient can be
output's value; the arguments afteroutputarebackward_tolerance's.
- backward_finite_range(x, grad, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite gradient per element; the arguments are
backward_tolerance's.
- backward_may_be(kind: str, x, grad, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where the gradient may be
kind; the arguments afterkindarebackward_tolerance's.
- backward_tolerance(x, grad, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - op.backward(x, grad, axis).rounded.grad_x|per element over the finite gradients of this algorithm's formula on its forward's result; the arguments are the backward's andResult.tolerance's.
- covers(output, x, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output's value, asResult.coversdescribes; the arguments afteroutputaretolerance's.
- finite_range(x, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output per element, as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the arguments afterkindaretolerance's.
- tolerance(x, axis=_UNSET, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - op(x, axis).rounded|per element over this algorithm's finite outputs, asResult.tolerancedescribes; the arguments are the operation's andResult.tolerance's.
Normalization algorithms#
er.rms_norm, er.layer_norm, and er.batch_norm describe the steps of
PyTorch's CPU kernels. These algorithms describe the steps other kernels
take instead, and their methods combine.
The normalizations' page says
which kernel takes which. A query takes the operation's arguments in order,
then compute, ulps, flush_to_zero, and standard by keyword. A
backward_ query takes x, grad, and then the operation's arguments.
- rms_norm_algorithm(*, rsqrt_ulps=None) NormAlgorithm#
rms_normwhose reciprocal square root is one library function withinrsqrt_ulpsunits in the last place (NormAlgorithm): CUDA's and MPS's kernels.
- layer_norm_algorithm(*, folded: bool = False, welford: bool = False, rsqrt_ulps=None) NormAlgorithm#
layer_normby another kernel's steps (NormAlgorithm): any offolded,welfordandrsqrt_ulps.
- batch_norm_algorithm(*, centered: bool = False, welford: bool = False, rsqrt_ulps=None) NormAlgorithm#
batch_normby another kernel's steps (NormAlgorithm): any ofcentered,welfordandrsqrt_ulps.
- class NormAlgorithm#
rms_norm,layer_normorbatch_normby another kernel's steps than the standard sequence, which is PyTorch's CPU kernel's. The reference is the operation's own; the algorithm has bounds (tolerance(),finite_range(),may_be()andcovers(), and the same of the backward withbackward_before the name). The methods:rsqrt_ulps(the square root and the division are one library function within that many units in the last place: CUDA's and MPS'srsqrt); forlayer_norm,folded(x * r + (-r * mean)before the weight and the bias: PyTorch's CPU kernel for float16 and bfloat16) andwelford(Welford's method over any merge tree: CUDA's); forbatch_norm,centered(the mean subtracted first, the two products in either order: PyTorch's CPU kernel for an input that is not contiguous, and CUDA's) andwelford(the statistics by Welford's method: CUDA's). A query takes the operation's arguments, thenResult.tolerance's by keyword. Norun()and no normal answer.- tolerance(*arguments, compute=None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', **options)#
Worst-case distance from the operation's reference per element over this algorithm's finite outputs, as
Result.tolerancedescribes; the positional arguments are the operation's.
- finite_range(*arguments, compute=None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', **options)#
The lowest and highest finite output per element, as
Result.finite_rangedescribes.
- may_be(kind: str, *arguments, compute=None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', **options)#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes.
- covers(output, *arguments, compute=None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', **options)#
Where this algorithm can produce
output's value, asResult.coversdescribes.
- backward_tolerance(*arguments, compute=None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', **options)#
The gradients' tolerances, by gradient; the positional arguments are the backward's (
x,grad, then the operation's).
- backward_finite_range(*arguments, compute=None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', **options)#
The gradients' lowest and highest finite values, by gradient.
- backward_may_be(kind: str, *arguments, compute=None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', **options)#
Where a gradient may be
kind, by gradient.
- backward_covers(output, *arguments, compute=None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', **options)#
Where the gradients can be
output's values (a dict by gradient), by gradient.
FFT algorithms#
An FFT algorithm describes a Fourier transform library by its plan: for each transformed axis, the passes that compute it, each a radix or a Bluestein pass. A plan of radix passes gives bounds never wider than the transform's own tolerance, which allows for every factorization. A plan with a Bluestein pass gives a proven bound where the transform's own is only measured. FFT algorithms in the Guide checks NumPy's FFT with pocketfft's plans and lists the libraries' plans.
- class FFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#
fftby a plan (_FFTAlgorithm):planthe passes of each axis, each a radix or aBluesteinpass;path"real" or "packed" for a real input's last axis (the real passes, or the packed form, whose plan is for n/2), "complex" otherwise;backward_planthe backward's (a complex transform), needed unlesspathis "complex", where it defaults toplan.- backward_covers(gradients: dict, x, grad, n=None, axis=-1, norm=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
For the gradient named in
gradients({"grad_x": output}, orgrad_Xfor ifft and irfft), where this algorithm can produce that value, asResult.coversdescribes; the other arguments arebackward_tolerance's.
- backward_finite_range(x, grad, n=None, axis=-1, norm=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
The lowest and highest finite gradient per element, by name; the arguments are
backward_tolerance's.
- backward_may_be(kind: str, x, grad, n=None, axis=-1, norm=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
Where this algorithm's gradient may be
kind, by name; the other arguments arebackward_tolerance's.
- backward_tolerance(x, grad, n=None, axis=-1, norm=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Outputs#
Worst-case
|gradient - reference|per part over this algorithm's finite gradients, by name (grad_x, orgrad_Xfor ifft and irfft), the backward's transform bybackward_plan(by default the forward's plan where its transform is of the forward's kind). The arguments are the operation's backward's; the rest aretolerance's.
- covers(output, x, n=None, axis=-1, norm=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm can produce
output, asResult.coversdescribes; the other arguments aretolerance's.
- error_model(compute: Format | str, norm=None, *, ulps=None, flush_to_zero: bool = False) ErrorModel#
The plan's error formula for its lengths, in the compute format
compute(a complex one's parts' format) with the operation'snorm:|error| <= relative * M + absolutefor each part before its final rounding, M the inputs' mass (proofs/fft.md, Algorithms, The error model). It is the first form of the bound, for exact inputs;tolerance()also takes the second, against sqrt(n) times the inputs' 2-norm, where that is smaller.ulpsandflush_to_zeroare as inResult.tolerance.
- finite_range(x, n=None, axis=-1, norm=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array]#
The lowest and highest finite output of this algorithm per element, as
Result.finite_rangedescribes; the arguments aretolerance's.
- may_be(kind: str, x, n=None, axis=-1, norm=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Where this algorithm may output
kind("+inf","-inf"or"nan"), asResult.may_bedescribes; the other arguments aretolerance's.
- tolerance(x, n=None, axis=-1, norm=None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, compute: Format | str | None = None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array#
Worst-case
|output - reference|per part over this algorithm's finite outputs (Result.tolerance).The arguments are the operation's (
overflowthe implementation's overflow mode);compute,ulps,flush_to_zero,standard, andworkersare as inResult.tolerance.
- class IFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#
ifftby a plan, asFFTAlgorithm.
- class RFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#
rfftby a plan, asFFTAlgorithm:paththe last axis's (its real input's);backward_planthe backward's complex transform, needed unlesspathis "complex".
- class IRFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#
irfftby a plan, asFFTAlgorithm:paththe real outputs' ("complex" on W or its Hermitian completion, "real" the backward real passes, "packed" the packed real-output form);backward_planandbackward_paththe backward's real-input transform, by defaultplanandpath.
- class HFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#
hfftby a plan, asIRFFTAlgorithm.
- class IHFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#
ihfftby a plan, asRFFTAlgorithm.
- class Bluestein(length: int, padded: int, radices: tuple)#
A Bluestein pass in an FFT algorithm's plan (proofs/fft.md, Bluestein passes): the transform of
lengthp values as a cyclic convolution ofpaddedlength n2 >= 2p - 1, the convolution's three transforms of n2 by passes ofradices(complex radices whose product is n2). pocketfft's padded length isgood_size_cmplx(2p - 1), DUCC's too.
Base classes#
Every named algorithm on this page is an er.Algorithm, and error_model()
returns an er.ErrorModel.
- class Algorithm#
Base for named algorithms: one implementation of an operation, with its
op,nameanddescription, the bounds of its outputs on actual inputs (tolerance,finite_range,may_beandcovers), and, where its rounding sequence is fully specified,run.
- class ErrorModel(relative: Fraction, absolute: Fraction, scale: str)#
|error| <= relative * scale + absolute, withscalenaming the input quantity.
Accumulation methods#
er.accumulation describes summation orders on their own, without a format,
for any list of terms: exact, sequential, pairwise, and blocked, plus
ANY_ORDER for every order and MMA_METHOD for the steps of tensor cores. Each fixed order reports its depth, the most
roundings any one term passes through, and its total number of roundings.
The textbook worst-case error bound is built on these two numbers.
Eight terms, with a dot at every rounding. Sequential summation starts from an exact zero, so term 1 passes through all 8 roundings. Pairwise summation rounds each term, then adds in three levels, so every term passes through 4.
The depth decides how large the worst case can be. Here are the depths for a sum of 4,096 terms, as in one output element of a layer of hidden size 4096:
from exactref.accumulation import get_method
# The length of the sum
n = 4096
# Sequential and pairwise summation: depth and total roundings
for key in ("sequential", "pairwise"):
method = get_method(key)
print(f"{key}: depth {method.depth(n)}, roundings {method.roundings(n)}")
# Blocked summation takes the block size
blocked_method = get_method("blocked")
print(f"blocked by 64: depth {blocked_method.depth(n, block_size=64)}, "
f"roundings {blocked_method.roundings(n, block_size=64)}")
sequential: depth 4096, roundings 4096
pairwise: depth 13, roundings 8191
blocked by 64: depth 127, roundings 4160
Pairwise summation rounds about twice as often as sequential summation, but
no term passes through more than 13 of those roundings. The worst-case bound
grows with the depth: it is about the depth times the
unit roundoff u, times the sum of the terms' magnitudes. In float32 at
4,096 terms, that is about 2.4e-4 for the sequential order, 7.6e-6 for blocks
of 64, and 7.7e-7 for the pairwise tree, the numbers the
error models in the Guide print.
The exact bound below also adds, about once per rounding, eta, the largest
absolute error of a rounding to a subnormal result.
Accumulation methods: how an implementation may add up a list of terms.
Each method in METHODS is a fully specified summation order, which the matmul
algorithms' run() emulates exactly; ANY_ORDER and MMA_METHOD describe
families of orders, for tolerances only. For tolerances,
a method of METHODS reports depth (the most roundings any one term passes through) and
roundings (the total), which give the standard worst-case bound
|computed - exact| <= gamma(depth) * sum|t_i| + roundings * eta * (1 + gamma(depth))
with gamma(n) = n*u / (1 - n*u) (Higham, Accuracy and Stability of
Numerical Algorithms, 2nd ed., chapters 3-4). The exact method sums
exactly and rounds once, which no implementation can beat.
- get_method(key: str) AccumulationMethod#
The accumulation method named
key: one ofMETHODS,"any_order"or"mma"(ValueError for any other).
- class AccumulationMethod#
An accumulation method: its
key, a shortlabeland adescription, whether its result depends on the order of the terms, theparametersit takes (such asblock_size) and itsreferences. For a method ofMETHODS,depth(n)androundings(n)give the worst-case bound's counts fornterms (the module docstring);ANY_ORDERandMMA_METHODhave none.
- METHODS#
A dict from each fixed summation order's key (
"exact","sequential","pairwise","blocked") to its method.
- ANY_ORDER#
Every way to sum the terms: any tree of additions or fused multiply-adds, where a term may also be rounded on its own first.
get_method("any_order")returns it.
- MMA_METHOD#
Chains of tensor-core steps added in any order, the summation of the tensor-core algorithms.
get_method("mma")returns it.