Chains and any_of#
Many computations have several steps. A LoRA adapter, for example, computes
(x @ A) @ B: it stores x @ A in the model's dtype, then rounds again when
it multiplies by B. To check such a chain of steps, run the same steps in
ExactRef, and pass each earlier ExactRef result where the implementation used
its stored output.
A result's bounds are the outputs a correct implementation can produce: its
tolerance, how far a finite output can be from the reference rounded (the
exact answer rounded once to the output format); finite_range(), the
lowest and highest finite output; and may_be(), where the output may be
+inf, -inf, or NaN. ExactRef does not know which value the implementation
stored for an earlier step, only that it is within that step's bounds. So
the next result's bounds cover every such value. Each step's uncertainty
carries into the next, and the bounds of the last step cover the whole
computation.
The value stored by step 1 could be anywhere in its band, so step 2's tolerance covers all of them.
Passing a result as an input#
A LoRA adapter on a layer of hidden size 4096, with rank 16, for 128 tokens in bfloat16:
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 adapter's down and up projections
x = torch.randn(128, 4096, generator=g).bfloat16()
A = (torch.randn(4096, 16, generator=g) / 64).bfloat16()
B = (torch.randn(16, 4096, generator=g) / 4).bfloat16()
# The reference for x @ A
first = er.matmul(x, A)
# x @ A stored in bfloat16, then @ B
chain = er.matmul(first, B)
# Can a correct implementation of the chain give PyTorch's (x @ A) @ B?
print("covered:", chain.covers((x @ A) @ B).all())
covered: True
What the chained result holds:
chain.roundedis the exact product offirst.roundedandB, rounded once, andchain.exactis an enclosure of that exact product, an interval guaranteed to contain it. They are not the exact value of the whole expression(x @ A) @ B.chain.tolerance()covers every storedx @ Awithinfirst.tolerance()offirst.rounded, so it is wider than if the stored values were known.chain.normal()emulates exactly an ordinary implementation that adds in index order, at both steps: it works onfirst.normal().
How the bounds carry through#
The options you give a chained result's methods, such as tolerance() and
covers(), also apply to the earlier steps. The normal tolerance, the
default, assumes normal accumulation at every step: index order, or
SIMD lanes side by side. The any-order tolerance,
standard="any_order", assumes any order of additions at every step.
compute, the compute format the additions round to, and
flush_to_zero (flush to zero) also apply to every step.
For each value an earlier step may have stored, the next step's bounds do
this:
The earlier result allows |
The next step's bounds |
|---|---|
a finite value within its tolerance (for complex values, each part within its own) |
cover every such value |
an infinity or NaN that |
carry it into |
any value (an infinite tolerance) |
give no bound: an infinite tolerance wherever the reference is finite |
a possible infinity or NaN, into an operation that can turn it into a finite value: |
give no bound (an infinite tolerance) where the output can be finite |
Reading complicated tolerances has
an example of the last case. When you pass a result to the run() of a
named algorithm, one specific way of computing an
operation, run() uses that result's rounded values.
Every operation, backward, and algorithm accepts, in place of an array, the
result of a forward operation with one output. Results with several
outputs name them, and are passed one output at a time: attention's
output and logsumexp, var's and std's result and mean,
batch_norm's output, running_mean, and running_var when it updates
running statistics, and every backward's gradients, such as grad_A. See
Named outputs below. The
tensor-core algorithms are the one exception for float32: they take a
float32 A or B only as an array of TF32 values
(Tensor-core algorithms).
Named outputs#
Attention, var, std, batch_norm when it updates running statistics,
and every backward name their outputs, even a backward with one gradient. Such a result is passed one output at a time, by name;
passing the result itself raises TypeError. Backpropagation through two
layers passes the second layer's input gradient on as the first layer's
output gradient:
# Two bfloat16 linear layers of width 1024, and the gradient of their output
h_in = torch.randn(128, 1024, generator=g).bfloat16()
W1 = (torch.randn(1024, 1024, generator=g) / 32).bfloat16()
W2 = (torch.randn(1024, 1024, generator=g) / 32).bfloat16()
grad = torch.randn(128, 1024, generator=g).bfloat16()
# The first layer's output, stored and passed to the second
h = er.matmul(h_in, W1.T)
# The second layer's gradients; grad_A is the gradient of its input, h
second = er.matmul.backward(h, W2.T, grad)
# second["grad_A"] is passed as the first layer's output gradient
first_layer = er.matmul.backward(h_in, W1.T, second["grad_A"])
# PyTorch's autograd through both layers, for the same input
h_in_ = h_in.clone().requires_grad_()
out = torch.nn.functional.linear(torch.nn.functional.linear(h_in_, W1), W2)
out.backward(grad)
# Could a correct implementation of the chain give PyTorch's input gradient?
print("covered:", first_layer["grad_A"].covers(h_in_.grad).all())
covered: True
Attention algorithms take a forward's outputs the same way, as
fwd["output"] and fwd["logsumexp"].
Views#
When the next step needs another layout, reshape and transpose move the
elements of a one-output result without rounding anything. Attention's
queries, keys, and values come from projections reshaped into heads:
# 128 tokens of hidden size 512, and the query, key, and value weights
xs = torch.randn(128, 512, generator=g)
Wq, Wk, Wv = (torch.randn(512, 512, generator=g) / 22 for _ in range(3))
def heads(r):
"""A projection's result as (batch, heads, positions, head dimension): 8 heads of 64."""
return r.reshape((1, 128, 8, 64)).transpose(1, 2)
# Each projection's result, reshaped into heads and passed to attention
q, k, v = (heads(er.matmul(xs, W.T)) for W in (Wq, Wk, Wv))
a = er.scaled_dot_product_attention(q, k, v, is_causal=True)
print("output:", a.rounded.output.shape)
output: (1, 8, 128, 64)
Either of several expressions: any_of#
Some implementations may compute one of several expressions, and not always
the same one for every element. PyTorch's float16 add with alpha on the
CPU is one: its vectorized loop computes x + alpha * y with one rounding,
and the elements left over at the end of each chunk go through a scalar path
that stores alpha * y in float16 first. Each way of computing has its own
exact answer and bounds. er.any_of(center, *alternatives) combines them
into one result whose bounds accept an output from any of them, element by
element; any_of checks that
add on a classifier's logits.
any_of keeps the center's reference and widens its range to hold every alternative's.
The result keeps everything from the center: its rounded,
exact, guarantee, normal(), and backward(). Only the bounds are
widened, per element:
the finite range is the smallest range that holds the center's and every alternative's;
may_be()allows every infinity and NaN that any of them allows;the tolerance is the largest distance from the center's
roundedto an end of that range.
Every result passed to any_of must have one unnamed output (pass a
backward's gradient as r[name]), with the same shape and dtype.
PyTorch equivalents lists PyTorch operations whose
roundings are chains or any_of of ExactRef calls.
Where to go next#
Find the step that loses accuracy: check each intermediate of a computation with several steps.
PyTorch equivalents: PyTorch calls that are chains.
any_of: the full specification.