Skip to content

Numerical precision and the MXU

30 min read

Prerequisites: Execution model: eager modes, deferred ops, torch.compile, Memory model, storage and views

A model ported from CUDA to TorchTPU usually trains, and its outputs usually differ from the GPU run in the third or fourth significant digit. Sometimes that difference is a bug; usually it is the TPU doing exactly what it was designed to do. The TPU's matrix unit multiplies bfloat16 numbers and adds them up in float32, so a "float32" matmul at TorchTPU's default setting has bf16 inputs. Inside a compiled program, XLA may also keep a float32 intermediate where eager PyTorch would have rounded it to bf16, which gives a compiled function slightly different (and slightly more precise) answers than the same code run eagerly. This chapter explains both mechanisms bit by bit, shows the controls TorchTPU gives you (torch.set_float32_matmul_precision, torch.tpu.precision, out_dtype, torch.tpu.allow_excess_precision), and ends with a parity check whose tolerance is derived from the arithmetic instead of guessed, so you can tell a precision effect from a bug.

What this chapter covers

  • How the bfloat16 and float32 formats differ, and why bf16 keeps float32's range while losing most of its precision.
  • Which TPU unit runs which operations and at what precision, and how the "medium", "high" and "highest" matmul modes map to 1, 3 and 6 bf16 MXU passes.
  • Excess precision, how torch.tpu.allow_excess_precision controls it, and why a compiled function can disagree with its eager version.
  • The causes of a numerical mismatch between TPU, CPU and GPU runs: input rounding, accumulation order, excess precision and real bugs.
  • Tolerances that fit the dtype and the operation, with torch.testing.assert_close and an error bound for contractions.

bfloat16 and float32: same range, fewer bits

The two formats that matter on a TPU share their exponent and differ in the mantissa. A float32 has 1 sign bit, 8 exponent bits and 23 stored mantissa bits, which with the implicit leading 1 gives a 24-bit significand. A bfloat16 has 1 sign bit, the same 8 exponent bits, and only 7 stored mantissa bits, an 8-bit significand. Its machine epsilon (the gap between 1.0 and the next representable number) is \(2^{-7}\), about 0.78%; float32's is \(2^{-23}\).

Three rows of bit cells. Row one, float32, value 1.0235595703125: a grey sign cell 0, eight teal exponent cells 01111111, and 23 blue mantissa cells with ones at positions 6, 7 and 13; the cell at mantissa bit 13 is outlined in orange and labelled mantissa bit 13 = 2^-13; a note reads 1 + 8 + 23 bits: VPU math, MXU accumulator. Row two, TF32 (CUDA), value 1.0234375: the same sign and exponent cells and 10 mantissa cells with ones at positions 6 and 7; note 1 + 8 + 10 bits: CUDA Tensor Core fast math. Row three, bfloat16, value 1.0234375: the same sign and exponent cells and 7 mantissa cells with ones at positions 6 and 7; note 1 + 8 + 7 bits: MXU inputs. A dashed orange vertical line after the 16th bit of every row is labelled bf16 keeps everything left of this line.

All three rows hold the same number, \((1 + 2^{-6})(1 + 2^{-7})\), which this chapter uses throughout. The exponent fields are identical, so bf16 covers float32's whole range; bf16 is literally the top 16 bits of a float32. Bit 13 exists only in the float32 row.

The TorchTPU documentation explains why this trade works: Google's research on bf16 found that neural networks train with reduced mantissa precision as long as they keep float32's dynamic range, which matters for norms and gradients. Range is exactly what bf16 keeps. TF32, the format the documentation lists for CUDA Tensor Core fast math, sits between the two with 10 mantissa bits.

The documentation also draws a distinction that the rest of this chapter depends on. An interchange format is how a number is stored in memory; an arithmetic format is how the hardware computes and rounds intermediate results, for example the 3 extra guard, round and sticky bits in a standard ALU. "bf16" can mean either. A bf16 tensor in HBM is stored in bf16; the arithmetic that produces it may well have happened in float32.

Where the arithmetic happens: MXU and VPU

Chapter 1 introduced the two compute units of a TensorCore. The numerical precision documentation assigns them their arithmetic:

  • The MXU executes contracting operations: torch.matmul, torch.mm, torch.bmm and convolutions. It takes bf16 inputs (and fp8 on newer generations such as v7x) and accumulates in float32.
  • The VPU executes non-contracting operations: elementwise arithmetic, activations, layer normalization and softmax. On float32 tensors it computes in full IEEE-754 float32, all 23 mantissa bits, apart from minor edge cases such as subnormals.

A blue dashed container labelled TensorCore. On the far left, outside it, a block fp32 tensor with two arrows. The upper arrow, labelled contracting, goes into an orange block Round to bf16, then a blue block MXU with the note bf16 inputs, then a teal block fp32 accumulator, then a grey block Output cast. The lower arrow, labelled non-contracting, goes into a long blue block VPU with the note fp32 math.

At the default precision, a float32 matmul loses precision in exactly one place: the orange box. The products and their sum are exact or float32 from there on, and the output cast decides how many of those bits survive. Elementwise float32 work on the VPU loses nothing.

The float32 accumulator is not a luxury. A matmul [I, J] @ [J, K] is a grid of dot products, each summing \(J\) products along the contracting dimension. With an epsilon of \(2^{-7}\), summing thousands of products in bf16 would be badly wrong, so the MXU sums in float32, which plays the role that guard, round and sticky bits play in an ALU: extra precision held until the final rounding. The product of two bf16 values has at most 16 significant bits, so it is exact in float32; the only rounding inside the MXU is in the float32 sums.

The documentation names the consequence: the mismatch between bf16 inputs and a float32 accumulator is the root cause of both less-than-expected precision (a float32 matmul whose inputs were cut to 8-bit significands) and excess precision (float32 intermediates kept across fused ops where the dtype says bf16). The next two sections take them in that order.

Matmul precision modes: passes for bits

When both inputs of a matmul are float32, TorchTPU has to decide how much of their 24-bit significands to feed through an 8-bit multiplier. It maps PyTorch's standard knob onto the torch.tpu.Precision enum, a direct binding to StableHLO's dot_general precision configuration:

torch.set_float32_matmul_precision torch.tpu.Precision MXU passes Significand bits multiplied Cost vs default
"medium" (TorchTPU default) DEFAULT 1 8 1x
"high" HIGH 3 16 about 3x MXU compute
"highest" HIGHEST 6 24 about 6x MXU compute

Two bar charts. Left, titled bf16 MXU passes per float32 matmul: DEFAULT ("medium") 1x, HIGH ("high") 3x, HIGHEST ("highest") 6x. Right, titled Significand bits multiplied: 8 bits, 16 bits and 24 bits, with a dotted line at 24 labelled float32 significand: 24 bits. A footer says accumulation is float32 in every mode and only float32 inputs are affected.

Cost grows with the number of passes; precision grows by 8 significand bits per step. A bf16 model is unaffected by this setting: its inputs already fit in one pass.

How the passes work. XLA uses the algorithm of Henry, Tang and Heinecke (arXiv 1904.06376): write each float32 value as a sum of three bf16 values, \(a = a_\text{high} + a_\text{med} + a_\text{low}\), each holding the next 8 bits of the significand. A product of two such sums has nine cross terms:

\[ (a_h + a_m + a_l)(b_h + b_m + b_l) = a_h b_h + (a_h b_m + a_m b_h) + (a_h b_l + a_m b_m + a_l b_h) + \underbrace{(a_m b_l + a_l b_m + a_l b_l)}_{\text{below float32 precision}} \]

Each cross term is one bf16 matmul, one MXU pass. DEFAULT computes only \(a_h b_h\), which is the same as rounding both inputs to bf16. HIGH adds the two terms of relative size about \(2^{-8}\), for three passes. HIGHEST adds the three terms of size about \(2^{-16}\), for six. The remaining three are of size \(2^{-24}\) or smaller and fall below float32 precision next to High × High, so no mode computes them.

A 3 by 3 grid with row and column headings. The note above the column headings reads Second input; the note in the top-left corner, above the row headings, reads First input. Columns and rows are both High, Med, Low. Row High: DEFAULT, about 2⁰; HIGH, about 2⁻⁸; HIGHEST, about 2⁻¹⁶. Row Med: HIGH, about 2⁻⁸; HIGHEST, about 2⁻¹⁶; below float32, in a grey cell. Row Low: HIGHEST, about 2⁻¹⁶; below float32; below float32, both grey.

Read the grid by anti-diagonals: each one is 8 bits further down the significand. A mode computes whole anti-diagonals, which is why the pass counts are 1, 3 and 6 rather than 1, 2 and 3.

The companion script emulates this decomposition on the CPU: it splits float32 inputs into three bf16 parts, multiplies the cross terms each mode computes, accumulates in float32, and compares with a float64 reference.

A log-scale line chart of relative error against a float64 reference for N x N by N x N float32 matmuls with N from 64 to 1024. The 1-pass "medium" / DEFAULT line is flat at about 2.3e-3. The 3-pass "high" / HIGH line is flat at about 4.5e-6. The 6-pass "highest" / HIGHEST line rises from about 6e-8 to about 2.5e-7, just below a dotted CPU float32 matmul line that rises from about 1.5e-7 to about 6e-7. A footer says this is a CPU emulation, not a TPU measurement.

The 1-pass error does not grow with the contracting dimension: it is set by rounding the inputs, about \(2 \times 10^{-3}\) for random data, the same figure chapter 3 used as its smoke-test expectation. The 6-pass emulation lands at plain float32 accuracy. These are emulated numbers; the TPU's summation order is not documented, so its last digits will differ.

Setting the mode

There are two controls, and the scoped one overrides the global one:

import torch

torch.set_float32_matmul_precision("medium")     # process-wide; "medium" is already the TPU default
print(torch.get_float32_matmul_precision())

P = torch.tpu.Precision                           # Experimental
with torch.tpu.precision(P.HIGHEST):             # thread-local, for one sensitive layer
    logits = model.lm_head(hidden)

The torch.tpu.precision context manager is thread-local and, when no context is active, operations fall back to the global setting (csrc/common/context_states.h). Its docstring adds a caution worth keeping: the lowering of the StableHLO precision settings to each TPU generation's instructions "is not fully documented", so precision may vary across hardware. Three more rules from the documentation and the source:

  • A one-time warning. Selecting "high" or "highest" emits TORCH_WARN_ONCE about performance. The documentation's advice is to keep "medium" unless you observe precision-related convergence problems.
  • A graph break. torch.tpu.precision calls torch._dynamo.graph_break() on entry. Under a default torch.compile, the surrounding frame falls back to eager; with fullgraph=True it raises. Put the context manager around the call to the compiled function, or set the global mode before compiling.
  • Only float32 contractions are affected. The setting applies to matmuls and convolutions with float32 inputs. Elementwise ops already run in float32 on the VPU, and bf16 matmuls take one pass in every mode.
torch.set_float32_matmul_precision("high")   # chosen on CUDA for speed

PyTorch's CUDA default is "highest", pure float32. The documentation's comparison lists TF32 Tensor Cores as CUDA's fast-math primitive, with float32 accumulation in "highest" and "high" and TF32 in "medium", and puts the cost of "high" and "highest" at baseline speed or a modest slowdown, about 1 to 2 times.

torch.set_float32_matmul_precision("medium")  # 1 bf16 pass; the TorchTPU default

The same "high" line that made a CUDA script faster makes a TPU script use 3 MXU passes, about 3 times the matmul compute. Translate by intent (chapter 3): if the CUDA setting was chosen for speed, the TPU setting is "medium".

Is the cost real?

The 3x and 6x figures are MXU compute, not end-to-end time, and the documentation gives two cases where they matter less:

  • Large contracting dimensions. In modern models trained with float32 accumulation, such as DeepSeek-V3, accumulation noise and non-determinism across thousands of summed products dominate the lower-order cross terms, so 1-pass is sufficient. The emulation chart shows the same thing from the other side: the 1-pass error does not get worse as \(K\) grows.
  • Memory-bound models. Older float32 models often do not do enough arithmetic per HBM byte to saturate the MXU (chapter 2). Their extra passes fill otherwise idle MXU cycles, so the slowdown is less than 3x or 6x.

A compute-bound float32 matmul, on the other hand, pays the full factor, which is why most models store weights in bf16 and rarely run float32 matmuls at all.

Output precision: keep the accumulator

For bf16 inputs there is no mode to choose; the inputs already fit. What you can choose is the output. torch.mm and torch.bmm on bf16 tensors accumulate in float32 and round the result back to bf16. Passing out_dtype=torch.float32 returns the float32 accumulator instead:

a = torch.randn((2, 256, 256), dtype=torch.bfloat16, device="tpu")
res = torch.bmm(a, a, out_dtype=torch.float32)   # float32 accumulator, no downcast
print(res.dtype)                                  # torch.float32

This is the explicit, eager-safe way to get the extra bits that excess precision gets implicitly. It costs float32 output bytes (4 per element instead of 2, which matters for a memory-bound matmul) and nothing on the MXU. (The CPU build of PyTorch does not implement mm with out_dtype, so the companion code emulates it with .float().)

Excess precision

Retaining more bits than the dtype promises is what the documentation calls excess precision. It arises only when two operations share one compiled program: the producer computes in float32, the consumer could use the float32 value directly, and the question is whether the compiler inserts the downcast to bf16 that the PyTorch dtype implies.

The documentation's example uses two numbers that are exact in bf16:

\[ x = 1 + 2^{-6}, \qquad y = 1 + 2^{-7}, \qquad x y = 1 + 2^{-6} + 2^{-7} + 2^{-13} \]

The product has bits set at mantissa positions 6, 7 and \(6 + 7 = 13\). Positions 6 and 7 fit in bf16's 7 mantissa bits; position 13 does not. Round the product to bf16 and bit 13 disappears (it is far below half a bf16 step, \(2^{-8}\), so it rounds down); keep it in float32 and bit 13 survives. Subtract \(1 + 2^{-6} + 2^{-7}\) and the two paths give \(0\) and \(2^{-13}\).

An animation in nine frames. Step 1 shows x = 1 + 2^-6 = 1.015625 and y = 1 + 2^-7 = 1.0078125 as rows of 7 bf16 mantissa bits. Step 2 shows the exact product 1.0235595703125 as 23 float32 mantissa bits with ones at 6, 7 and 13, bit 13 outlined in orange. Step 3 says the product is formed in float32: on the TPU in the MXU accumulator, in the CPU emulation with .float(). Step 4 splits into two paths: A, round to bf16, taken at every eager op boundary and by compiled code with allow_excess_precision = False, the default; B, keep float32, allowed inside one fused program with allow_excess_precision = True. Step 5 rounds to bf16: bits after position 7 are greyed out, value 1.0234375, bit 13 is gone. Step 6 keeps float32: value 1.0235595703125. Step 7 subtracts bias = 1 + 2^-6 + 2^-7: path A gives 0.0, path B gives 0.0001220703125 = 2^-13. Step 8 shows the documentation's TPU check (A @ B * c)[0, 0] with 256 x 256 bf16 identity matrices: 1.0234375 for eager or compiled with the flag False, 1.0235595703125 for compiled with the flag True. Step 9 is a summary table of both examples and notes that the flag defaults to False and must be set before the first compilation.

The inputs and the operations never change; only the place where rounding happens does. Steps 7 and 8 are two different experiments: the first is an elementwise version, computed on the CPU; the second is the matmul version the TorchTPU documentation runs on a TPU.

The documented TPU behaviour

The documentation's check puts the two numbers on the diagonals of 256 x 256 bf16 matrices, so the multiplication runs on the MXU, and multiplies the result by a float32 c = [1.0] (a 1-element vector rather than a 0-D scalar, because PyTorch's type promotion ignores the dtype of 0-D tensors next to 2-D ones):

def mul_add(a, b, c):
    return a @ b * c          # a, b: bf16 [256, 256]; c: float32 [1]
How mul_add runs (a @ b * c)[0, 0] Bit 13
Eager 1.0234375 dropped: a @ b returns a bf16 tensor before * c
torch.compile(backend="tpu"), allow_excess_precision = False 1.0234375 dropped: the compiler keeps the downcast
torch.compile(backend="tpu"), allow_excess_precision = True 1.0235595703125 kept: the float32 accumulator feeds * c

The companion script reproduces both values on a laptop, rounding the accumulator to bf16 in one case and keeping it in float32 in the other:

$ python code/ch06_precision/excess_precision.py --cpu-smoke
...
2. Elementwise example: prod = x * y; prod - bias   (bias = 1 + 2^-6 + 2^-7)
   product rounded to bf16 (op boundary)      -> 0.0
   product kept in float32 (excess precision) -> 0.0001220703125   (2^-13 = 0.0001220703125)

3. Documented matmul check: (A @ B * c)[0, 0], A = I(1 + 2^-6), B = I(1 + 2^-7), 256 x 256
   A @ B rounded to bf16, then * c            -> 1.0234375
   float32 accumulator kept, then * c         -> 1.0235595703125

The documentation states the TPU behaviour only for the matmul case. The elementwise arithmetic is exact, and the script reproduces it on the CPU, but what a TPU returns for the elementwise version is not documented; run the script's TPU path to see it.

The flag

torch.tpu.allow_excess_precision (Experimental) reads and sets XLA's --xla_allow_excess_precision compiler flag for the whole process:

  • False, the default when neither XLA_FLAGS nor the property sets it, as both the documentation and the property's docstring in _device_module.py state. The compiler keeps the intermediate downcasts to bf16, so fused operations match eager bf16 rounding. (The documentation's example code prints a fallback message that mentions a "default 'True'"; the page's text and the source both give False.)
  • True. The compiler may elide those downcasts and keep fused intermediates in float32.

The XLA runtime locks the flag when the first compilation starts. Setting it to the same value afterwards is a no-op; setting a different value raises RuntimeError. Because Strict eager mode compiles a small program for every new op (chapter 4), "the first compilation" can be your first tensor operation, so set the flag at the top of the script, or outside Python with XLA_FLAGS="--xla_allow_excess_precision=true" (the property's docstring documents both).

import torch

torch.tpu.allow_excess_precision = True   # before any TPU work in this process
model = torch.compile(model, backend="tpu")

This is not only a TPU effect

Excess precision is a property of fusing compilers, not of TPUs. The companion script also runs the elementwise function through a plain torch.compile on the CPU. With PyTorch 2.15 it printed:

6. The elementwise function through torch.compile on this CPU (observed, not asserted)
   eager:    [0.0]
   compiled: [0.0001220703125]

Inductor's compiled kernel kept the product in float32 between the multiply and the subtraction. So "compiled differs from eager in the last bits" can happen on any backend; what TorchTPU adds is a documented switch, defaulting to eager-compatible behaviour, for the TPU compiler. Treat this as one observation on one PyTorch build, not a guarantee; your version may differ.

Eager versus compiled: what changes

Putting the pieces together, these are the precision-relevant differences between running code eagerly and under torch.compile(backend="tpu"):

Eager (Strict) torch.compile
Rounding between ops Every op returns a tensor of its dtype, so a bf16 result is rounded at each op boundary One program; downcasts kept with allow_excess_precision = False (default), may be elided with True
Summation and fusion order Each op compiled on its own at -O1 Whole graph at -O2; fusion can change the order of float32 operations, so the last bits can differ even with the flag False
torch.tpu.precision Works anywhere Causes a graph break; wrap the compiled call instead
torch.set_float32_matmul_precision Applies to matmuls run after the call Set it outside the compiled function, before calling it

The documentation's guidance on interpreting mismatches covers the second row: a high percentage of elements with small absolute differences typically means rounding or accumulation-order differences from compiler fusion, not a bug. The FLUX case study checks a compiled RoPE function against its eager version with torch.testing.assert_close at default float32 tolerances, which is the right test when the computation is float32 elementwise math.

DeferAndFuse, the eager mode that fuses runs of ops into -O2 programs (chapter 4), is not discussed in the precision documentation. The flag is a compiler flag, so fused DeferAndFuse programs are compiled under the same setting; if you need to know whether a particular chain keeps float32 intermediates in that mode, run the script's TPU path with TORCH_TPU_DEFER_AND_FUSE=1 and compare its "eager" line with the documented Strict value.

Mixed precision patterns

The TorchTPU documentation and case studies do not prescribe one recipe, but they agree on a pattern: bf16 where the bytes and FLOPs are, float32 where errors accumulate.

  • Store weights and activations in bf16. The documentation notes that most modern models store weights in bf16. The FLUX case study runs with bf16 block parameters and inputs, and recommends running its attention kernel in bf16 after float32 inputs proved slower.
  • Use autocast with the "tpu" device type. torch.amp.autocast("tpu") is PyTorch's standard autocast; on TPU its default dtype is bf16 (torch.tpu.get_amp_supported_dtype() lists what is supported).
  • Keep reductions and sensitive math in float32. The TorchTPU announcement's Qwen3 235B MoE pod-scale run used "BF16 with FP32 mixed precision reduction": gradient reduction, RoPE and optimizer states in float32. The FLUX case study's RoPE upcasts with .float(), rotates, and casts back with .type_as(x).
  • Leave matmul precision at "medium" and scope torch.tpu.precision(Precision.HIGHEST) to a layer only when you have identified a precision-related convergence problem there.
  • Take the float32 accumulator explicitly with out_dtype=torch.float32 when a following reduction needs it, rather than relying on excess precision.

Loss scaling does not appear in the TorchTPU documentation, and bf16 does not need it: a GradScaler exists to keep small fp16 gradients from underflowing, and bf16 keeps float32's 8-bit exponent and therefore its dynamic range, as Google's bfloat16 overview explains.

Choosing tolerances

A parity check is only as good as its tolerance, and the right tolerance depends on the dtype and on the operation.

Compare like with like. The documentation's first rule: compare bf16 on TPU against bf16 on CPU, or float32 on TPU under Precision.HIGHEST against float32 on CPU. Comparing bf16 against float32 measures quantization error, not hardware drift. Check gradients as well as activations: after loss.backward(), compare model_tpu.weight.grad.cpu() against model_cpu.weight.grad.

Start from PyTorch's defaults. torch.testing.assert_close picks its tolerance from the dtype:

dtype rtol atol
torch.float32 1.3e-6 1e-5
torch.bfloat16 1.6e-2 1e-5
torch.float16 1e-3 1e-5

The documentation's sample report shows the bf16 pair in action ("up to 1e-05 allowed", "up to 0.016 allowed") for a bf16 nn.Linear(10, 10) compared between TPU and CPU, and warns that TorchTPU's bf16 accumulation and fusion differences can exceed these defaults. Relax atol or rtol only where reduced-precision accumulation explains it.

Scale contraction tolerances by their inputs, not their outputs. An element of \(A B\) is a sum of \(K\) products. If each input is rounded with relative error at most \(u\) (\(2^{-8}\) for bf16, half of its epsilon) and the products are summed in float32, the error of each output element is bounded, to first order, by

\[ |C_{ij} - \hat C_{ij}| \le \left(2u + K \cdot 2^{-24}\right) \sum_k |A_{ik}| |B_{kj}| \]

The scale on the right is \(|A| \, |B|\), not \(|C|\). When positive and negative products cancel, \(C_{ij}\) can be small while it still carries the rounding error of every product in it, so any fixed rtol fails on those elements. The companion script shows exactly that: a 1-pass matmul fails both the float32 and the bf16 default tolerances against a CPU float32 reference, and sits at 0.21 of this bound.

5. Default assert_close tolerances and a parity check
   1-pass vs CPU float32 (64 x 64 @ 64 x 64), max abs diff 7.81e-02
     float32 default tolerances:  passed=False
     bfloat16 default tolerances: passed=False   (the error scales with |A| @ |B|, not with the output)
     bound (2 * 2^-8 + K * 2^-24) * (|A| @ |B|): worst element at 0.210 of the bound
   6-pass vs CPU float32, bound (2 * 2^-24 + K * 2^-24) * (|A| @ |B|): 0.064 of the bound

A worst-case bound is loose by design, so it will not catch an error confined to the last few bits. It does catch bugs: multiplying by a transposed operand by mistake, for example, puts the result far outside the bound.

Read the report. When assert_close fails it prints the number of mismatched elements and the greatest absolute and relative differences with their indices. Many small mismatches spread across the tensor point to rounding or accumulation order; a few large ones, or a large greatest absolute difference, point to a logic bug, and the index tells you where to look.

Failure modes

Symptom Likely cause What to do
float32 results differ from a GPU run by about 1e-3 relative TorchTPU defaults to "medium" (1 bf16 pass); PyTorch on CUDA defaults to "highest" Expected. To check the hardware, compare under Precision.HIGHEST against float32
A port runs about 3 times slower in its matmuls than expected The CUDA script's torch.set_float32_matmul_precision("high") now means 3 MXU passes Use "medium"; scope higher precision to the layers that need it
Compiled function differs from eager in the last bits Fusion changed the summation order, or allow_excess_precision = True kept float32 intermediates Check the flag; compare with a tolerance, not torch.equal
RuntimeError when setting torch.tpu.allow_excess_precision A compilation already ran in this process Set it at the very top of the script or through XLA_FLAGS
torch.compile(..., fullgraph=True) fails at torch.tpu.precision The context manager is a graph break Wrap the call to the compiled function, or set the global mode before compiling
Parity fails for bf16 TPU vs float32 CPU Comparing different dtypes measures bf16 quantization Compare bf16 with bf16, or float32 under HIGHEST with float32
Matmul parity fails on a few near-zero elements rtol scaled by the output; cancellation left a small output with a full-size error Use a bound scaled by $
Training diverges or stalls after the port Possibly a precision-sensitive layer; possibly a bug Check parity per layer first; then scope Precision.HIGHEST to the suspect layer and see whether convergence recovers
A default-precision float32 matmul agrees with the CPU to about 1e-7 It did not take one bf16 pass: a global "highest" or "high" is set, or it ran on the CPU Check torch.get_float32_matmul_precision() and the result's device (chapter 3)

When the symptom is just "the numbers differ", this decision flow attributes the difference:

A decision tree read from top to bottom. Four white rounded questions form a spine on the left; each ending answer leads right to a card. First question: Same dtype on both sides? No leads right to an orange card, Quantization, not drift, Compare like with like. Yes leads down to the second question: A float32 matmul at default precision? Yes leads right to a green card, One bf16 pass: about 2e-3, Rerun under Precision.HIGHEST. No leads down to the third question: Compiled differs from eager only? Yes leads right to a green card, Fusion or excess precision, Check allow_excess_precision. No leads down to the fourth question: Inside the error bound for the dtype? Yes leads right to a green card, Precision effect, Pick the tolerance from the bound. No leads down to an orange card under the spine, Likely a bug, Inspect the worst index, bisect layer by layer.

The green cards are differences that the precision rules of this chapter explain; only the two orange cards point to a fault, in the comparison or in the code.

Verifying the result

You have a trustworthy result when a parity check against a CPU float32 reference passes with a tolerance you can derive, and the dtype-matched checks agree. The TPU path of the companion script runs each step:

python code/ch06_precision/excess_precision.py --cpu-smoke                  # laptop: the arithmetic
python code/ch06_precision/excess_precision.py --allow-excess-precision false   # TPU VM, fresh process
python code/ch06_precision/excess_precision.py --allow-excess-precision true    # TPU VM, fresh process
  1. The excess precision setting is what you think. The script prints torch.tpu.allow_excess_precision and runs the documentation's mul_add check. Eager must print 1.0234375; compiled must print 1.0234375 with the flag False and 1.0235595703125 with True. Any other combination means the flag was locked earlier than you expected.
  2. float32 matmuls are within the bound for their mode. Against a CPU float32 reference, a Precision.DEFAULT matmul must sit inside the bf16-input bound \((2 \cdot 2^{-8} + K \cdot 2^{-24}) \, |A||B|\), and its relative error should be close to the CPU emulation's (about \(2 \times 10^{-3}\)). Precision.HIGHEST should sit inside the float32 bound. The script prints both ratios and the emulated errors next to the measured ones.
  3. Dtype-matched parity passes. A bf16 layer on the TPU compared with the same bf16 layer on the CPU, with synchronized weights and identical inputs, passes assert_close at bf16 default tolerances, or fails only with the "many small mismatches" pattern. Repeat for gradients.
  4. Your own model, layer by layer. Apply the same pattern to the layers you ported: parity(out_tpu, out_cpu) from excess_precision.py returns the passed flag and the largest absolute and relative differences instead of raising, and refuses to compare different dtypes.

Keep your output: it records how your TorchTPU version and TPU generation behave. Chapter 23 turns these checks into parity gates for whole models.

Worked problems

Problem 1. Write \(x = 1 + 2^{-6}\) and \(y = 1 + 2^{-7}\) in bf16 and their exact product in float32 (mantissa bits only). Explain why rounding the product to bf16 gives \(1 + 2^{-6} + 2^{-7}\) and not the next bf16 value up.

Answer

\(x\) has mantissa 0000010 and \(y\) has 0000001 (bit 6 and bit 7). The product \(1 + 2^{-6} + 2^{-7} + 2^{-13}\) has a 23-bit float32 mantissa with ones at positions 6, 7 and 13: 00000110000010000000000. bf16 keeps 7 mantissa bits, so its spacing near 1 is \(2^{-7}\) and round to nearest moves a value up only if the discarded part is at least half a step, \(2^{-8}\). The discarded part is \(2^{-13}\), far below \(2^{-8}\), so the result rounds down to \(1 + 2^{-6} + 2^{-7} = 1.0234375\).

Problem 2. A float32 matmul layer accounts for 40% of a step's time and is compute-bound. Estimate that layer's time under "high" and "highest", and say what would make the real slowdown smaller.

Answer

The documentation gives about 3x and 6x MXU compute. If the layer was 0.4 of the step and is compute-bound, it becomes about 1.2 and 2.4 step-units, so the step grows to about 1.8x and 3.0x of the original. The slowdown is smaller if the layer is memory-bound (chapter 2): the extra passes then fill idle MXU cycles and cost much less than 3x or 6x. Storing the weights and activations in bf16 removes the question, since bf16 matmuls take one pass in every mode.

Problem 3. A team compares a float32 model's logits on TPU with the same model on an A100 GPU and finds a maximum relative difference of about 3e-3. They suspect a TorchTPU bug. List, in order, the checks that attribute the difference, and what each outcome means.

Answer

First, the settings: PyTorch on CUDA defaults to "highest" (unless the script changed it), TorchTPU to "medium", which rounds float32 matmul inputs to bf16. About 2e-3 relative per matmul is what one bf16 pass costs, so 3e-3 at the logits is consistent with it. Second, rerun the TPU side with torch.set_float32_matmul_precision("highest") or inside torch.tpu.precision(torch.tpu.Precision.HIGHEST) and compare with a CPU float32 reference rather than the GPU. If the difference drops to float32 level (inside \(K \cdot 2^{-24} |A||B|\) per matmul), the original difference was the precision mode, not a bug. If it does not drop, bisect: compare layer by layer with synchronized weights, find the first layer that leaves its error bound, and inspect the worst index that assert_close reports.

Problem 4. A function f(a, b, c) = (a @ b) * c with bf16 a, b and float32 c returns slightly different values eagerly and under torch.compile(backend="tpu"). The script sets torch.tpu.allow_excess_precision = True on line 50, after a warm-up loop. Explain what you expect to happen, and give two ways to make compiled and eager agree.

Answer

The warm-up loop runs TPU ops, which compile programs, so the flag is locked by line 50. Setting True then raises RuntimeError, because the flag defaults to False and the new value differs. If the script catches the error or the flag was already True through XLA_FLAGS, the compiled program can keep a @ b's float32 accumulator and multiply by c without rounding, while eager rounds a @ b to bf16 first: that is the documented 1.0234375 versus 1.0235595703125 difference. To make them agree: (1) leave the flag at False (the default, and set nothing in XLA_FLAGS), which keeps the downcast in the compiled program; or (2) make both paths keep the accumulator explicitly with torch.mm(a, b, out_dtype=torch.float32) * c (or torch.bmm for batches), so neither path rounds. Even then, fusion can reorder float32 operations, so compare with a tolerance, not torch.equal.

Problem 5. A parity test runs torch.testing.assert_close(out_tpu.cpu(), out_cpu) on a float32 nn.Linear(4096, 4096) at default precision, with out_cpu computed in float32. It fails: 41% of elements mismatched, greatest absolute difference 0.09, greatest relative difference 2.7 at an element where out_cpu is 0.03. Is the layer broken? Choose a tolerance that would make a sound test.

Answer

Probably not. The default float32 tolerances (rtol 1.3e-6, atol 1e-5) assume float32 inputs; at default precision the inputs were rounded to bf16, so the test measures quantization. The huge relative difference is at an output near zero, where cancellation left a small value carrying the rounding error of all 4,096 products: relative tolerance is the wrong scale there. A sound test either compares like with like (rerun under Precision.HIGHEST and keep float32 tolerances, or compare against the CPU emulation of the bf16 pass) or bounds each element by \((2 \cdot 2^{-8} + 4096 \cdot 2^{-24}) \sum_k |x_k| |W_{jk}|\), which is what matmul_error_bound(x, W.t(), BF16_UNIT_ROUNDOFF) computes (W is stored as [out, in], so its transpose is the right-hand matrix; add the bias to both sides first). If every element sits inside that bound, the layer is fine; elements far outside it point to a real error.

Problem 6. A training run is compiled with torch.compile(model, backend="tpu", fullgraph=True). Its final projection to a 256K vocabulary shows unstable loss, and an engineer adds with torch.tpu.precision(torch.tpu.Precision.HIGHEST): around the projection inside forward. The run now fails at compile time. Explain, and give a design that applies the higher precision without breaking the graph. What do you check afterwards?

Answer

torch.tpu.precision calls torch._dynamo.graph_break(); with fullgraph=True a graph break is an error. Without fullgraph, the frame would silently fall back to eager, which is worse for performance. Options: set the mode for the whole compiled call, either globally with torch.set_float32_matmul_precision("highest") before compiling or by wrapping the call with torch.tpu.precision(torch.tpu.Precision.HIGHEST): loss = compiled_model(x); but that makes every float32 matmul in the model 6 passes. Better: compile the body and the projection as two functions and wrap only the projection's call in the context manager, or keep the projection's inputs in bf16 and request out_dtype=torch.float32 if the issue is rounding of the logits rather than of the inputs. Afterwards check two things: that the loss is stable (the precision hypothesis was right), and the step time, since a 6-pass projection over a 256K vocabulary is a large compute-bound matmul and will cost close to 6 times its 1-pass time.

Quick questions

  1. How many exponent and mantissa bits do float32, TF32 and bfloat16 have, and what is bf16's machine epsilon?
  2. Which operations run on the MXU and which on the VPU, and at what precision does each compute?
  3. Map "medium", "high" and "highest" to torch.tpu.Precision, MXU passes and significand bits. Which is the TorchTPU default, and which is the CUDA default?
  4. Why are the pass counts 1, 3 and 6, and which three cross terms does no mode compute?
  5. What does out_dtype=torch.float32 change for a bf16 torch.bmm, and what does it cost?
  6. What is excess precision, what does torch.tpu.allow_excess_precision default to, and when can you no longer change it?
  7. Name two reasons a compiled function can differ from its eager version in the last bits.
  8. Why does a fixed rtol fail for matmul outputs near zero, and what should the tolerance scale with?

Key takeaways

  • bf16 keeps float32's 8-bit exponent and only 7 mantissa bits (epsilon \(2^{-7}\)): float32's range with about two to three decimal digits of precision.
  • The MXU multiplies bf16 (fp8 on v7x) and accumulates in float32; the VPU computes elementwise ops, norms and softmax in float32.
  • TorchTPU's default "medium" / Precision.DEFAULT runs a float32 matmul as one bf16 pass, about 2e-3 relative error for random data. "high" takes 3 passes (about 3x MXU compute) and "highest" 6 (about 6x). CUDA's default is "highest", so expect differences from GPU float32 runs.
  • Scope higher precision with torch.tpu.precision, around compiled calls rather than inside them, and only for layers with a demonstrated precision problem.
  • Excess precision keeps float32 intermediates inside a fused program. torch.tpu.allow_excess_precision defaults to False (compiled matches eager rounding) and locks at the first compilation.
  • Compare like with like: bf16 with bf16, float32 under HIGHEST with float32. Start from PyTorch's dtype defaults, and bound matmul errors by \(|A| \, |B|\), not by the output.
  • Mixed precision on TPU: bf16 weights and activations, torch.amp.autocast("tpu"), float32 for reductions, RoPE and optimizer state.

References