Mixed precision II: FP8, microscaling and the 4-bit frontier
With 8 bits a global scale is no longer enough: the range is short enough to require a per-tensor factor, while outliers motivate block scaling. We study E4M3 and E5M2, current and delayed tensor scaling, the FP8 matmul recipe, DeepSeek-V3 tile scaling and MX formats, and instabilities that emerge only in long training runs. The lab checks compatibility before measuring native FP8 matmuls: on the RTX 3060 used here it compares quantization, emulation, and BF16 without attributing native FP8 acceleration to that device. Code is also provided for compatible GPUs, and the lesson closes with the FP4 training frontier.
After this lesson you can
- Quantize tensors to E4M3 and E5M2 with per-tensor, tile and MX block scaling, and measure error against BF16.
- Explain delayed scaling with an amax history and its risks when activation spikes occur.
- Run scaled FP8 matmuls on compatible GPUs, measure performance and error, and distinguish these from emulation on unsupported hardware.
- Design and justify an FP8 recipe choosing which layers and tensors remain in BF16.
- Summarize techniques that make FP4 training viable and their current limitations.
Before you start
Eight bits are not a complete recipe
Mixed-precision training separates the storage format from computation and accumulation. With eight bits you must also choose the scale: one outlier can determine it for an entire tensor and cause small values to be represented at low resolution. A product of two quantized matrices also needs a way to undo the scales. The error of an isolated conversion and the accumulated effect on training are different questions.
The figure uses 4096 values from the first MLP layer output of an initialized small GPT, computed with PyTorch and the class from m18-l12. This is not a tensor from a trained model. Changing the scale shifts the representable-value grid relative to that fixed sample. Values outside the finite range saturate and those near zero can round to zero. Capture code appears in the local lab below.
E4M3 provides more resolution within an exponent interval; E5M2 provides more range. A common recipe uses E4M3 for forward activations and weights and E5M2 for gradients. This is not a law: DeepSeek-V3 uses E4M3 for all operands of its low-precision products with fine-grained scaling. The previous lesson’s loss scaling and this lesson’s quantization scaling address related problems but are distinct factors.
Scale is part of the representation
Per-tensor scaling chooses the dequantization factor for nonzero absolute maximum and maximum finite value . Compute and reconstruct . Alternatively the reciprocal is called the scale: always check the convention. A scale with more headroom reduces future saturation at the cost of resolution. If , choose and preserve zeros.
Current scaling computes the maximum of the tensor being quantized. Delayed scaling reuses earlier statistics to keep the current reduction off the critical path. If a new spike appears, its magnitude may exceed and saturate without producing NaN. A longer maximum history protects against a past spike but may leave an excessive scale afterward; neither predicts the future. Count saturations and error, not just finite values.
In the documented Transformer Engine recipe, current scaling reads the tensor to obtain the maximum and reads it again to convert; delayed scaling obtains the scale from history and records the maximum for a later step. Reduction can be implemented differently: do not extrapolate that count to every kernel.
An FP8 GEMM recipe converts both operands, computes the product with the accumulation guaranteed by the kernel, and descales. If both scales are scalars, . With different scales along the reduction dimension, each partial product needs its own pair of factors before summation. Accumulation precision and output type cannot be inferred from the name FP8. The DeepSeek report describes promoting partial sums to FP32 every 128 products in its H800 implementation; this is not a property of all GEMMs.
A concrete policy helps distinguish mechanism from choice. DeepSeek-V3 retains embeddings, output head, MoE gates, normalizations, and attention operators in higher precision; it also keeps master weights, weight gradients, and optimizer states in higher precision. This is a published recipe for that training run, not proof that all those operations must remain in BF16 for every architecture. For another network, test each exclusion with the same seed, data, and budget, and observe loss, gradients, and saturation.
Speed depends on shape and conversion cost. In NVIDIA’s benchmark for a 5B model on H200, the delayed-scaling recipe reaches approximately 1.69 times the BF16 speed of its GEMMs, whereas comparing already quantized data reaches 1.92. These are published results for that configuration, not RTX 3060 measurements or a guarantee for small matrices.
Small groups, metadata, and outliers
Fine-grained block scaling assigns a scale to each group. DeepSeek-V3 describes activations in tiles and weights in blocks. In MX, MXFP8 groups 32 FP8 elements with an 8-bit power-of-two E8M0 scale. A scale per group costs memory and work, but lets a group of small values avoid sharing a scale with an outlier in another group. If both fall in the same group, the problem persists.
A complete MXFP8 group takes 32 bytes of elements plus one scale byte: 3.125% overhead relative to data, excluding alignment. One FP32 scale per 128 FP8 elements adds 4 bytes to 128, also 3.125%. These are storage figures and exclude temporaries, packing, and memory access.
Lab: represent and reconstruct
This simulator enumerates finite magnitudes by their bit pattern and rounds to the nearest neighbor, breaking ties toward the even pattern. We saturate to the finite maximum before converting; we do not simulate NaN or infinity propagation. scale is the dequantization factor. Quantized values are stored in higher-precision NumPy values to study error: the program does not pack bits or execute native FP8 operations.
import numpy as np
def grid(fmt):
if fmt == 'e4m3':
mb,bias,last = 3,7,126
elif fmt == 'e5m2':
mb,bias,last = 2,15,123
else:
raise ValueError('formato desconocido')
values = []
for bits in range(last+1):
exponent,mantissa = divmod(bits,1 << mb)
v = ((mantissa/(1 << mb))*2.**(1-bias) if exponent == 0 else
(1+mantissa/(1 << mb))*2.**(exponent-bias))
values.append(v)
return np.asarray(values)
def quantize(x,fmt='e4m3'):
vals = grid(fmt)
x = np.asarray(x,dtype=np.float64)
if not np.all(np.isfinite(x)):
raise ValueError('solo entradas finitas')
mag = np.abs(x)
hi = np.minimum(np.searchsorted(vals,mag,side='left'),len(vals)-1)
lo = np.maximum(hi-1,0)
dl,dh = mag-vals[lo],vals[hi]-mag
idx = np.where((dh < dl) | ((dh == dl) & (hi%2 == 0)),hi,lo)
return np.copysign(vals[idx],x)
print('máximos:',grid('e4m3')[-1],grid('e5m2')[-1])
print('empates E4M3:',quantize([1.0625,1.1875]))
assert grid('e4m3')[-1] == 448 and grid('e5m2')[-1] == 57344
assert np.array_equal(quantize([1.0625,1.1875]),[1.,1.25])The next converter groups consecutive values and uses one scale per group. For MX it chooses the smallest power of two that avoids saturating the maximum, within E8M0 exponents from -127 to 127; this is an explicit conversion recipe, not the only one allowed by the specification. For tiles it groups each row of 128; a matrix of another width must respect its boundaries. Weight blocks of require grouping along both dimensions, not arbitrary flattening. Below we compare global and flat groups of 32 for specific matrices.
def scaled(x,fmt='e4m3',block=None,power2=False):
x = np.asarray(x,dtype=np.float64)
flat = x.ravel()
block = len(flat) if block is None else block
out = np.empty_like(flat); scales = []
maximum = grid(fmt)[-1]
for start in range(0,len(flat),block):
part = flat[start:start+block]
amax = np.max(np.abs(part),initial=0)
scale = amax/maximum if amax else 1.
if power2:
scale = 2.**np.clip(np.ceil(np.log2(scale)),-127,127)
scales.append(scale)
out[start:start+block] = quantize(part/scale,fmt)
return out.reshape(x.shape),np.asarray(scales)
def dequant(q,scales,block=None):
q = np.asarray(q); flat = q.ravel()
block = len(flat) if block is None else block
out = np.empty_like(flat)
for i,start in enumerate(range(0,len(flat),block)):
out[start:start+block] = flat[start:start+block]*scales[i]
return out.reshape(q.shape)
def qdq(x,fmt='e4m3',block=None,power2=False):
q,s = scaled(x,fmt,block,power2)
return dequant(q,s,block)
def bf16(x):
x = np.asarray(x,dtype=np.float32)
bits = x.view(np.uint32)
rounded = bits+np.uint32(0x7fff)+((bits >> 16)&1)
return (rounded & np.uint32(0xffff0000)).view(np.float32)
rng = np.random.default_rng(21)
a = rng.standard_normal((64,128)).astype(np.float32)
w = rng.standard_normal((128,64)).astype(np.float32)
a[:,3] *= 30
ref = a @ w
for name,aa,ww in [('BF16',bf16(a),bf16(w)),('FP8 global',qdq(a),qdq(w)),
('FP8 bloque 32',qdq(a,block=32,power2=True),qdq(w,block=32,power2=True))]:
print(name,'error relativo Frobenius:',np.linalg.norm(aa@ww-ref)/np.linalg.norm(ref))With that seed, observed error is approximately 0.00247 for BF16 operands, 0.03532 for global FP8 scaling, and 0.03872 for flat groups of 32. Blocks do not win on this sample: results depend on where outliers fall, layout, and power-of-two scales. Do not select a result merely to make finer granularity look always better. All these products accumulate with NumPy, not an FP8 Tensor Core.
Now quantize activations in tiles and weights in blocks. The operation handles incomplete edges correctly. It descales each block before multiplication to study quantization error; an efficient kernel would integrate scale handling with the partial product and accumulation.
def tiled_qdq(matrix,rows,cols):
matrix = np.asarray(matrix)
result = np.empty_like(matrix,dtype=float)
for i in range(0,matrix.shape[0],rows):
for j in range(0,matrix.shape[1],cols):
sl = (slice(i,i+rows),slice(j,j+cols))
result[sl] = qdq(matrix[sl])
return result
at = tiled_qdq(a,1,128)
wt = tiled_qdq(w,128,128)
print('error relativo teselas:',np.linalg.norm(at@wt-ref)/np.linalg.norm(ref))
assert at.shape == a.shape and wt.shape == w.shapeDelayed scaling uses only previous maxima. In this example a spike of amplitude 10 at step 8 exceeds the threshold computed before observing it. Once it enters history, the scale remains large for several steps and reduces resolution for small values. The next cell shows when saturation occurs; the figure also calculates the captured sample’s error and signal-to-noise ratio.
amax = [1.]*8+[10.]+[1.]*6
history = 4
for i,current in enumerate(amax):
previous = max(amax[max(0,i-history):i],default=1.)
print(i,'amax actual:',current,'umbral diferido:',previous,'satura:',current>previous)An MLP with simulated FP8
This small regression applies quantization and reconstruction of operands in forward and backward multiplications, with E5M2 for the propagated gradient and E4M3 for other operands. Derivatives are manual: weights stay and are updated in higher precision. Evaluation uses the same training data; this is a short numerical check, not a test of generalization or long-term stability.
rng = np.random.default_rng(7)
x = rng.standard_normal((64,16))
target = np.maximum(x @ rng.standard_normal((16,8)),0) @ rng.standard_normal((8,4))/4
initial = (rng.standard_normal((16,32))/4,rng.standard_normal((32,4))/np.sqrt(32))
for mode in ('float64','fp8_simulado'):
w1,w2 = (v.copy() for v in initial)
losses = []
def mm(a,b,fmt='e4m3'):
return a@b if mode == 'float64' else qdq(a,fmt)@qdq(b,'e4m3')
for step in range(200):
z = mm(x,w1); h = np.maximum(z,0); y = mm(h,w2)
dy = 2*(y-target)/target.size
dw2 = mm(h.T,dy); dh = mm(dy,w2.T,'e5m2')
dw1 = mm(x.T,dh*(z>0))
w1 -= .03*dw1; w2 -= .03*dw2
if step in (0,49,99,199): losses.append(float(np.mean((y-target)**2)))
print(mode,'pérdidas pasos 0, 49, 99 y 199:',np.round(losses,6))Why a short test does not demonstrate stability
Low-precision instabilities can appear after a prolonged run. Fishman et al. study outlier amplification associated with SwiGLU and propose Smooth-SwiGLU. Their study also quantizes both Adam moments; this does not imply that every FP8 Adam implementation is stable. Compare losses and norms, per-tensor saturations, gradients, and validation samples throughout training. A short curve verifies only that case.
Smooth-SwiGLU introduces a per-channel factor before quantization and compensates for it in the next projection. Without quantization, applying and undoing that scale leaves the composed function unchanged; with quantization, it changes values’ positions relative to the grid. The paper reports that a standard FP8 configuration diverged after 200 billion tokens, whereas its variant converged in the stated experiment. Duration, architecture, and hardware are part of that evidence: it has not been repeated here.
Kumar et al. fit empirical laws relating precision, size, data, and loss, interpreting some degradation as a reduction in effective parameter count. Their fit does not turn a reduction in bits into a fixed universal loss, and its training and inference conditions must remain explicit.
To see what losing useful range means, imagine a spike multiplies the maximum by 32 and the scale follows that maximum. The absolute threshold below which a value rounds to zero also increases by 32, five powers of two. This does not mean every normal value has lost five significand bits: floating point retains relative resolution per binade while it neither becomes subnormal nor saturates. Model quality loss depends on which values undergo the change and how it propagates, not merely on counting bits.
The FP4 training frontier requires even more care. NVIDIA studies NVFP4 with two-level scaling, random Hadamard transforms, two-dimensional scaling, and stochastic gradient rounding. The orthogonal transform distributes magnitudes before quantization but does not itself eliminate error. Quartet studies another recipe and kernels on Blackwell. Do not confuse these operations with post-training quantization for inference.
If is orthogonal, in exact arithmetic. Random rotation applied to both operands can spread an outlier across coordinates before quantization, but its computation has a cost and subsequent quantization still introduces error. Under its recipe the NVFP4 study uses transforms on weight-gradient inputs, local and global scales, and stochastic rounding to reduce bias; this does not mean all training components are FP4.
Local lab: conversion, matmul, and autograd
Save the “GPT PyTorch y cargadores” cell from m18-l12 as gpt_pytorch.py. This capture reproduces the figures’ values: the GPT is initialized from the seed and does not load a trained checkpoint. Capture uses CPU; the JSON file is optional for inspection. Histogram figures come from this particular run and may vary with the PyTorch version.
import os, json, torch
from pathlib import Path
scope = {}
exec(compile(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf-8'),
'gpt_pytorch.py','exec'),scope)
torch.manual_seed(21); torch.set_num_threads(1)
net = scope['TorchGPT'](vocab=128,context=128,width=128,layers=2,heads=4,dropout=0).eval()
captured = []
handle = net.blocks[0].mlp.fc.register_forward_hook(lambda module,args,output: captured.append(output.detach()))
ids = torch.randint(128,(1,128))
with torch.no_grad(): net(ids)
handle.remove()
values = captured[0].reshape(-1)[:4096].tolist()
Path('activacion-fp8.json').write_text(json.dumps(values),encoding='utf-8')
print('forma:',tuple(captured[0].shape),'muestras:',len(values),'máximo absoluto:',max(map(abs,values)))npm run lab and open the connection link.The next code checks conversion against an independent NumPy grid, measures emulated matmul and BF16 error against FP32, and tests the private torch._scaled_mm operator. If it fails on a GPU older than 8.9, it reports the limitation and uses an FP32 matmul to emulate training. On compatible hardware it must execute the native operator, and an error there propagates instead of being hidden. The private API, alignment restrictions, and support can change with PyTorch: check the version. On a compatible system, the loop compares BF16 and FP8 including scale calculation and conversion. It times with CUDA events after warm-up; do not treat an isolated number under shared load as a hardware property.
The FP8Linear layer stores input and weights, and uses E5M2 for the output gradient in backward. The example uses matrices with dimensions divisible by 16, GELU, and the same initial weights for a two-matrix MLP, with SGD and ten steps. Weights and updates remain FP32. This teaching recipe does not reproduce a GPT’s entire policy or guarantee large-scale convergence.
import numpy as np, torch
from torch.nn import functional as F
assert torch.cuda.is_available()
torch.manual_seed(21)
device = 'cuda'
capability = torch.cuda.get_device_capability()
print('GPU:',torch.cuda.get_device_name(),'capacidad:',capability,'PyTorch:',torch.__version__)
def fp8_grid(fmt):
mb,bias,last = (3,7,126) if fmt == 'e4m3' else (2,15,123)
out = []
for bits in range(last+1):
e,m = divmod(bits,1 << mb)
out.append((m/(1 << mb))*2.**(1-bias) if e == 0 else (1+m/(1 << mb))*2.**(e-bias))
return np.asarray(out)
def np_quant(x,fmt):
vals=fp8_grid(fmt); mag=np.abs(x)
hi=np.minimum(np.searchsorted(vals,mag),len(vals)-1); lo=np.maximum(hi-1,0)
dl,dh=mag-vals[lo],vals[hi]-mag
idx=np.where((dh<dl)|((dh==dl)&(hi%2==0)),hi,lo)
return np.copysign(vals[idx],x)
# La búsqueda que alimenta el botón de la figura usa la muestra capturada antes.
sample=np.asarray(values,dtype=np.float64)
for fmt in ('e4m3','e5m2'):
scores=[]
for i in range(161):
log_scale=-5+i*.025; scale=10.**log_scale
scores.append((float(np.mean((scale*np_quant(sample/scale,fmt)-sample)**2)),log_scale))
error,log_scale=min(scores)
print('mejor escala de la rejilla',fmt,'log10:',round(log_scale,3),'MSE:',error)
def prepare(x,fmt):
dtype,maximum = ((torch.float8_e4m3fn,448.) if fmt == 'e4m3' else (torch.float8_e5m2,57344.))
scale = x.detach().float().abs().amax().clamp_min(torch.finfo(torch.float32).tiny)/maximum
return (x.float()/scale).clamp(-maximum,maximum).to(dtype),scale
def native_mm(a,b,afmt='e4m3',bfmt='e4m3'):
qa,sa=prepare(a,afmt); qb,sb=prepare(b,bfmt)
qa=qa.contiguous(); qb=qb.T.contiguous().T
return torch._scaled_mm(qa,qb,scale_a=sa,scale_b=sb,out_dtype=torch.bfloat16)
def emulated_mm(a,b,afmt='e4m3',bfmt='e4m3'):
qa,sa=prepare(a,afmt); qb,sb=prepare(b,bfmt)
return ((qa.float()@qb.float())*(sa*sb)).bfloat16()
a=torch.randn(256,256,device=device); b=torch.randn(256,256,device=device)
for fmt,dtype,maximum in [('e4m3',torch.float8_e4m3fn,448.),('e5m2',torch.float8_e5m2,57344.)]:
raw=torch.linspace(-maximum,maximum,100000,device=device,dtype=torch.float32)
gpu=raw.to(dtype).float().cpu().numpy(); cpu=np_quant(raw.cpu().numpy(),fmt)
error=float(np.max(np.abs(cpu-gpu)))
print(fmt,'error máximo de conversión:',error)
assert error == 0
torch.backends.cuda.matmul.allow_tf32=False
reference=a@b; emulated=emulated_mm(a,b)
bf=(a.bfloat16()@b.bfloat16()).float()
def rel(v): return float(torch.linalg.vector_norm(v.float()-reference)/torch.linalg.vector_norm(reference))
print('error relativo BF16:',rel(bf),'FP8 emulado:',rel(emulated))
try:
probe=native_mm(a,b)
except RuntimeError as exc:
print('scaled_mm nativa no disponible:',str(exc).splitlines()[0])
if capability >= (8,9): raise
mm=emulated_mm; label='FP8 emulado con matmul FP32'
else:
print('error relativo FP8 nativo:',rel(probe))
mm=native_mm; label='FP8 nativo'
class FP8Linear(torch.autograd.Function):
@staticmethod
def forward(ctx,x,w):
ctx.save_for_backward(x,w)
return mm(x,w)
@staticmethod
def backward(ctx,dy):
x,w=ctx.saved_tensors
dx=mm(dy,w.T,'e5m2','e4m3').to(x.dtype)
dw=mm(x.T,dy,'e4m3','e5m2').to(w.dtype)
return dx,dw
def bench(fn):
for _ in range(3): fn()
start=torch.cuda.Event(enable_timing=True); end=torch.cuda.Event(enable_timing=True)
start.record()
for _ in range(10): fn()
end.record(); end.synchronize()
return start.elapsed_time(end)/10
for n in (256,512,1024):
x=torch.randn(n,n,device=device); w=torch.randn(n,n,device=device)
x16=x.bfloat16(); w16=w.bfloat16()
t16=bench(lambda:x16@w16)
print('n:',n,'BF16 TFLOP/s:',2*n**3/(t16*1e9))
if mm is native_mm:
t8=bench(lambda:native_mm(x,w))
print('FP8 nativo con conversión TFLOP/s:',2*n**3/(t8*1e9))
x=torch.randn(128,256,device=device,dtype=torch.bfloat16)
target=torch.randn(128,256,device=device)
initial=(torch.randn(256,1024,device=device)*.02,torch.randn(1024,256,device=device)*.02)
for mode in ('BF16',label):
w1,w2=[torch.nn.Parameter(v.clone()) for v in initial]
opt=torch.optim.SGD([w1,w2],lr=.02); losses=[]
for step in range(10):
opt.zero_grad(set_to_none=True)
h=FP8Linear.apply(x,w1) if mode == label else x@w1.bfloat16()
h=F.gelu(h)
y=FP8Linear.apply(h,w2) if mode == label else h@w2.bfloat16()
loss=(y.float()-target).square().mean(); loss.backward(); opt.step()
assert torch.isfinite(loss) and all(torch.isfinite(w.grad).all() for w in (w1,w2))
losses.append(float(loss.detach()))
print(mode,'pérdidas inicial y final:',losses[0],losses[-1])npm run lab and open the connection link.On an RTX 3060 with PyTorch 2.11.0+cu128, both formats matched the NumPy grid over 100000 values and _scaled_mm reported that the device is unsupported. In one run of the matmul control, relative Frobenius error was approximately 0.00288 for BF16 and 0.03720 for FP8 emulation, with TF32 disabled. Emulated and BF16 training finished ten steps with similar losses, but this does not test the native branch or long-run behavior. The native branch and its timings must be run and verified on compatible hardware.
Exercises
Step 1 of 4. What changes when multiplying by 2 to an integer power?
quantize_mx(x, block=32, fmt='e4m3') for a finite vector. Return (q, scales), where q contains signed magnitudes representable in the format and each positive scale is a power of two with exponent between -127 and 127. Per block use the smallest power of two avoiding saturation if one exists, round to nearest with ties to even, and saturate to finite values if maximum E8M0 is insufficient. An all-zero block uses scale 1.import numpy as np
def quantize_mx(x, block=32, fmt='e4m3'):
pass