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.

Code
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))
Output
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, in format.

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 format and 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 (rounding in run and 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 rounded values 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, as Result.covers describes; the other arguments are tolerance'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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the other arguments are tolerance'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, as Result.tolerance describes.

A and B may be earlier results; their tolerances are then taken with standard and flush_to_zero (which change nothing for arrays). overflow is the implementation's overflow mode, as in matmul, and workers the number of threads, as in Result.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 to products exact products and the float32 accumulator, aligned to the largest exponent (not below exponent_floor), each truncated to fraction_bits bits 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).

split states how the kernels being checked split a sum into pieces: every piece but one holds a multiple of split products (1: any split). CUTLASS splits K on multiples of 128 / element bits (8 for 16-bit inputs); a multiple of products costs no extra steps. Each piece is summed in full steps: every step but the piece's last takes products products, 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 with step's parameters, the chains' results optionally rounded to nearest in reduction (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 no run(): kernels split and order the steps as they choose. standard="any_order" gives the same bound as the normal standard; flush_to_zero=True raises 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, as Result.covers describes; the other arguments are tolerance'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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the other arguments are tolerance'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, as Result.tolerance describes.

A and B may be earlier results; their tolerances are then taken with standard and flush_to_zero (which change nothing for arrays). overflow is the implementation's overflow mode, as in matmul, and workers the number of threads, as in Result.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 no reduce_batch). No run(); standard="any_order" gives the same bound as the normal standard; flush_to_zero=True raises 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, as Result.tolerance describes; overflow is the implementation's overflow mode, as in gemm.

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_range describes.

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"), as Result.may_be describes.

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, as Result.covers describes.

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 views finite_range(), may_be() and covers(), each with a backward_ form): how far an implementation that rounds at the required boundaries and at these points can be from the correct answer. It has no run(), 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 by exp(old max - new max). With block_size None, any blocking and order; otherwise at most ceil(S / block_size) blocks of at most block_size keys (as kernels split the keys: every block full but one), in any order.

  • exp2: weights computed as exp2 of logits in base-2 units (the scale times log2(e), and mask values times log2(e), held in the compute format within ulps).

  • 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 with reciprocal), rounds it in the compute format (and to weights if given), and then sums the probabilities times the values, with no division after: PyTorch's math path, which computes softmax and then its product with the values, with reciprocal on 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 with online_softmax (or split_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 needs exp_ulps.

  • exp_ulps: for a kernel with an approximate exp, each key's softmax exponential (exp, or exp2 with exp2) within this many ulps instead of the call's ulps, 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 keep ulps.

  • mma: an MMAStep: 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. Needs weights equal to the inputs' format (float16 or bfloat16), which P and dS are rounded to before their products; not with accumulate or backward_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_softmax is 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 is log(sum exp(lse_i - M)) + M and the output sum exp(lse_i - logsumexp) O_i, rounded at each step, exp and log within ulps, 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 within ulps ulps 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); with split_kv, each split's log too.

  • scale_ds: the backward multiplies dS by the scale, rounded once in the compute format, before its rounding to weights (cuDNN's and PyTorch's memory-efficient kernels), so grad_query and grad_key are not scaled after their sums (no scale_gradients rounding). Not with backward_blocks.

  • rounded_p: the backward forms dS from P already rounded to weights (PyTorch's memory-efficient kernel). Needs weights.

  • 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 with backward_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 of query_block queries (each query head of a group in turn), grad_query after each block of key_block keys, and the scale is applied to each block. This replaces those gradients' nested output roundings and, for grad_query and grad_key, the scale_gradients rounding. Fused backward only (backward_tolerance with out and logsumexp); a broadcast query, or a key or value broadcast across batch dimensions, raises ValueError (pass full-size inputs).

backward_tolerance given the forward's rounded out and logsumexp describes a fused backward kernel: it recomputes P = exp(logit - logsumexp) and takes D = sum grad * out. Without them it describes a backward that recomputes the softmax, as PyTorch's math path does. online_softmax applies to the forward only.

Every input of tolerance and backward_tolerance, out and logsumexp included, may also be an earlier result, as Result describes. The bounds are proven in proofs/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 of output and logsumexp, over this algorithm's finite outputs (Result.tolerance).

The arguments are scaled_dot_product_attention's (overflow the implementation's overflow mode); compute, ulps, flush_to_zero, standard and workers are as in Result.tolerance. With online_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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the other arguments are tolerance'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, as Result.covers describes; the other arguments are tolerance'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 of grad_query, grad_key and grad_value, over this algorithm's finite outputs. Given the forward's rounded out and logsumexp (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, standard and workers are as in Result.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_range describes; the arguments are backward_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"), as Result.may_be describes; the other arguments are backward_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, as Result.covers describes; the other arguments are backward_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#

add with each scalar operand and alpha first rounded to held, or to each format of a sequence in turn (AddHeldScalar).

multiply_held_scalar(held: Format | str | Sequence[Format | str]) -> MultiplyHeldScalar#

multiply with each scalar operand first rounded to held, or to each format of a sequence in turn (MultiplyHeldScalar).

class AddHeldScalar#

add with each scalar operand and alpha first rounded to nearest even to held (proofs/add.md, Held scalars), as MultiplyHeldScalar rounds a scalar operand; then add's model runs on the held values. held is "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 in MultiplyHeldScalar. The bounds are measured from add'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 no run().

PyTorch's CPU add rounds a scalar operand and alpha to the dtype first: "operand" for float32, complex64 and float16 (where PyTorch converts a float64 value to float16 in one rounding, as MultiplyHeldScalar says), ("float32", "operand") for bfloat16 and ("complex64", "operand") for complex32, which PyTorch converts a float64 or complex128 value to through float32 or complex64. With alpha other than 1, its bfloat16 and complex32 kernels, and its float16 kernel for some elements (of a short broadcast row), also store alpha * y in the dtype before the addition, a rounding this model does not have: add's chain add(x, multiply(y, alpha, dtype=...)) with alpha so rounded, which any_of combines with add.

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, as Result.tolerance describes; the arguments are add's (overflow the implementation's overflow mode) and Result.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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the other arguments are tolerance'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, as Result.covers describes; the other arguments are tolerance'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 and alpha held.

class MultiplyHeldScalar#

multiply with each scalar operand first rounded to nearest even to held (proofs/multiply.md, Held scalars). A scalar operand is one multiply takes by its value: a Python scalar, FloatValue or ComplexValue, or an array of shape () beside an operand with dimensions; a complex one is rounded part by part, and a value past held's range gives an infinity (NaN in a format without one), as a cast does. Then multiply's model runs on the held value. held is "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 from multiply'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 chain multiply(s, 1, dtype=...) holds it, and multiply takes that). No backward and no run().

PyTorch's CPU mul rounds 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 * x with a Python scalar s, torch.mul(x, s)): "compute" (float32, which it computes in).

  • float16 and bfloat16 with the scalar first (torch.mul(s, x), s0d * x with a tensor s0d of 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, as Result.tolerance describes; the arguments are multiply's (overflow the implementation's overflow mode) and Result.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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the other arguments are tolerance'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, as Result.covers describes; the other arguments are tolerance's.

normal(x, y, *, 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#

multiply's normal answer (Result.normal) with each scalar operand held.

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 bfloat16 reciprocal on a Linux ARM CPU.

class ReciprocalEstimate#

PyTorch's bfloat16 reciprocal on a Linux ARM CPU: per element either reciprocal's value, correctly rounded (the kernel's scalar path), or Arm's reciprocal estimate of x rounded 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. covers and may_be hold where either path's do; tolerance and finite_range are for the range holding both. The bounds are measured from reciprocal's reference; with flush_to_zero the 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; compute is bfloat16 and there is no ulps. No run() 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 after output are backward_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 after kind are backward_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's rounded; the arguments are the backward's and Result.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, as Result.covers describes; the arguments after output are tolerance'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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the arguments after kind are tolerance'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's rounded, as Result.tolerance describes; the arguments are the operation's and Result.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 exp by another sequence (FunctionAlgorithm): fused, the Windows CPU's (MSVC's), whose c exp(x) for each part is one library routine, or products, MPS's: exp(x) as one library value with no scaling, so an infinity past the format, times cos(y) and sin(y), with no special case but y = 0.

expm1_algorithm(*, difference: bool = False, ulps=None) -> FunctionAlgorithm#

A complex expm1 by another sequence (FunctionAlgorithm): difference, MPS's.

log_algorithm(*, hypot: bool = False, sqrt_sum: bool = False, norm_log1p: bool = False, ulps=None) -> FunctionAlgorithm#

A complex log by 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, or norm_log1p, the Windows CPU's (MSVC's).

log1p_algorithm(*, squares: bool = False, direct: bool = False, norm_log1p: bool = False, ulps=None) -> FunctionAlgorithm#

A complex log1p by another sequence (FunctionAlgorithm): squares, the macOS CPU's and CUDA's, direct, MPS's, or norm_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 tanh by another sequence (FunctionAlgorithm): double_angle, the macOS CPU's, kahan, CUDA's, quotient, MPS's, or sinh_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 sigmoid by another sequence (FunctionAlgorithm): scaled, CUDA's, divided, MPS's, or fused, 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() and covers()): how far an implementation of this sequence can be from the exact value, each real library function within its ulps units 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 for expm1's difference, which also takes real inputs: Metal's real kernel is the library function below 0.1 in magnitude and exp(x) - 1 from there. MPS's methods (exp's products, expm1's difference, log's sqrt_sum, sigmoid's divided, and tanh's quotient) take Metal's special values: a part their formula takes through a NaN may be NaN beside the reference. log1p's direct, MPS's too, gives the reference's own special values. MPS runs a complex32 kernel in float16, which compute="float16" describes. No run() 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 after output are backward_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 after kind are backward_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's rounded; the arguments are the backward's and Result.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, as Result.covers describes; the arguments after output are tolerance'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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the arguments after kind are tolerance'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's rounded, as Result.tolerance describes; the arguments are the operation's and Result.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 complex sqrt by the polar method, each library function within its ulps.

class SqrtPolar#

A complex sqrt by the polar method, as PyTorch's CUDA kernels compute it: r = sqrt(hypot(a, b)) and th = atan2(b, a) / 2, then r * cos(th) and r * sin(th), each library function within its ulps units 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 from sqrt'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 of z is not finite the value is sqrt's own. The backward forms bound PyTorch's formula grad / (2 * conj(result)) on this algorithm's result. Complex inputs only. No run(), 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 after output are backward_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 after kind are backward_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's rounded; the arguments are the backward's and Result.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, as Result.covers describes; the arguments after output are tolerance'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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the arguments after kind are tolerance'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's rounded, as Result.tolerance describes; the arguments are the operation's and Result.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 within ulps.

class RsqrtDirect#

rsqrt by one library function: a value of the compute format within ulps units in the last place of the exact 1 / sqrt(x), then the rounding to the output (proofs/rsqrt.md, rsqrt_direct). ulps defaults 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's rsqrtf and rsqrt (2 and 1 units from the correctly rounded result); a query's own ulps replaces it. The bounds are measured from rsqrt's reference. The backward forms bound PyTorch's formula (-0.5 * grad) * result**3 on this algorithm's result. Real, integer and bool inputs. No run() 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): ulps units 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 after output are backward_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 after kind are backward_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's rounded; the arguments are the backward's and Result.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, as Result.covers describes; the arguments after output are tolerance'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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the arguments after kind are tolerance'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's rounded, as Result.tolerance describes; the arguments are the operation's and Result.tolerance's.

rsqrt_estimate() -> RsqrtEstimate#

The algorithm RsqrtEstimate: PyTorch's bfloat16 rsqrt on a Linux ARM CPU.

class RsqrtEstimate#

PyTorch's bfloat16 rsqrt (and x.pow(-0.5)) on a Linux ARM CPU: per element either rsqrt'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() with vrecpeq_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. covers and may_be hold where either path's do; tolerance and finite_range are for the range holding both. The bounds are measured from rsqrt's reference; with flush_to_zero a 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**3 on either path's result, the cube as two products, each step rounded to bfloat16. bfloat16 inputs and outputs only; compute is bfloat16 and there is no ulps. No run() 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 after output are backward_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 after kind are backward_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's rounded; the arguments are the backward's and Result.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, as Result.covers describes; the arguments after output are tolerance'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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the arguments after kind are tolerance'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's rounded, as Result.tolerance describes; the arguments are the operation's and Result.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: var by Welford's running method, under any merging of blocks.

class VarWelford#

var by 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, so compute="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 from var'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. No run(), 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, as Result.tolerance describes; the arguments are var's and Result.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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the arguments after kind are tolerance'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, as Result.covers describes; the arguments after output are tolerance's.

std_welford() -> StdWelford#

The algorithm StdWelford: std as the square root of Welford's variance.

class StdWelford#

std as 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, with compute="float64" on a CPU and the default compute format on CUDA. The bounds are measured from std's reference. No run() 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#

softmax by another kernel's steps (SoftmaxAlgorithm): any of reciprocal, stored_exp and products.

log_softmax_algorithm(*, stored_sum: bool = False, ulps=None) -> SoftmaxAlgorithm#

log_softmax by another kernel's steps (SoftmaxAlgorithm): stored_sum.

class SoftmaxAlgorithm#

softmax or log_softmax by 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) and products (the backward as grad * 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 no keepdims.

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 after output are backward_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 after kind are backward_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 and Result.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, as Result.covers describes; the arguments after output are tolerance'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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the arguments after kind are tolerance'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, as Result.tolerance describes; the arguments are the operation's and Result.tolerance's.

logsumexp_algorithm(*, hypot: bool = False, sqrt_sum: bool = False, ulps=None) -> LogsumexpAlgorithm#

A complex logsumexp whose logarithm is another sequence (LogsumexpAlgorithm): hypot, the macOS CPU's and CUDA's, or sqrt_sum, MPS's.

class LogsumexpAlgorithm#

logsumexp of a complex input with another complex logarithm than glibc's (RowAlgorithm): hypot or sqrt_sum, as log_algorithm names 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 after output are backward_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 after kind are backward_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 and Result.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, as Result.covers describes; the arguments after output are tolerance'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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the arguments after kind are tolerance'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, as Result.tolerance describes; the arguments are the operation's and Result.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_norm whose reciprocal square root is one library function within rsqrt_ulps units 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_norm by another kernel's steps (NormAlgorithm): any of folded, welford and rsqrt_ulps.

batch_norm_algorithm(*, centered: bool = False, welford: bool = False, rsqrt_ulps=None) -> NormAlgorithm#

batch_norm by another kernel's steps (NormAlgorithm): any of centered, welford and rsqrt_ulps.

class NormAlgorithm#

rms_norm, layer_norm or batch_norm by 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() and covers(), and the same of the backward with backward_ 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's rsqrt); for layer_norm, folded (x * r + (-r * mean) before the weight and the bias: PyTorch's CPU kernel for float16 and bfloat16) and welford (Welford's method over any merge tree: CUDA's); for batch_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) and welford (the statistics by Welford's method: CUDA's). A query takes the operation's arguments, then Result.tolerance's by keyword. No run() 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.tolerance describes; 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_range describes.

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"), as Result.may_be describes.

covers(output, *arguments, compute=None, ulps=None, flush_to_zero: bool = False, standard: str = 'normal', **options)#

Where this algorithm can produce output's value, as Result.covers describes.

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)#

fft by a plan (_FFTAlgorithm): plan the passes of each axis, each a radix or a Bluestein pass; 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_plan the backward's (a complex transform), needed unless path is "complex", where it defaults to plan.

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}, or grad_X for ifft and irfft), where this algorithm can produce that value, as Result.covers describes; the other arguments are backward_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 are backward_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, or grad_X for ifft and irfft), the backward's transform by backward_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 are tolerance'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, as Result.covers describes; the other arguments are tolerance'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's norm: |error| <= relative * M + absolute for 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. ulps and flush_to_zero are as in Result.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_range describes; the arguments are tolerance'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"), as Result.may_be describes; the other arguments are tolerance'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 (overflow the implementation's overflow mode); compute, ulps, flush_to_zero, standard, and workers are as in Result.tolerance.

class IFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#

ifft by a plan, as FFTAlgorithm.

class RFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#

rfft by a plan, as FFTAlgorithm: path the last axis's (its real input's); backward_plan the backward's complex transform, needed unless path is "complex".

class IRFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#

irfft by a plan, as FFTAlgorithm: path the real outputs' ("complex" on W or its Hermitian completion, "real" the backward real passes, "packed" the packed real-output form); backward_plan and backward_path the backward's real-input transform, by default plan and path.

class HFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#

hfft by a plan, as IRFFTAlgorithm.

class IHFFTAlgorithm(plan, path: str = 'complex', *, backward_plan=None, backward_path: str | None = None)#

ihfft by a plan, as RFFTAlgorithm.

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 length p values as a cyclic convolution of padded length n2 >= 2p - 1, the convolution's three transforms of n2 by passes of radices (complex radices whose product is n2). pocketfft's padded length is good_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, name and description, the bounds of its outputs on actual inputs (tolerance, finite_range, may_be and covers), and, where its rounding sequence is fully specified, run.

class ErrorModel(relative: Fraction, absolute: Fraction, scale: str)#

|error| <= relative * scale + absolute, with scale naming 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.

sequential pairwise 0 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 depth 8, 8 roundings depth 4, 15 roundings

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:

Code
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)}")
Output
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 of METHODS, "any_order" or "mma" (ValueError for any other).

class AccumulationMethod#

An accumulation method: its key, a short label and a description, whether its result depends on the order of the terms, the parameters it takes (such as block_size) and its references. For a method of METHODS, depth(n) and roundings(n) give the worst-case bound's counts for n terms (the module docstring); ANY_ORDER and MMA_METHOD have 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.