Skip to content
Skip to lesson
Back to Topics
LearnGPU Systems & LLM InferenceLow-Precision GPU Programming
HardInference Optimization13 min read

Low-Precision GPU Programming

A scaled FP8 round trip can turn 500 into 10 with no NaN. The scale, the accumulator, and the kernel interface decide whether that loss stays visible.

On this page

Feed the number 500 through a scaled FP8 conversion and it can come back as 10, with zero exceptions, zero infinities, and zero NaN flags. An older batch's scale factor (10 / 448) left 500 far above the E4M3 ceiling of 448, so saturating conversion quietly clamped it to 448 and reconstructed 448 × (10 / 448) = 10 (a 98% error). Even an FP32 accumulator downstream happily multiplies and sums that corrupted 10 without ever knowing 490 vanished.

A prior amax of 10 sets S_old to 10 divided by 448. Current x=500 becomes scaled input 22,400, clips to finite E4M3 code 448, then reconstructs to 10. The original-value number line maps 0 to 500 and shows x-hat=10 beside x=500, a 490-unit or 98% relative loss; the FP32 accumulator receives 10 times the weight.
Stale delayed scaling turns 500 into 10: scaled to 22,400, saturated to E4M3 max 448, and reconstructed to 10 with no NaN flag.

Low-precision programming is therefore about four explicit choices, never just flipping a dtype: encoding (bitfields and special values), scaling architecture (what shares a scale and when it is measured), arithmetic and accumulation (input vs. product vs. accumulator precision), and kernel ABI (layouts, alignment, and vendor conventions).

Format taxonomy: range, spacing, and bitfields

Exponent bits control dynamic range; fraction (mantissa) bits control spacing inside each binary octave (binade):

FormatBits (S / E / M)BiasMax finiteSmallest normalTypical GPU role
FP321 / 8 / 231273.40×10383.40 \times 10^{38}1.18×10−381.18 \times 10^{-38}Reference math, accumulation
TF32FP32 storage (8E / 10M read)1273.40×10383.40 \times 10^{38}1.18×10−381.18 \times 10^{-38}Fast FP32 Tensor Core matmuls (no storage savings)
BF161 / 8 / 71273.39×10383.39 \times 10^{38}1.18×10−381.18 \times 10^{-38}Wide-range activations, weights, gradients
FP161 / 5 / 101565,5046.10×10−56.10 \times 10^{-5}Higher precision, narrow range
FP8 E4M31 / 4 / 374482−6=0.0156252^{-6} = 0.015625Forward activations and weights
FP8 E5M21 / 5 / 21557,3442−14≈6.1×10−52^{-14} \approx 6.1 \times 10^{-5}Backward gradients and wide-range tensors

The OCP OFP8 specification[1] pairs E4M3 forward (spacing 0.125 in [1,2)[1, 2), no infinities, 0x7F/0xFF reserved for NaN) with E5M2 backward (wider range up to 57,344, spacing 0.25 in [1,2)[1, 2)).[2][3] Below 8 bits, block-scaled formats attach a tiny shared scale to small element groups:

E4M3 and E5M2 bit strips allocate their eight bits to one sign, four or five exponent bits, and three or two fraction bits. On the same one-to-two number line, E4M3 marks are spaced by 0.125 and E5M2 marks by 0.25. A close view around 2 shows the E4M3 step widening from 0.125 below the boundary to 0.25 above it.
E4M3 trades one exponent bit for finer spacing (0.125 vs. E5M2's 0.25 in [1, 2)), and spacing doubles at every power-of-two binade boundary.

Scale ownership and the GEMM dataflow

In Y=XWY = XW (X∈RM×KX \in \mathbb{R}^{M \times K}, W∈RK×NW \in \mathbb{R}^{K \times N}), where can scales be applied? If each row of XX shares scale SX,iS_{X,i} and each column of WW shares scale SW,jS_{W,j}, neither depends on the contraction index kk, so both factor straight out into the GEMM epilogue:

Y^ij=(SX,i⋅SW,j)∑k=1KX~ikW~kj\hat{Y}_{ij} = \left(S_{X, i} \cdot S_{W, j}\right) \sum_{k=1}^K \tilde{X}_{ik} \tilde{W}_{kj}

By contrast, when scales vary along KK (as in 32-element MX blocks), the scale product cannot leave the outer sum:

Y^ij=∑b=1⌈K/32⌉(SX,i,b⋅SW,j,b)∑k∈block bX~ikW~kj\hat{Y}_{ij} = \sum_{b=1}^{\lceil K/32\rceil} \left(S_{X, i, b} \cdot S_{W, j, b}\right) \sum_{k \in \text{block } b} \tilde{X}_{ik} \tilde{W}_{kj}

For two blocks with partial sums [2, 3] and scale products [5, 8], the true block-scaled dot product is 5(2)+8(3)=345(2) + 8(3) = 34, whereas mistakenly pulling scale 5 outside gives 5(2+3)=255(2 + 3) = 25.[4][6]

FP8 scale factoring dataflow. Top five-stage pipeline moves X and W through quantization (Q, S), packed storage, FP8 MMA with FP32 accumulation, and epilogue rescaling plus BF16 cast. Bottom left shows row/column scales factoring cleanly outside the K-sum: Y_ij = S_{X,i} * S_{W,j} * sum_k q_{X,ik} q_{W,kj}. Bottom right shows K-varying block scales staying inside the contraction: block 0 (5 * 2 = 10) plus block 1 (8 * 3 = 24) equals 34, whereas factoring 5 outside gives the wrong value 25.
Row/column scales factor into the GEMM epilogue; K-varying block scales must apply per block inside the contraction (5×2 + 8×3 = 34, not 25).

Numerical hazards: subnormals, saturation, and rounding

Three encoding behaviors silently alter numbers before the accumulator ever runs:

  1. Subnormals and RNE ties: OCP E4M3's smallest normal is 2−62^{-6} and its smallest subnormal is d=2−9≈0.001953d = 2^{-9} \approx 0.001953. Under round-to-nearest-even (RNE), 0.75 d rounds up to d, while exact tie 0.5 d rounds to signed zero (±0.0). Some GPU modes also flush denormals to zero (FTZ).[7]
  2. Saturation cliffs: Saturating conversion (__NV_SATFINITE) clamps 500 and 50,000 identically to 448; non-saturating conversion turns overflow into E4M3 NaN or E5M2 ±inf.[8]
  3. Stochastic rounding (SR) vs. RNE: Repeated small weight updates can stall under RNE when RNE(W+ΔW)=W\text{RNE}(W + \Delta W) = W. Stochastic rounding rounds to neighboring representable values l<x<ul < x < u with probabilities x−lu−l\frac{x - l}{u - l} (up) and u−xu−l\frac{u - x}{u - l} (down), making E[SR(x)]=x\mathbb{E}[\text{SR}(x)] = x unbiased for any finite xx inside range (for x=1.01x = 1.01 between 1.0 and 1.125, p(1.125) = 0.08, expected value 1.01).[5] Also verify internal MMA precision: even an FP32 accumulator register can use narrower internal product or accumulation precision inside Tensor Core MMA instructions.[9]
Dual-zoom FP8 E4M3 conversion boundary rulers. Left zoom magnifies 0 to the smallest E4M3 subnormal d = 2^-9: round-to-nearest-even maps tie midpoint 0.5d to signed zero (even) and 0.75d up to d. Right zoom spans 0 to 500 with S = 1: the finite E4M3 ceiling stops at 448, clamping unscaled input x = 500 to code q = 448 and reconstructing 448 without emitting NaN.
E4M3 subnormal tie rounding around d=2−9d = 2^{-9} (left) and saturating ceiling clamp at 448 (right).
A shared linear number line places 1.01 eight percent of the way between neighboring representable values 1 and 1.125. Round-to-nearest-even chooses 1. A deterministic probability bar assigns 0.92 mass to 1 and 0.08 to 1.125, whose weighted expectation is 1.01. A separate saturation lane shows 500 clipped to 448 beyond the finite neighbor interval.
Stochastic rounding between representable neighbors `1.0` and `1.125` gives `1.01` an 8% chance of rounding up, preserving exact expectation `1.01`.

Hands-on: inspecting FP8 conversion thresholds and ABI bytes

Run this PyTorch check on CPU to see E4M3 subnormal rounding, saturation, and a notorious cross-vendor trap: the exact same raw byte 0x38 decodes to 1.0 in OCP E4M3 (bias 7) and 0.5 in AMD CDNA3 FNUZ E4M3 (bias 8), while 0x80 decodes to -0.0 in OCP and NaN in FNUZ![10][11]

fp8-conversion-and-abi.py
import torch

d = 2.0 ** -9
vals = torch.tensor([0.5 * d, 0.75 * d, -0.5 * d, 1.0625, 1.1875, 500.0])
cast = vals.clamp(-448.0, 448.0).to(torch.float8_e4m3fn).float()
print("E4M3 round-trip:", cast.tolist())
print("negative tie preserves -0.0:", bool(torch.signbit(cast[2])))

raw_bytes = torch.tensor([0x38, 0x80], dtype=torch.uint8)
print("OCP  E4M3 (0x38, 0x80):", raw_bytes.view(torch.float8_e4m3fn).float().tolist())
print("FNUZ E4M3 (0x38, 0x80):", raw_bytes.view(torch.float8_e4m3fnuz).float().tolist())
Output
E4M3 round-trip: [0.0, 0.001953125, -0.0, 1.0, 1.25, 448.0]
negative tie preserves -0.0: True
OCP  E4M3 (0x38, 0x80): [1.0, -0.0]
FNUZ E4M3 (0x38, 0x80): [0.5, nan]
The same raw bytes enter two E4M3 decoder conventions. The byte 0x38 has sign 0, exponent bits 0111, and fraction bits 000; bias 7 decodes it as 1.0 while bias 8 decodes it as 0.5. The byte 0x80 has sign 1, exponent 0000, and fraction 000; OCP decodes negative zero while FNUZ reserves that byte for NaN.
Identical bytes decode differently across OCP (bias 7) and FNUZ (bias 8): `0x38` shifts from 1.0 to 0.5 and `0x80` flips from `-0.0` to `NaN`.

Scaling architectures: granularity and delayed scaling

Watch the reciprocal convention in every library: here S=amax/448S = \text{amax} / 448 is the reconstruction scale (x^=Sq\hat{x} = S q), while many APIs store α=1/S=448/amax\alpha = 1/S = 448/\text{amax} (q=Q(αx)q = Q(\alpha x)). For an all-zero block, set an explicit positive scale like 1.0 instead of dividing by zero.

Two schematic device timelines comparing current and delayed FP8 scaling. Current scaling performs two tensor passes: Read X, compute amax_t and S_t, Read X again, cast and write Q, then GEMM. Delayed scaling reads X in one pass, splitting into an upper branch (compute amax_t, record a_t into future history H_{t+1}) and a lower branch (cast with historical S_t = max(H_t)/448 from the 3-step history ring [a_{t-3}, a_{t-2}, a_{t-1}], write Q, then GEMM) with zero crossing paths.
Current scaling makes two passes during quantization (amax + cast); delayed scaling casts in one pass using historical amax while recording today's amax for future steps.

Microscaling: the two-row experiment

What happens when a small activation (0.001) shares one tensor-wide scale with a spike (500.0) versus getting its own 32-element MX block scale? Let's run it in PyTorch, and then expose a subtle cancellation trap:

fp8-two-row-microscaling.py
import math
import torch

x = torch.tensor([
    [0.001, 0.03, 0.117, 0.5, 1.0, -0.25, 0.0625, -0.015625] * 4,
    [4.0, 16.0, 64.0, 500.0, -2.0, -8.0, -32.0, -250.0] * 4,
], dtype=torch.float32)
w = torch.tensor([0.5, -0.25, 0.125, -0.0625, 0.03125, -0.5, 0.25, -0.125] * 4).reshape(32, 1)
fp8_max = torch.finfo(torch.float8_e4m3fn).max

def quant_rt(t, s):
    return (t / s).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn).float() * s

def mx_scale(block):
    r = block.abs().max().item() / fp8_max
    return 1.0 if r == 0 else 2.0 ** max(-127, math.ceil(math.log2(r)))

# Tensor-wide vs 32-element power-of-two block scaling
x_ten = quant_rt(x, x.abs().max() / fp8_max)
w_ten = quant_rt(w, w.abs().max() / fp8_max)
s_mx = torch.tensor([mx_scale(row) for row in x]).reshape(2, 1)
x_mx = quant_rt(x, s_mx)
w_mx = quant_rt(w, torch.tensor(mx_scale(w)))

ref_y, ten_y, mx_y = (x @ w).squeeze(), (x_ten @ w_ten).squeeze(), (x_mx @ w_mx).squeeze()
print(f"x[0,0]=0.001 -> tensor={x_ten[0,0]:.6f} (WIPED!), MX={x_mx[0,0]:.6f}")
print(f"x[1,3]=500.0 -> tensor={x_ten[1,3]:.1f}, MX={x_mx[1,3]:.1f}")
print(f"dot y: ref={ref_y.tolist()}, tensor={[round(v, 4) for v in ten_y.tolist()]}, MX={mx_y.tolist()}")

# Cancellation hides the 500 -> 512 error in mx_y[1]=7.75; a one-hot selector exposes +12.0 error!
sel = torch.zeros_like(w); sel[3, 0] = 1.0
print(f"spike-only dot: ref={(x @ sel)[1].item():.1f}, MX={(x_mx @ sel)[1].item():.1f}")
Output
x[0,0]=0.001 -> tensor=0.000000 (WIPED!), MX=0.000977
x[1,3]=500.0 -> tensor=500.0, MX=512.0
dot y: ref=[0.6008124947547913, 7.75], tensor=[0.5831, 7.5684], MX=[0.6015625, 7.75]
spike-only dot: ref=500.0, MX=512.0

Look at two sharp lessons from those four lines of output:

  1. Under tensor-wide scaling (S=1.116S = 1.116), 0.001 falls below half of the smallest scaled E4M3 step (0.5 × 0.00218 = 0.00109) and vanishes to zero! Under MX block scaling (S0=2−8S_0 = 2^{-8}), 0.001 survives cleanly at 0.000977 (2.3% error), with just 1 E8M0 byte per 32 elements (66 B vs. 68 B for a 64-element activation).[16]
  2. On row 1, 500.0 rounds to 512.0 under S1=2.0S_1 = 2.0, yet mx_y[1] still matches 7.75 identically because positive and negative rounding errors cancel (184 - 176.25 = 7.75). Swap WW to a one-hot selector and the hidden 12.0 error jumps right out!
For the same 64-element FP8 activation X, 64 code bytes plus one four-byte tensor scale total 68 bytes. Two 32-element MX groups use 64 code bytes plus two one-byte E8M0 scales, totaling 66 bytes. The scale-byte inset draws each metadata byte three times wider than each code-byte cell. E8M0 examples map 0x77 to 2 to the minus 8, 0x80 to 2, 0x00 to a positive scale, and 0xff to NaN. The MX payload is 8.25 bits per value, with scale bytes equal to 3.125 percent of the 64 code bytes.
64 FP8 elements take 68 bytes with one FP32 tensor scale vs. 66 bytes with two 1-byte E8M0 MX scales (8.25 bits/value).
Two side-by-side layouts show one scale shared by both 32-value rows and one scale owned by each row. Separate original-value zooms plot the exact reconstructions: 0.001 becomes 0 with the shared tensor scale and 0.00097656 with the row scale; 500 stays 500 with the tensor scale and becomes 512 with the second row scale.
Per-row MX scaling rescues `0.001` from flushing to zero, while power-of-two rounding shifts `500` to `512` in row 1.
The 32-value activation row repeats an eight-value pattern four times; highlighted spikes at indices 3, 11, 19, and 27 reconstruct from 500 to 512. Grouped positive and negative real-arithmetic sums meet at 7.75: 181 plus negative 173.25 for FP32 values, and 184 plus negative 176.25 for reconstructed operands. A full 32-entry one-hot W selector has only w3 set to 1; at index 3 it exposes 500 versus 512, an absolute error of 12.
Cancellation masks the 500→512 error inside the 7.75 dot product; a one-hot selector exposes the 12-unit operand error immediately.
One logical 32 by 32 high-precision matrix can be quantized with horizontal 1 by 32 groups or vertical 32 by 1 groups. The highlighted horizontal group contains all 32 values of row i; the highlighted vertical group contains all 32 values of column j. Transposing encoded bytes carries their existing group ownership, so derive the columnwise representation from the original wider matrix.
Row-wise (1×32) and column-wise (32×1) blocks group completely different elements; quantize each orientation from the original wider matrix.

Hardware support and troubleshooting numerical failures

Always check target microarchitecture and toolkit tables before shipping: NVIDIA Hopper/Ada support FP8, Blackwell (SM 10.x) adds hardware MXFP8/NVFP4 block-scaled MMA, AMD CDNA3 uses FNUZ FP8 while CDNA4/RDNA4 adopt OCP FP8, and PyTorch exposes modern torch.backends.cuda.matmul.fp32_precision = "tf32" | "ieee" controls.[7][16][5][11]

SymptomLikely root causeFix
Many FP8 codes equal ±448Saturation clipping from stale or tight scaleInspect pre-cast scaled magnitudes; widen margin or switch to current/block scaling.
Entire row flushes to 0.0Shared scale dominated by an outlier in another rowMove from tensor-wide to row-wise or 32-element MX block scaling.
Output collapses when porting NVIDIA → AMDOCP (bias 7) vs. FNUZ (bias 8) byte mismatchCheck hex byte 0x38; explicitly transcode between OCP and FNUZ.
Backward pass turns to noise after transposeScale orientation mismatchQuantize row-major and column-major views from the wider source tensor.
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A saturating OCP E4M3 conversion uses reconstruction scale S=7/448 from a previous maximum. The current finite activation is 700. What reconstructed operand and relative magnitude error reach the next consumer?
2.Let d=2^-9 be OCP E4M3’s smallest positive subnormal. Under round-to-nearest-even with preserved signed zero, what do positive 0.25d and positive 1.5d become?
3.A finite input 1.09375 lies between representable neighbors 1 and 1.125. Proper stochastic rounding uses only those two outcomes, without clipping. Which upper-neighbor probability and expected rounded value follow?
4.For normal OCP E4M3 numbers, compare the adjacent spacing just below 4, in [2, 4), with the spacing just above 4, in [4, 8). Which ordered pair is correct?
5.Two contraction blocks have coded partial dots -3 and 4, with positive reconstruction-scale products 2 and 5 respectively. In real arithmetic over reconstructed operands, what is the correctly scaled total and the result of wrongly pulling scale product 2 outside both blocks?
6.A declared payload layout stores five logical rows of 33 FP8 values. Each row is physically padded to two full 32-value blocks, and each block stores one E8M0 byte. Exclude other tensors and allocator alignment. What is the total stored operand payload?
7.A wide reference gives 10 for a dot product with the original operands and 8 with the reconstructed FP8 operands. The kernel returns 8 for the same FP8 inputs. What are the signed changes in the output when you first replace the operands and then run the kernel?
8.A matrix cell holds 1/256 before quantization. Its row scale is 8 and its column scale is 1/512. Both encoders divide by their scale and round to the nearest OCP E4M3 value. The smallest positive E4M3 value is 1/512. For a fresh columnwise encoding of the matrix, which input should the column encoder read and what FP8 code value should it store for this cell?
9.An OCP E4M3 producer stores byte 0x40 for value 2. A FNUZ E4M3 consumer interprets that unchanged byte, then multiplies by 3. What result follows, and which FNUZ byte explicitly preserves the producer’s value before multiplication?
10.Compare 64 values in two explicitly one-dimensional FP4 activation payloads without padding. NVFP4 uses one E4M3 scale per 16 values plus one FP32 tensor scale. MXFP4 uses one E8M0 scale per 32 values. What are their total payloads, NVFP4 first?

10 questions remaining.

References

OCP 8-bit Floating Point Specification (OFP8), Revision 1.0

Open Compute Project · 2023

https://www.opencompute.org/documents/ocp-8-bit-floating-point-specification-ofp8-revision-1-0-2023-12-01-pdf-1

Using FP8 and FP4 with Transformer Engine

NVIDIA · 2026

https://docs.nvidia.com/deeplearning/transformer-engine/examples/fp8_primer.html

FP8 Formats for Deep Learning.

Micikevicius, P., et al. · 2022

https://arxiv.org/abs/2209.05433

OCP Microscaling Formats (MX) Specification, Version 1.0

Open Compute Project · 2023

https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf

Transformer Engine NVFP4 Recipe

NVIDIA · 2026

https://docs.nvidia.com/deeplearning/transformer-engine/features/low_precision_training/nvfp4/nvfp4.html

PTX ISA: Fifth-Generation TensorCore Instructions

NVIDIA · 2026

https://docs.nvidia.com/cuda/parallel-thread-execution/#tensorcore-5th-generation-instructions

Numerical Accuracy

PyTorch Contributors · 2026 · Official PyTorch Documentation

https://docs.pytorch.org/docs/stable/notes/numerical_accuracy.html

FP8 Conversion and Data Movement

NVIDIA · 2026 · CUDA Math API

https://docs.nvidia.com/cuda/cuda-math-api/cuda_math_api/group__CUDA__MATH__FP8__MISC.html

Parallel Thread Execution ISA

NVIDIA · 2026

https://docs.nvidia.com/cuda/parallel-thread-execution/

Tensor Attributes

PyTorch Contributors · 2026 · Official PyTorch Documentation

https://docs.pytorch.org/docs/stable/tensor_attributes.html

Data Types and Precision Support

AMD · 2026 · ROCm Documentation

https://rocm.docs.amd.com/en/docs-10.0.0/reference/precision-support.html

Transformer Engine FP8 Current Scaling

NVIDIA · 2026

https://docs.nvidia.com/deeplearning/transformer-engine/features/low_precision_training/fp8_current_scaling/fp8_current_scaling.html

Transformer Engine FP8 Delayed Scaling

NVIDIA · 2026

https://docs.nvidia.com/deeplearning/transformer-engine/features/low_precision_training/fp8_delayed_scaling/fp8_delayed_scaling.html

DeepSeek-V3 Technical Report.

DeepSeek-AI · 2024 · arXiv preprint

https://arxiv.org/abs/2412.19437

DeepGEMM Source Snapshot, July 15 2026

DeepSeek AI and Contributors · 2026

https://github.com/deepseek-ai/DeepGEMM/tree/559d79fb6994a58b8a15b4b93bf13ccc16edf247

MXFP8

NVIDIA · 2026

https://docs.nvidia.com/deeplearning/transformer-engine/features/low_precision_training/mxfp8/mxfp8.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.