Generate golden reference values#

The problem#

You are testing an implementation that cannot call Python at test time: hardware, an FPGA design, a compiler's code generator, or a library in C, Rust, or another language. You need fixed test vectors: inputs, expected outputs, and how far each output may be from the expected one.

Why the usual approach falls short#

Expected outputs computed with a higher-precision library are not exact, and they come without a bound on what a correct implementation can output. A test against them needs a tolerance chosen by hand, in every language that runs the test.

The solution#

Generate the vectors once with ExactRef, and store the bits: the inputs' encodings, the encodings of the reference (the exact answer rounded once to the output format), and the lowest and highest finite output a correct implementation can produce, plus where it may produce an infinity or NaN. A checker in any language then compares numbers, with no tolerance to choose.

The unit under test here is a matrix unit that multiplies bfloat16 tiles into float32: 64 by 64 outputs with an inner dimension of 256. The vectors cover four cases at that shape: random values, sums that nearly cancel, results below float32's smallest normal value, and sums near the top of float32's range:

Code
import json
import os
import struct
import tempfile
import numpy as np
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)


def tile_inputs(case):
    """A 64x256 and a 256x64 bfloat16 tile for one test case."""
    # Random normal values, which the cases below change
    a = torch.randn(64, 256, generator=g)
    b = torch.randn(256, 64, generator=g)
    if case == "cancellation":
        # The inner dimension's second half nearly undoes the first: a's last 128
        # columns repeat its first 128, and b's last 128 rows are its first 128
        # negated, plus a small difference
        a = torch.cat([a[:, :128], a[:, :128]], dim=1)
        b = torch.cat([b[:128], -b[:128] + torch.randn(128, 64, generator=g) / 256])
    elif case == "subnormal":
        # Products near 2**-140, below float32's smallest normal value, 2**-126
        a, b = a * 2.0 ** -70, b * 2.0 ** -70
    elif case == "overflow":
        # Positive products whose sums straddle float32's largest value, about 2**128
        a, b = a.abs() * 2.0 ** 60, b.abs() * 1.5 * 2.0 ** 60
    return a.bfloat16(), b.bfloat16()


def hex_bits(array, digits):
    """Each element's raw encoding, as a hex string of the format's width."""
    return [f"{encoding:0{digits}x}" for encoding in array.encodings()]


def where(mask):
    """The flat positions where a bool array is True."""
    return [i for i, value in enumerate(mask.scalars()) if value]


# The vectors go into a JSON Lines file, one record per line
path = os.path.join(tempfile.mkdtemp(), "matmul_bfloat16.jsonl")
with open(path, "w") as f:
    for case in ("random", "cancellation", "subnormal", "overflow"):
        a, b = tile_inputs(case)
        # The reference, with float32 outputs as the unit writes them
        r = er.matmul(a, b, dtype="float32")
        # The lowest and highest finite output of a correct implementation
        low, high = r.finite_range()
        record = {
            # What the bounds assume: the formats, the default normal accumulation
            # (adding in index order or a few SIMD lanes side by side) in float32,
            # the compute format, and subnormal values kept
            "op": "matmul", "inputs": "bfloat16", "output": "float32", "compute": "float32",
            "standard": "normal", "flush_to_zero": False,
            "case": case, "shape": [64, 256, 64],
            # The inputs as 4 hex digits each, the outputs as 8
            "A": hex_bits(er.asarray(a), 4), "B": hex_bits(er.asarray(b), 4),
            "reference": hex_bits(r.rounded, 8), "low": hex_bits(low, 8), "high": hex_bits(high, 8),
            # Where a correct implementation may output +inf, -inf, or NaN
            "may_be": {value: where(r.may_be(value)) for value in ("+inf", "-inf", "nan")},
        }
        f.write(json.dumps(record) + "\n")
        # The number of outputs, and how many of them may be +inf
        print(f"{case}: {len(record['reference'])} outputs, {len(record['may_be']['+inf'])} may be +inf")
Output
random: 4096 outputs, 0 may be +inf
cancellation: 4096 outputs, 0 may be +inf
subnormal: 4096 outputs, 0 may be +inf
overflow: 4096 outputs, 1289 may be +inf

Each record stores the formats, the operation's options, and whether its low and high come from the default bounds, standard="normal", or from standard="any_order", which allows any order of additions, so the vector says what its bounds assume. Inputs narrower than 32 bits take narrower hex strings: 4 digits for bfloat16.

The checker decodes each output and tests low <= output <= high. An inf or NaN output passes only at a position its may_be list holds. In Python, as a model for the checker in your language:

Code
def decode(hex_bits):
    """The float32 that 8 hex digits encode, most significant byte first."""
    return struct.unpack(">f", bytes.fromhex(hex_bits))[0]


def check(record, outputs):
    """Whether every output is one a correct implementation can produce."""
    for i, (out, low, high) in enumerate(zip(outputs, record["low"], record["high"])):
        if out != out:
            # NaN: allowed only where the record lists it
            ok = i in record["may_be"]["nan"]
        elif abs(out) == float("inf"):
            # An infinity: allowed only where the record lists that sign
            ok = i in record["may_be"]["+inf" if out > 0 else "-inf"]
        else:
            # A finite output: between low and high
            ok = decode(low) <= out <= decode(high)
        if not ok:
            return False
    return True

Two devices run each vector. One keeps subnormal values, as NumPy's float32 product does. The other runs in flush-to-zero mode and returns 0 for every result below float32's smallest normal value:

Code
def bfloat16_values(hexes, shape):
    """bfloat16 encodings as float32 values: a bfloat16 is the top half of a float32."""
    return np.array([decode(h + "0000") for h in hexes], dtype=np.float32).reshape(shape)


with open(path) as f:
    for line in f:
        record = json.loads(line)
        m, k, n = record["shape"]
        # The vector's inputs, read back from their encodings
        A, B = bfloat16_values(record["A"], (m, k)), bfloat16_values(record["B"], (k, n))
        # NumPy's float32 product, as a list of Python floats in row-major order
        out = (A @ B).ravel().tolist()
        # The same outputs from a device that flushes subnormal results to zero
        flushed = [0.0 if abs(x) < 2.0 ** -126 else x for x in out]
        # Does each device pass this vector?
        print(f"{record['case']}: NumPy {check(record, out)}, flush to zero {check(record, flushed)}")
Output
random: NumPy True, flush to zero True
cancellation: NumPy True, flush to zero True
subnormal: NumPy True, flush to zero False
overflow: NumPy True, flush to zero True

The flush-to-zero device fails only the subnormal case, which is what that case is for. If a device flushes on purpose, generate its vectors with flush_to_zero=True passed to finite_range() and may_be(), and store that in the record.