Decide whether inf or NaN is legitimate#
The problem#
An implementation returns inf or NaN for some elements. That may be an
overflow that any implementation would hit, an overflow caused by a poor order
of additions, NaN passed on from the inputs, or NaN the implementation
created itself. torch.isfinite and allclose(..., equal_nan=True) cannot
tell these apart.
Why the usual approach falls short#
Whether inf is acceptable depends on the exact value and on how close it is to the top of the format's range. Whether NaN is acceptable depends on the special values in the inputs. Neither is visible from the output.
The solution#
covers() says, per element, whether a correct implementation can produce an
output, and it judges infinities and NaN too: an inf or NaN output passes only
where may_be() says a correct implementation can produce it. The examples
below follow attention in float16, where both appear.
Overflow in the exact answer#
Model code often computes attention scores as q @ k.T in the model's dtype
and scales them afterwards. In float16, whose largest value is 65504, that
product overflows when queries and keys grow large, as they can late in
training. Here is one head with 1024 positions and head dimension 128:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# Queries and keys for one head in float16, grown to a standard deviation of 40
q = (torch.randn(1024, 128, generator=g) * 40).half()
k = (torch.randn(1024, 128, generator=g) * 40).half()
# The scores before scaling, from PyTorch's float16 product
scores = q @ k.T
# The reference for q @ k.T
r = er.matmul(q, k.T)
# Can a correct implementation produce every score, the infinities included?
print("covered:", r.covers(scores).all())
# How many scores a correct implementation may return as +inf or -inf
infinite = r.may_be("+inf").scalars().count(True) + r.may_be("-inf").scalars().count(True)
print("may be infinite:", infinite)
covered: True
may be infinite: 385
The exact values of these 385 scores lie beyond float16's range, so every
correct implementation returns an infinity there. The infinities are
legitimate: the kernel is right, and the fix belongs in the model, for
example scaling q before the product or computing the scores in float32.
Where an exact value lies close to the point where float16 rounds to
infinity, a correct implementation can land on either side, and may_be()
allows both:
What a correct float16 result can be, by where the exact value lies: finite well below 65520, finite or +inf within the tolerance of it (how far a correct result can be from the exact value rounded once), +inf well above it.
Overflow from the order of additions#
A kernel that keeps its running sums in float16, as cuBLAS may when
torch.backends.cuda.matmul.allow_fp16_accumulation is set, can overflow
partway through a sum whose exact value fits. Here such a kernel computes the
same scores, emulated on the CPU:
# The kernel: for each of the 128 products, add it to every score in float16
out = torch.zeros(1024, 1024, dtype=torch.float16)
for i in range(128):
# Add q[m, i] * k[n, i] to score (m, n), rounding the product and the sum to float16
out = out + q[:, i:i + 1] * k[:, i:i + 1].T
print("infinities:", out.isinf().sum().item())
# Per score, whether a correct implementation can produce it, as a tensor: by
# default for float32 accumulation, and with "float16" for a float16 accumulator
float32_ok = torch.tensor(r.covers(out).scalars()).reshape(out.shape)
float16_ok = torch.tensor(r.covers(out, "float16").scalars()).reshape(out.shape)
# The infinities no correct implementation produces, judged each way
print("impossible, float32 accumulation:", (out.isinf() & ~float32_ok).sum().item())
print("impossible, float16 accumulation:", (out.isinf() & ~float16_ok).sum().item())
infinities: 637
impossible, float32 accumulation: 252
impossible, float16 accumulation: 26
The kernel returns 637 infinities, 252 more than the exact scores call for. Their exact values fit in float16, so an implementation that adds in float32 returns a finite value there. Judged as a float16 accumulator, most of the 252 become possible, because float16's error near the top of its range is large. 26 stay impossible: their exact scores are well below 65504, and only a running sum that overflows partway returns an infinity.
NaN that the inputs do not force#
NaN is legitimate where the inputs force it, as inf - inf does, and nowhere
else. A common source is attention over a batch with left padding and a
causal mask. A query at a padding position sees only earlier positions, all
of them padding and masked out, so it keeps no key at all. PyTorch's
scaled_dot_product_attention returns 0 for such a query; a hand-written
softmax returns NaN, which then spreads into later steps and the gradients.
Here are two sequences of 512 positions, the second left-padded by 200, with
8 heads of dimension 64:
import math
# Queries, keys, and values: (batch, heads, positions, head dimension)
q, k, v = (torch.randn(2, 8, 512, 64, generator=g) for _ in range(3))
# Per query, the keys it keeps: the causal mask, without the second
# sequence's 200 padding positions
keep = torch.ones(512, 512, dtype=torch.bool).tril().repeat(2, 1, 1, 1)
keep[1, :, :, :200] = False
# A hand-written attention: masked scores become -inf before the softmax
scores = (q @ k.transpose(-2, -1)) / math.sqrt(64)
out = torch.softmax(scores.masked_fill(~keep, float("-inf")), dim=-1) @ v
print("NaN elements:", out.isnan().sum().item())
# The reference for the same attention; ["output"] selects its first output
a = er.scaled_dot_product_attention(q, k, v, attn_mask=keep)["output"]
# May a correct implementation return NaN anywhere? Does out pass?
print("may be NaN:", a.may_be("nan").any())
print("covered:", a.covers(out).all())
# PyTorch's own attention on the same inputs
fused = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=keep)
print("PyTorch covered:", a.covers(fused).all())
NaN elements: 102400
may be NaN: False
covered: False
PyTorch covered: True
ExactRef follows PyTorch: a query that keeps no key gets an output of 0. So none of the 102,400 NaNs is legitimate. The hand-written attention created them.
A NaN or an infinity in a masked key's score or value does not force NaN
either. A masked key takes no part in the reference, whatever its score or
value, so a row that masks it keeps a finite reference. A kernel that still
computes the masked key's terms gets NaN there (-inf plus a NaN score, or a
weight of 0 times a NaN value), and may_be("nan") allows that in the rows
the masked key could reach; a kernel that skips masked keys keeps them
finite. Both pass, forward and backward.
Special values
shows a NaN key under a causal mask.
NaN that the inputs force#
The next step, the attention's output projection, receives those NaN rows. Its own NaNs are forced by its input, so it passes:
# The output projection's weight: 8 heads of 64 make 512 features
w_o = torch.randn(512, 512, generator=g) / math.sqrt(512)
# The heads side by side again, one row per position: 1024 rows of 512
merged = out.transpose(1, 2).reshape(1024, 512)
projected = merged @ w_o.T
print("NaN elements:", projected.isnan().sum().item())
# The reference for the projection of the stored input, NaN rows included
p = er.matmul(merged, w_o.T)
# Where a correct implementation may return NaN, and whether the projection passes
print("may be NaN:", p.may_be("nan").scalars().count(True))
print("covered:", p.covers(projected).all())
NaN elements: 102400
may be NaN: 102400
covered: True
A row of the input that holds a NaN makes a NaN in every element of that row's output, so every NaN of the projection is forced. Checking each step on its stored input tells you where NaN starts: the first step whose NaNs are not forced is the one that created them. Find the step that loses accuracy checks a computation step by step the same way.
For complex outputs, each part is judged on its own, so a finite imaginary part is still checked next to an infinite real part.