Check a PyTorch operation across dtypes#

The problem#

You maintain a PyTorch backend, or a build of PyTorch, and want to know that its operations are correct in every dtype they support: float32, float16, and bfloat16 at least. A float64 reference converted to the dtype hides exactly the dtype-specific rounding you want to check.

Why the usual approach falls short#

Each dtype rounds differently, and PyTorch sometimes rounds in places the mathematics does not require: it rounds alpha and scalar operands before using them, stores some intermediate results in the dtype, and computes some products in the dtype itself. A single tolerance per dtype either misses those or fails them.

The solution#

Loop over dtypes and operations, and check each output with covers(), which says per element whether a correct implementation can produce it. Use PyTorch equivalents to find the ExactRef call for each PyTorch call and the roundings it adds. Here the operations run on a linear layer's tensors: 128 tokens of hidden size 1024, a 1024 by 1024 weight, and a bias.

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The device under test; set it to "cuda" or "mps" for a GPU
device = "cpu"


def on(t):
    """A copy of t on the device under test."""
    return t.to(device)


for dtype in (torch.float32, torch.float16, torch.bfloat16):
    # In this dtype: the layer's input x, weight w, bias b, and a second
    # activation tensor y of x's shape
    x = torch.randn(128, 1024, generator=g).to(dtype)
    w = (torch.randn(1024, 1024, generator=g) / 32).to(dtype)
    b = torch.randn(1024, generator=g).to(dtype)
    y = torch.randn(128, 1024, generator=g).to(dtype)
    # Per operation: is the device's output, copied back to the CPU, covered?
    results = {
        "matmul": er.matmul(x, w.T).covers((on(x) @ on(w).T).cpu()).all(),
        # er.gemm is beta * C + alpha * (A @ B), PyTorch's addmm
        "addmm": er.gemm(x, w.T, b, alpha=0.5, beta=2.0).covers(
            torch.addmm(on(b), on(x), on(w).T, beta=2.0, alpha=0.5).cpu()).all(),
        # Each token's sum over its 1024 features
        "sum": er.sum(x, axis=1).covers(on(x).sum(dim=1).cpu()).all(),
        "mul": er.multiply(x, y).covers((on(x) * on(y)).cpu()).all(),
    }
    print(str(dtype), "covered:", results)
Output
torch.float32 covered: {'matmul': True, 'addmm': True, 'sum': True, 'mul': True}
torch.float16 covered: {'matmul': True, 'addmm': True, 'sum': True, 'mul': True}
torch.bfloat16 covered: {'matmul': True, 'addmm': True, 'sum': True, 'mul': True}

On a CUDA GPU, the float16 and bfloat16 products here (matmul and addmm) run on tensor cores, whose block additions truncate. The operations' own tolerances, how far a correct output can be from the exact answer rounded once, do not cover that, so check them with matmul_mma and gemm_mma, which model the tensor cores' steps (Tensor-core algorithms).

To check torch.add with alpha, round alpha the way PyTorch does: its CPU kernel converts alpha to the tensor's dtype. In bfloat16 on an ARM CPU, and in float16 for some elements of a short broadcast row, the check also needs a second way of computing the result: alpha * y rounded to the dtype first, then added to x. Here alpha scales a residual branch by 0.3:

Code
for dtype in (torch.float32, torch.float16, torch.bfloat16):
    # A residual stream x and a branch y in this dtype
    x = torch.randn(128, 1024, generator=g).to(dtype)
    y = torch.randn(128, 1024, generator=g).to(dtype)
    # alpha = 0.3 rounded to the dtype, as the CPU kernel uses it
    a = torch.tensor(0.3, dtype=dtype).item()
    # The dtype's name without "torch.", such as "float16"
    name = str(dtype).removeprefix("torch.")

    # One way: x + a * y, rounded once
    plain = er.add(x, y, alpha=a)
    # The second way: a * y rounded to the dtype first, then added to x
    stored = er.add(x, er.multiply(y, a, dtype=name))
    # any_of widens plain's bounds to cover the second way too
    covered = er.any_of(plain, stored).covers(torch.add(x, y, alpha=0.3)).all()
    print(name, "covered:", covered)
Output
float32 covered: True
float16 covered: True
bfloat16 covered: True
any_of: the smallest range holding both center's rounded alternative center

any_of keeps the reference of the first way, the center: its exact answer rounded once. It widens the center's range to hold the range of the second way, the alternative.

When a check fails on a backend, move the inputs back to the CPU and look at the failing elements. Either the backend is wrong, or PyTorch rounds somewhere that the ExactRef call from PyTorch equivalents does not describe yet.