import random5.5 Numerical Formats
Every tensor in our models so far has used 32-bit floating point (fp32), without questioning whether neural networks actually need that many bits. Cutting the bit width in half pays off immediately in both memory and throughput: the 8-billion-parameter model running through this chapter takes 32 GB for its weights in 32-bit precision but only 16 GB in 16-bit, and modern GPUs execute 16-bit matrix multiplications at least twice as fast as 32-bit ones. Can we train in 16 bits and still recover the same model?
Not naively. Sixteen-bit formats are noticeably coarser, opening the door to two silent failure modes that raise no runtime error. In fp16, \(300^2\) already overflows to inf, flooding training with inf and NaN values. In bf16, adding \(0.001\) to a weight of \(1\) rounds right back to \(1\), silently stalling learning even while gradients look healthy.
This section shows how to train reliably in 16 bits while avoiding both traps. Every tensor carries a dtype (its numerical format), and every format trades off dynamic range (how large or small representable numbers can be) against precision (how finely adjacent numbers are spaced). Mixed-precision training keeps an fp32 master copy of the weights so tiny gradient updates accumulate faithfully, while executing expensive matrix multiplications and storing activations in 16 bits, paired with loss scaling when using fp16 so small gradients do not underflow to zero. Whereas Section 5.2 counted bytes per parameter, here we control bytes per number. The second subsection (dtype promotion and model casting) is practical reference material you can skim quickly. All examples run on CPU or GPU; actual 16-bit speedups require GPU matrix units, which we measure in Section 5.7.
import ml_dtypes
import randomimport random5.5.1 Floating-Point Formats
5.5.1.1 Range and Precision
Simply squaring 300 in both 16-bit formats reveals the two distinct ways low precision can bite (300 is hardly exotic inside a neural network, where an unnormalized logit or intermediate variance sum can easily reach that size):
x = torch.tensor(300.0)
x.to(torch.float16)**2, x.to(torch.bfloat16)**2(tensor(inf, dtype=torch.float16), tensor(90112., dtype=torch.bfloat16))
x = tf.constant(300.0)
tf.cast(x, tf.float16)**2, tf.cast(x, tf.bfloat16)**2(<tf.Tensor: shape=(), dtype=float16, numpy=inf>,
<tf.Tensor: shape=(), dtype=bfloat16, numpy=90112.0>)
x = jnp.array(300.0)
x.astype(jnp.float16)**2, x.astype(jnp.bfloat16)**2(Array(inf, dtype=float16), Array(90112, dtype=bfloat16))
x = mnp.array(300.0)
x.astype('float16')**2array(inf, dtype=float16)
MXNet supports bf16 only in part and cannot train bf16 weights, so here we work in fp16 and square 300 in fp16 alone. In bf16 the result would be 90112.
In fp16 (half precision), \(300^2\) overflows straight to inf because its largest finite value is just 65504. In bf16 (brain floating point), the result stays finite (90112 instead of 90000), yet already incurs rounding error in the third significant digit. Both formats fit in 16 bits; they simply partition those bits differently. Any normal floating-point number stores a sign bit \(s\), an exponent \(e\), and a \(t\)-bit mantissa encoding a fraction \(f \in [0, 1)\), representing
\[x = (-1)^s \cdot 2^{e} \cdot (1 + f). \tag{5.5.1}\]
Exponent bits govern dynamic range (the largest and smallest magnitudes \(|x|\) the format can represent), while mantissa bits govern relative precision: adjacent numbers between \(1\) and \(2\) sit \(2^{-t}\) apart, and between \(2^e\) and \(2^{e+1}\) they sit \(2^{e-t}\) apart, maintaining uniform relative spacing across scales. The three formats we work with allocate their bits as follows:
| format | sign | exponent | mantissa |
|---|---|---|---|
| fp32 | 1 | 8 | 23 |
| bf16 | 1 | 8 | 7 |
| fp16 | 1 | 5 | 10 |
Notice the trade-off immediately. bf16 preserves all 8 exponent bits of fp32 while trimming the mantissa down to 7 bits, delivering fp32’s full dynamic range at coarser resolution. fp16 does the opposite, retaining 10 mantissa bits but only 5 exponent bits: finer local steps, far narrower range. We can check both outputs above by hand: with 5 exponent bits, \(e\) spans \([-14, 15]\), capping fp16 at \(2^{15}(2 - 2^{-10}) = 65504\). With 7 mantissa bits, bf16 values between \(2^{16}\) and \(2^{17}\) are spaced by \(2^9 = 512\), so 90000 falls between \(175 \cdot 512 = 89600\) and \(176 \cdot 512 = 90112\) and rounds to the closer value, 90112.
Figure 5.5.1 visualizes these bit budgets side by side (see Section 35.8 for a deeper treatment of IEEE floating-point arithmetic).
We can query each format’s exact numerical limits via finfo, focusing on three fields: max (largest finite value), tiny (smallest positive normal value), and eps (the gap \(2^{-t}\) just above 1). Below tiny, where the exponent hits its floor, the format degrades gracefully through evenly spaced subnormal numbers down to zero: in fp16 these are multiples of \(2^{-24}\), so a value near \(3 \times 10^{-5}\) still preserves 9 significant bits, whereas one near \(10^{-7}\) retains only a single bit.
for dtype in (torch.float32, torch.bfloat16, torch.float16):
fi = torch.finfo(dtype)
print(f'{str(dtype):15} max {fi.max:10.3e} tiny {fi.tiny:9.3e}'
f' eps {fi.eps:8.3e}')torch.float32 max 3.403e+38 tiny 1.175e-38 eps 1.192e-07
torch.bfloat16 max 3.390e+38 tiny 1.175e-38 eps 7.812e-03
torch.float16 max 6.550e+04 tiny 6.104e-05 eps 9.766e-04
for dtype in (tf.float32, tf.bfloat16, tf.float16):
fi = ml_dtypes.finfo(dtype.as_numpy_dtype)
print(f'{dtype.name:10} max {float(fi.max):10.3e}'
f' tiny {float(fi.tiny):9.3e} eps {float(fi.eps):8.3e}')float32 max 3.403e+38 tiny 1.175e-38 eps 1.192e-07
bfloat16 max 3.390e+38 tiny 1.175e-38 eps 7.812e-03
float16 max 6.550e+04 tiny 6.104e-05 eps 9.766e-04
for dtype in (jnp.float32, jnp.bfloat16, jnp.float16):
fi = jnp.finfo(dtype)
print(f'{fi.dtype.name:10} max {float(fi.max):10.3e}'
f' tiny {float(fi.tiny):9.3e} eps {float(fi.eps):8.3e}')float32 max 3.403e+38 tiny 1.175e-38 eps 1.192e-07
bfloat16 max 3.390e+38 tiny 1.175e-38 eps 7.812e-03
float16 max 6.550e+04 tiny 6.104e-05 eps 9.766e-04
for dtype in ('float32', 'float16'):
fi = mnp.finfo(dtype)
print(f'{dtype:10} max {fi.max:10.3e} tiny {fi.smallest_normal:9.3e}'
f' eps {fi.eps:8.3e}')float32 max 3.403e+38 tiny 1.175e-38 eps 1.192e-07
float16 max 6.550e+04 tiny 6.104e-05 eps 9.766e-04
TensorFlow has no finfo of its own for bf16. The numbers come from ml_dtypes, the small package that defines the bf16 type TensorFlow uses.
mnp.finfo calls the smallest normal value smallest_normal rather than tiny. For bf16, which the cell leaves out, the three numbers are max \(3.39 \times 10^{38}\), tiny \(1.18 \times 10^{-38}\), and eps \(2^{-7} \approx 0.0078\).
Because bf16 shares fp32’s 8-bit exponent, it matches fp32’s tiny and nearly matches its max, while its eps of \(0.0078\) gives two to three decimal digits of precision. fp16 resolves three to four decimal digits, but overflows above 65504, slips into subnormals below \(6.1 \times 10^{-5}\), and cannot represent any positive value below \(2^{-24} \approx 6.0 \times 10^{-8}\). Which shortage hurts deep learning more? Activations and gradients routinely span many orders of magnitude; running out of range catastrophically turns numbers into inf or zero, whereas slightly coarser precision merely introduces mild rounding noise. That is why bf16 has become the default 16-bit training format on modern hardware, leaving fp16 primarily for older GPUs and inference.
5.5.1.2 Rounding of Small Updates
Where bf16’s coarse spacing does hurt is during parameter updates. A single gradient descent step shifts a weight by \(\eta g\), often \(10^{-3}\) or less of the weight’s magnitude. Under round-to-nearest, any step smaller than half the local spacing vanishes completely. Below we add \(10^{-3}\) and \(10^{-4}\) to a weight of \(1\) in each format:
w = torch.tensor(1.0)
for dtype in (torch.float32, torch.bfloat16, torch.float16):
print(f'{str(dtype):14}: {float(w.to(dtype) + 1e-3):.7f}, '
f'{float(w.to(dtype) + 1e-4):.7f}')torch.float32 : 1.0010000, 1.0001000
torch.bfloat16: 1.0000000, 1.0000000
torch.float16 : 1.0009766, 1.0000000
w = tf.constant(1.0)
for dtype in (tf.float32, tf.bfloat16, tf.float16):
print(f'{dtype.name:8}: {float(tf.cast(w, dtype) + 1e-3):.7f}, '
f'{float(tf.cast(w, dtype) + 1e-4):.7f}')float32 : 1.0010000, 1.0001000
bfloat16: 1.0000000, 1.0000000
float16 : 1.0009766, 1.0000000
w = jnp.array(1.0)
for dtype in (jnp.float32, jnp.bfloat16, jnp.float16):
print(f'{jnp.dtype(dtype).name:8}: {float(w.astype(dtype) + 1e-3):.7f}, '
f'{float(w.astype(dtype) + 1e-4):.7f}')float32 : 1.0010000, 1.0001000
bfloat16: 1.0000000, 1.0000000
float16 : 1.0009766, 1.0000000
w = mnp.array(1.0)
for dtype in ('float32', 'float16'):
print(f'{dtype:8}: {float(w.astype(dtype) + 1e-3):.7f}, '
f'{float(w.astype(dtype) + 1e-4):.7f}')float32 : 1.0010000, 1.0001000
float16 : 1.0009766, 1.0000000
For bf16, which the cell leaves out, both sums come out as 1.0000000.
In fp32, both increments register cleanly. In bf16, whose spacing near 1 is \(2^{-7} \approx 0.0078\), both round right back to 1, leaving the weight completely frozen. In fp16 (spacing \(2^{-10} \approx 0.00098\)), the \(10^{-3}\) step survives (rounded to one grid step) while \(10^{-4}\) disappears. Figure 5.5.2 draws both grids to one scale: an update registers only if it carries the weight more than half a grid spacing away. Storing weights directly in 16 bits can therefore stall optimization even when every gradient is accurate, which is why training keeps master weights in fp32.
5.5.2 Dtype Promotion and Model Casting
5.5.2.1 Promotion
What dtype results when an expression combines mismatched operands? We test adding an fp16 tensor to an fp32 tensor, a Python float, and an integer tensor:
x16 = torch.ones(3, dtype=torch.float16)
x32 = torch.ones(3, dtype=torch.float32)
(x16 + x32).dtype, (x16 + 1.0).dtype, (x16 + torch.arange(3)).dtype(torch.float32, torch.float16, torch.float16)
x16 = tf.ones(3, dtype=tf.float16)
x32 = tf.ones(3, dtype=tf.float32)
try:
x16 + x32
except tf.errors.InvalidArgumentError as e:
print(e.message.split(' but ')[0])
(x16 + 1.0).dtypecannot compute AddV2 as input #1(zero-based) was expected to be a half tensor
tf.float16
x16 = jnp.ones(3, dtype=jnp.float16)
x32 = jnp.ones(3, dtype=jnp.float32)
(x16 + x32).dtype, (x16 + 1.0).dtype, (x16 + jnp.arange(3)).dtype(dtype('float32'), dtype('float16'), dtype('float16'))
x16 = mnp.ones(3, dtype='float16')
x32 = mnp.ones(3, dtype='float32')
((x16 + x32).dtype, (x16 + 1.0).dtype,
mnp.result_type(x16, mnp.ones(3, dtype='int32')))(dtype('float32'), dtype('float16'), dtype('float16'))
Combining two float tensors promotes to the wider format (and fp16 + bf16 promotes to fp32), so a single stray fp32 tensor silently promotes an entire downstream 16-bit computation to fp32. Python float literals and integer tensors do not promote float tensors.
TensorFlow never promotes across tensor dtypes: combining fp16 and fp32 raises an InvalidArgumentError unless explicitly converted with tf.cast.
Combining two float tensors promotes to the wider format (and fp16 + bf16 promotes to fp32), so a single stray fp32 tensor silently promotes an entire downstream 16-bit computation to fp32. Python float literals and integer tensors do not promote float tensors.
Combining two float tensors promotes to the wider format (and fp16 + bf16 promotes to fp32), so a single stray fp32 tensor silently promotes an entire downstream 16-bit computation to fp32. Python float literals and integer tensors do not promote float tensors.
5.5.2.2 Casting a Model
Since parameters are just tensors, we can cast an entire model to 16 bits. Throughout this section we use our Fashion-MNIST MLP from Section 4.2: 784 inputs, a 256-unit ReLU hidden layer, and 10 outputs, with \(\mathcal{N}(0, 0.01^2)\) weights and zero biases (203,530 parameters occupying 814,120 bytes in fp32).
def mlp():
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 256), nn.ReLU(),
nn.Linear(256, 10))
for layer in net[1], net[3]:
nn.init.normal_(layer.weight, std=0.01)
nn.init.zeros_(layer.bias)
return net
def param_bytes(net):
return sum(p.numel() * p.element_size() for p in net.parameters())
net = mlp()
param_bytes(net)814120
def mlp(dtype=None):
normal = tf.keras.initializers.RandomNormal # one instance per layer
return tf.keras.Sequential([
tf.keras.layers.Flatten(dtype=dtype),
tf.keras.layers.Dense(256, activation='relu', dtype=dtype,
kernel_initializer=normal(stddev=0.01)),
tf.keras.layers.Dense(10, dtype=dtype,
kernel_initializer=normal(stddev=0.01))])
def param_bytes(net):
return sum(w.shape.num_elements() * tf.as_dtype(w.dtype).size
for w in net.weights)
net = mlp()
net(tf.zeros((1, 28, 28, 1))) # The first call creates the weights
param_bytes(net)814120
def mlp(rngs, dtype=None):
normal = nnx.initializers.normal(0.01)
return nnx.Sequential(
lambda x: x.reshape((x.shape[0], -1)),
nnx.Linear(784, 256, kernel_init=normal, dtype=dtype, rngs=rngs),
nnx.relu,
nnx.Linear(256, 10, kernel_init=normal, dtype=dtype, rngs=rngs))
def param_bytes(model):
return sum(p.size * p.dtype.itemsize
for _, p in nnx.state(model, nnx.Param).flat_state())
net = mlp(nnx.Rngs(d2l.get_key()))
param_bytes(net)814120
def mlp():
net = nn.Sequential()
net.add(nn.Dense(256, activation='relu', in_units=784),
nn.Dense(10, in_units=256))
net.initialize(init.Normal(sigma=0.01))
return net
def param_bytes(net):
return sum(p.data().size * p.data().dtype.itemsize
for p in net.collect_params().values())
net = mlp()
param_bytes(net)814120
net.to(dtype) (or net.bfloat16()) casts all parameters and buffers; layers reject inputs whose dtype does not match their weights.
Passing dtype='bfloat16' at construction sets both variable_dtype and compute_dtype on each Keras layer, automatically casting inputs on call.
Flax NNX layers separate storage (param_dtype, default fp32) from compute (dtype). Mapping .astype(jnp.bfloat16) over nnx.Param casts stored weights.
net.cast('float16') casts all parameters in the block tree; inputs must be cast to match.
net = net.bfloat16()
X = torch.randn(8, 1, 28, 28)
try:
net(X)
except RuntimeError as e:
print(e)
print(net(X.bfloat16()).dtype, param_bytes(net))mat1 and mat2 must have the same dtype, but got Float and BFloat16
torch.bfloat16 407060
net16 = mlp(dtype='bfloat16')
X = tf.random.normal((8, 28, 28, 1))
print(net16(X).dtype, param_bytes(net16))<dtype: 'bfloat16'> 407060
def cast(model, dtype):
"""Return the model with its parameters stored in dtype."""
graph, params = nnx.split(model, nnx.Param)
return nnx.merge(graph, jax.tree.map(lambda p: p.astype(dtype), params))
net16 = cast(net, jnp.bfloat16)
X = jax.random.normal(d2l.get_key(), (8, 28, 28, 1))
print(net16(X).dtype, param_bytes(net16))
print(net16(X.astype(jnp.bfloat16)).dtype)float32 407060
bfloat16
net.cast('float16')
X = mnp.random.normal(size=(8, 1, 28, 28))
print(net(X.astype('float16')).dtype, param_bytes(net))float16 407060
Casting halves parameter memory immediately, though frameworks differ in whether a 16-bit model casts an fp32 input automatically or rejects the dtype mismatch.
For inference, casting a trained model to 16 bits immediately halves its weight footprint (subject to verifying that task accuracy holds up). For training, however, pure 16-bit weights run straight into the small-update rounding trap we just saw, as we confirm empirically below.
5.5.3 Mixed-Precision Training
5.5.3.1 Master Weights and 16-Bit Compute
We appear to face a dilemma: reliable weight updates demand 32-bit storage, yet hardware speedups live in 16-bit arithmetic. Mixed-precision training (Micikevicius et al. 2018) resolves this tension by decoupling parameter storage from computation. We keep fp32 master weights so every small update accumulates cleanly, cast them to 16 bits for the compute-heavy matrix multiplications and activations of the forward and backward passes, and keep sensitive reductions such as the loss in fp32. Figure 5.5.3 summarizes a single training step.
torch.autocast leaves parameters in fp32 and automatically casts eligible ops (matrix multiplies, convolutions) to 16 bits while keeping reductions and losses in fp32.
Constructing a model under the 'mixed_bfloat16' global policy gives every layer fp32 variable_dtype and bf16 compute_dtype.
Constructing NNX layers with dtype=jnp.bfloat16 (leaving param_dtype at its fp32 default) stores fp32 master weights and computes forward passes in bf16.
We cast the network to fp16 (net.cast('float16')) and pass multi_precision=True to the optimizer so it maintains fp32 master weights internally.
net = mlp()
with torch.autocast('cpu', dtype=torch.bfloat16):
Y = net(X)
Y.dtype, net[1].weight.dtype(torch.bfloat16, torch.float32)
tf.keras.mixed_precision.set_global_policy('mixed_bfloat16')
net = mlp()
tf.keras.mixed_precision.set_global_policy('float32')
Y = net(X)
Y.dtype, net.layers[1].kernel.dtype(tf.bfloat16, 'float32')
net = mlp(nnx.Rngs(d2l.get_key()), dtype=jnp.bfloat16)
net(X).dtype, jax.tree.leaves(nnx.state(net, nnx.Param))[0].dtype(dtype(bfloat16), dtype('float32'))
net = mlp()
net.cast('float16')
trainer = gluon.Trainer(net.collect_params(), 'sgd',
{'learning_rate': 0.1, 'multi_precision': True})
loss = gluon.loss.SoftmaxCrossEntropyLoss()
with autograd.record():
l = loss(net(X.astype('float16')), mnp.zeros(8)).mean()
l.backward()
trainer.step(1)
master = trainer._updaters[0].states[0][0] # The fp32 master copy
net[0].weight.data().dtype, master.dtype(dtype('float16'), dtype('float32'))
5.5.3.2 Training in fp32 and in 16 Bits
How much does 16-bit arithmetic affect optimization, and what goes wrong when we drop the fp32 master copy? Below we train our MLP three times with plain SGD on Fashion-MNIST minibatches of 256 images: full fp32, pure bf16 weights (with no fp32 master copy), and mixed precision. All three runs start from identical random weights and consume the exact same minibatches in the same order.
Notice the learning rate: we set \(\eta = 0.01\) (one-tenth the rate used in Section 4.2) and run for 1000 steps (about four epochs). Our rounding analysis explains why \(\eta\) matters so dramatically: an update \(\eta g\) disappears whenever it falls below half the local bf16 grid spacing, so a smaller learning rate loses more updates. A small rate is no artificial setting. Every real training run reaches one once its learning rate has decayed. Just before training, we will measure how much is lost at each of the two rates.
data = d2l.FashionMNIST(batch_size=256)
batches = list(torch.utils.data.DataLoader(data.train, batch_size=256,
drop_last=True)) # One epoch
val_batch = next(iter(torch.utils.data.DataLoader(data.val, batch_size=1024)))data = d2l.FashionMNIST(batch_size=256)
images, labels = data.train
batches = [(tf.constant(images[k:k+256, :, :, None], tf.float32) / 255,
tf.constant(labels[k:k+256], tf.int32))
for k in range(0, len(images) - 255, 256)] # One epoch
val_images, val_labels = data.val
val_batch = (tf.constant(val_images[:1024, :, :, None], tf.float32) / 255,
tf.constant(val_labels[:1024], tf.int32))data = d2l.FashionMNIST(batch_size=256)
images, labels = data.train
batches = [(jnp.asarray(images[k:k+256], jnp.float32) / 255,
jnp.asarray(labels[k:k+256], jnp.int32))
for k in range(0, len(images) - 255, 256)] # One epoch
val_images, val_labels = data.val
val_batch = (jnp.asarray(val_images[:1024, :, :, None], jnp.float32) / 255,
jnp.asarray(val_labels[:1024], jnp.int32))data = d2l.FashionMNIST(batch_size=256)
batches = list(gluon.data.DataLoader(data.train, batch_size=256,
last_batch='discard')) # One epoch
val_batch = next(iter(gluon.data.DataLoader(data.val, batch_size=1024)))With the training minibatches and a 1,024-image validation slice preloaded in memory, train runs \(1{,}000\) SGD steps at \(\eta = 0.01\) and returns the per-step losses alongside final validation accuracy:
def train(net, mixed=False, num_steps=1000):
dtype = next(net.parameters()).dtype # The inputs follow the weights
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)
losses = []
for step in range(num_steps):
X, y = batches[step % len(batches)]
with torch.autocast('cpu', dtype=torch.bfloat16, enabled=mixed):
loss = F.cross_entropy(net(X.to(dtype)).float(), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.detach())
Xv, yv = val_batch
with torch.no_grad():
accuracy = (net(Xv.to(dtype)).argmax(1) == yv).float().mean().item()
return torch.stack(losses).tolist(), accuracydef train(net, num_steps=1000):
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
losses = []
for step in range(num_steps):
X, y = batches[step % len(batches)]
with tf.GradientTape() as tape:
logits = tf.cast(net(X), tf.float32)
loss = tf.reduce_mean(
tf.keras.losses.sparse_categorical_crossentropy(
y, logits, from_logits=True))
grads = tape.gradient(loss, net.trainable_variables)
optimizer.apply_gradients(zip(grads, net.trainable_variables))
losses.append(loss)
Xv, yv = val_batch
y_hat = tf.argmax(net(Xv), axis=1, output_type=yv.dtype)
accuracy = float(tf.reduce_mean(tf.cast(y_hat == yv, tf.float32)))
return [float(l) for l in losses], accuracy@nnx.jit
def train_step(model, optimizer, X, y):
def loss_fn(model):
logits = model(X).astype(jnp.float32)
return optax.softmax_cross_entropy_with_integer_labels(
logits, y).mean()
loss, grads = nnx.value_and_grad(loss_fn)(model)
optimizer.update(model, grads)
return loss
def train(net, num_steps=1000):
optimizer = nnx.Optimizer(net, optax.sgd(0.01), wrt=nnx.Param)
losses = [train_step(net, optimizer, *batches[step % len(batches)])
for step in range(num_steps)]
Xv, yv = val_batch
accuracy = float((net(Xv).argmax(1) == yv).mean())
return [float(l) for l in losses], accuracydef bf16_round(w):
"""Round to the 8 significant bits of bf16, computed in NumPy."""
m, e = np.frexp(w.asnumpy()) # w = m * 2**e with 1/2 <= |m| < 1
return mnp.array(np.ldexp(np.round(m * 2**8) / 2**8, e))
def train(net, store=None, num_steps=1000):
dtype = net[0].weight.data().dtype
trainer = gluon.Trainer(net.collect_params(), 'sgd', {
'learning_rate': 0.01, 'multi_precision': dtype == np.float16})
loss = gluon.loss.SoftmaxCrossEntropyLoss()
losses = []
for step in range(num_steps):
X, y = batches[step % len(batches)]
with autograd.record():
logits = net(X.astype(dtype)).astype('float32')
l = loss(logits, y).mean()
l.backward()
trainer.step(1)
if store: # Round every updated weight to the storage format
for p in net.collect_params().values():
p.set_data(store(p.data()))
losses.append(l)
Xv, yv = val_batch
accuracy = float((net(Xv.astype(dtype)).argmax(axis=1) == yv).mean())
return [float(l) for l in losses], accuracyOne implementation detail in train is a good systems habit independent of precision: we keep per-step loss tensors on-device during the loop and convert them to Python floats once at the end, avoiding a CPU–GPU synchronization stall on every single step (Section 5.7).
Because MXNet cannot train bf16 weights directly, bf16_round rounds fp32 weights to bf16’s 7-bit mantissa after each step, while the mixed-precision run uses fp16 with multi_precision=True.
Before training, we check the rounding argument on the first minibatch. Of the nonzero first-layer updates \(\eta g\) at initialization, what fraction would bf16 storage round away at \(\eta = 0.01\) and at \(\eta = 0.1\), and what share of the total update magnitude do the lost updates carry?
net = mlp()
X, y = batches[0]
F.cross_entropy(net(X), y).backward()
w, g = net[1].weight.detach(), net[1].weight.grad
w16, moved = w.bfloat16(), g != 0 # Count only the nonzero updates
for lr in (0.01, 0.1):
lost = ((w16.float() - lr * g).bfloat16() == w16) & moved
share = lost.sum() / moved.sum()
mass = g[lost].abs().sum() / g.abs().sum()
print(f'lr {lr}: {share:.0%} of updates rounded away, '
f'{mass:.0%} of the update mass')lr 0.01: 92% of updates rounded away, 80% of the update mass
lr 0.1: 52% of updates rounded away, 16% of the update mass
net = mlp()
X, y = batches[0]
with tf.GradientTape() as tape:
loss = tf.reduce_mean(tf.keras.losses.sparse_categorical_crossentropy(
y, net(X), from_logits=True))
g = tape.gradient(loss, net.layers[1].kernel)
w16 = tf.cast(net.layers[1].kernel, tf.bfloat16)
moved = g != 0 # Count only the nonzero updates
for lr in (0.01, 0.1):
new = tf.cast(tf.cast(w16, tf.float32) - lr * g, tf.bfloat16)
lost = (new == w16) & moved
share = tf.reduce_sum(tf.cast(lost, tf.float32)) / tf.reduce_sum(
tf.cast(moved, tf.float32))
mass = tf.reduce_sum(tf.abs(g[lost])) / tf.reduce_sum(tf.abs(g))
print(f'lr {lr}: {float(share):.0%} of updates rounded away, '
f'{float(mass):.0%} of the update mass')lr 0.01: 91% of updates rounded away, 78% of the update mass
lr 0.1: 51% of updates rounded away, 14% of the update mass
net = mlp(nnx.Rngs(d2l.get_key()))
X, y = batches[0]
def loss_fn(model):
return optax.softmax_cross_entropy_with_integer_labels(
model(X), y).mean()
g = nnx.grad(loss_fn)(net)['layers'][1]['kernel'][...]
w16 = net.layers[1].kernel[...].astype(jnp.bfloat16)
moved = g != 0 # Count only the nonzero updates
for lr in (0.01, 0.1):
new = (w16.astype(jnp.float32) - lr * g).astype(jnp.bfloat16)
lost = (new == w16) & moved
share = float(lost.sum() / moved.sum())
mass = float(jnp.abs(g[lost]).sum() / jnp.abs(g).sum())
print(f'lr {lr}: {share:.0%} of updates rounded away, '
f'{mass:.0%} of the update mass')lr 0.01: 91% of updates rounded away, 77% of the update mass
lr 0.1: 50% of updates rounded away, 14% of the update mass
net = mlp()
X, y = batches[0]
with autograd.record():
l = gluon.loss.SoftmaxCrossEntropyLoss()(net(X), y).mean()
l.backward()
w, g = net[0].weight.data(), net[0].weight.grad()
w16, moved = bf16_round(w), g != 0 # Count only the nonzero updates
for lr in (0.01, 0.1):
lost = (bf16_round(w16 - lr * g) == w16) & moved
share = float(lost.sum() / moved.sum())
mass = float(mnp.abs(g[lost]).sum() / mnp.abs(g).sum())
print(f'lr {lr}: {share:.0%} of updates rounded away, '
f'{mass:.0%} of the update mass')lr 0.01: 92% of updates rounded away, 81% of the update mass
lr 0.1: 53% of updates rounded away, 16% of the update mass
At \(\eta = 0.01\) about nine in ten updates are rounded away, and they carry about four-fifths of the total update magnitude (the “mass” in the printout): most of the gradient step never reaches the weights. At \(\eta = 0.1\) about half of the updates are still lost, but they are the small ones and carry only about 15% of the magnitude. Most of the step then lands, and the failure stays hidden until the learning rate decays. Now we train all three variants at \(\eta = 0.01\).
def seeded_mlp(seed):
torch.manual_seed(seed) # The same seed gives the same initial weights
return mlp()
seed = random.randrange(2**31) # One random draw, shared by all runs
loss32, acc32 = train(seeded_mlp(seed))
loss_bf16, acc_bf16 = train(seeded_mlp(seed).bfloat16())
loss_mixed, acc_mixed = train(seeded_mlp(seed), mixed=True)
print(f'validation accuracy: fp32 {acc32:.3f}, bf16 weights {acc_bf16:.3f}, '
f'mixed {acc_mixed:.3f}')
d2l.plot(list(range(1, 1001)), [loss32, loss_bf16, loss_mixed], 'step',
'loss', legend=['fp32', 'bf16 weights', 'mixed precision'])validation accuracy: fp32 0.684, bf16 weights 0.639, mixed 0.685
def seeded_mlp(seed, policy):
tf.keras.utils.set_random_seed(seed) # The same initial weights
tf.keras.mixed_precision.set_global_policy(policy)
net = mlp()
tf.keras.mixed_precision.set_global_policy('float32')
return net
seed = random.randrange(2**31) # One random draw, shared by all runs
loss32, acc32 = train(seeded_mlp(seed, 'float32'))
loss_bf16, acc_bf16 = train(seeded_mlp(seed, 'bfloat16'))
loss_mixed, acc_mixed = train(seeded_mlp(seed, 'mixed_bfloat16'))
print(f'validation accuracy: fp32 {acc32:.3f}, bf16 weights {acc_bf16:.3f}, '
f'mixed {acc_mixed:.3f}')
d2l.plot(list(range(1, 1001)), [loss32, loss_bf16, loss_mixed], 'step',
'loss', legend=['fp32', 'bf16 weights', 'mixed precision'])validation accuracy: fp32 0.679, bf16 weights 0.633, mixed 0.676
key = d2l.get_key() # One random key, shared by all runs
loss32, acc32 = train(mlp(nnx.Rngs(key)))
loss_bf16, acc_bf16 = train(cast(mlp(nnx.Rngs(key), jnp.bfloat16),
jnp.bfloat16))
loss_mixed, acc_mixed = train(mlp(nnx.Rngs(key), jnp.bfloat16))
print(f'validation accuracy: fp32 {acc32:.3f}, bf16 weights {acc_bf16:.3f}, '
f'mixed {acc_mixed:.3f}')
d2l.plot(list(range(1, 1001)), [loss32, loss_bf16, loss_mixed], 'step',
'loss', legend=['fp32', 'bf16 weights', 'mixed precision'])validation accuracy: fp32 0.687, bf16 weights 0.646, mixed 0.688
def seeded_mlp(seed):
npx.random.seed(seed) # The same seed gives the same initial weights
return mlp()
seed = random.randrange(2**31) # One random draw, shared by all runs
loss32, acc32 = train(seeded_mlp(seed))
loss_bf16, acc_bf16 = train(seeded_mlp(seed), store=bf16_round)
net = seeded_mlp(seed)
net.cast('float16')
loss_mixed, acc_mixed = train(net)
print(f'validation accuracy: fp32 {acc32:.3f}, bf16 weights {acc_bf16:.3f}, '
f'mixed {acc_mixed:.3f}')
d2l.plot(list(range(1, 1001)), [loss32, loss_bf16, loss_mixed], 'step',
'loss', legend=['fp32', 'bf16 weights', 'mixed precision'])validation accuracy: fp32 0.677, bf16 weights 0.644, mixed 0.677
The fp32 and mixed-precision loss curves sit virtually on top of each other, with validation accuracies matching within about one percentage point. Pure bf16 weights, by contrast, lag behind within the first hundred steps: after 1000 steps, its loss has only reached about 1.15 versus 0.85, and validation accuracy trails at about 64% versus 68%. Just as our scalar experiment predicted, storing weights directly in bf16 rounds away most first-layer updates, whereas mixed precision applies them cleanly to fp32 master weights. None of the three runs is trained to convergence; what matters is the apples-to-apples comparison on identical data and step counts.
Notice two important caveats about what mixed precision does and does not buy us. First, we do not see a wall-clock speedup on a tiny CPU MLP; 16-bit speedups come from dedicated GPU tensor cores working on large matrix multiplications, which we benchmark in Section 5.7.2.1. Second, mixed precision does not shrink the static per-parameter memory floor from Section 5.2, because master weights and optimizer moments remain in fp32. That 16 GB footprint from the opening applies to an 8B model cast for inference; during training, mixed precision saves activation memory (halving stored 16-bit activations) and matrix-multiplication time.
In MXNet, the mixed-precision run above computed in fp16 rather than bf16 and trained without loss scaling. The next subsection measures what fp16 does to the gradients of this network and explains when scaling is needed.
5.5.3.3 Loss Scaling for fp16
With bf16, master weights complete the recipe. With fp16, however, its narrow exponent range creates a second hazard at the bottom end: small gradients underflow. Magnitudes below \(2^{-14} \approx 6.1 \times 10^{-5}\) drop into subnormals and shed significant bits, and anything below half the smallest subnormal (\(\approx 3 \times 10^{-8}\)) rounds straight to zero. A gradient of \(10^{-8}\) vanishes in fp16, yet multiplying it by \(2^{16}\) lifts it safely into normal range:
g = torch.tensor(1e-8)
g.half(), (g * 2**16).half()(tensor(0., dtype=torch.float16), tensor(0.0007, dtype=torch.float16))
g = tf.constant(1e-8)
tf.cast(g, tf.float16), tf.cast(g * 2**16, tf.float16)(<tf.Tensor: shape=(), dtype=float16, numpy=0.0>,
<tf.Tensor: shape=(), dtype=float16, numpy=0.0006551742553710938>)
g = jnp.array(1e-8)
g.astype(jnp.float16), (g * 2**16).astype(jnp.float16)(Array(0., dtype=float16), Array(0.000655, dtype=float16))
g = mnp.array(1e-8)
g.astype('float16'), (g * 2**16).astype('float16')(array(0., dtype=float16), array(0.000655, dtype=float16))
How common are tiny gradients in practice? Below we compute first-layer fp32 gradients for our MLP on the first minibatch and measure what fraction of nonzero entries fall into fp16’s subnormal or zero regimes, both unscaled and scaled by \(2^{16}\):
net = mlp()
X, y = batches[0]
F.cross_entropy(net(X), y).backward()
g = net[1].weight.grad.flatten()
g = g[g != 0]
for scale in (1, 2**16):
print(f'scale {scale:5}: '
f'{((g * scale).abs() < 2**-14).float().mean():.1%} subnormal, '
f'{((g * scale).half() == 0).float().mean():.2%} zero')scale 1: 32.5% subnormal, 0.21% zero
scale 65536: 0.0% subnormal, 0.00% zero
net = mlp()
X, y = batches[0]
with tf.GradientTape() as tape:
loss = tf.reduce_mean(tf.keras.losses.sparse_categorical_crossentropy(
y, net(X), from_logits=True))
g = tf.reshape(tape.gradient(loss, net.layers[1].kernel), -1)
g = g[g != 0]
for scale in (1, 2**16):
subnormal = tf.reduce_mean(tf.cast(tf.abs(g * scale) < 2**-14, tf.float32))
zero = tf.reduce_mean(tf.cast(tf.cast(g * scale, tf.float16) == 0,
tf.float32))
print(f'scale {scale:5}: {float(subnormal):.1%} subnormal, '
f'{float(zero):.2%} zero')scale 1: 33.3% subnormal, 0.22% zero
scale 65536: 0.0% subnormal, 0.00% zero
net = mlp(nnx.Rngs(d2l.get_key()))
X, y = batches[0]
def loss_fn(model):
return optax.softmax_cross_entropy_with_integer_labels(
model(X), y).mean()
g = nnx.grad(loss_fn)(net)['layers'][1]['kernel'][...].reshape(-1)
g = g[g != 0]
for scale in (1, 2**16):
print(f'scale {scale:5}: '
f'{float((jnp.abs(g * scale) < 2**-14).mean()):.1%} subnormal, '
f'{float(((g * scale).astype(jnp.float16) == 0).mean()):.2%} zero')scale 1: 31.9% subnormal, 0.14% zero
scale 65536: 0.0% subnormal, 0.00% zero
net = mlp()
X, y = batches[0]
with autograd.record():
l = gluon.loss.SoftmaxCrossEntropyLoss()(net(X), y).mean()
l.backward()
g = net[0].weight.grad().reshape(-1)
g = g[g != 0]
for scale in (1, 2**16):
print(f'scale {scale:5}: '
f'{float((mnp.abs(g * scale) < 2**-14).mean()):.1%} subnormal, '
f'{float(((g * scale).astype("float16") == 0).mean()):.2%} zero')scale 1: 32.9% subnormal, 0.17% zero
scale 65536: 0.0% subnormal, 0.00% zero
Roughly a third of the nonzero first-layer gradients land in fp16’s subnormal range, and about two in a thousand underflow all the way to zero. On this small MLP the impact is mild because only the tiniest entries vanish; in fact, it is hard to construct a toy model where fp16 fails outright and loss scaling saves it. Severe underflow hits large, deep models where losses average over many tokens or pixels and gradients attenuate across dozens of layers: Micikevicius et al. (2018) found that while several ImageNet classifiers trained fine in unscaled fp16, an object detector diverged and a large recurrent language model matched fp32 accuracy only once loss scaling was enabled.
Multiplying the gradients by \(2^{16}\) eliminates every subnormal entry while staying comfortably below fp16’s overflow ceiling of 65504. That is the essence of loss scaling: before the backward pass, multiply the scalar loss by a large constant \(S\). By linearity of differentiation, every intermediate gradient shifts up by \(S\) during backpropagation. Before stepping the optimizer, divide the gradients back down by \(S\) in fp32, where tiny values are represented faithfully, leaving the mathematical parameter update completely unchanged while keeping intermediate fp16 gradients out of the underflow zone.
Choosing \(S\) statically is brittle: too small and gradients underflow, too large and big gradients overflow to inf. Dynamic loss scaling automates the choice: start with a large \(S\), inspect the gradients on every step, and whenever an inf or NaN appears, skip the optimizer update and halve \(S\); after a streak of clean steps, double \(S\) to stay close to the top of fp16’s range. Figure 5.5.4 shows one step of this loop.
inf or NaN, the step is skipped and \(S\) is halved.
torch.amp.GradScaler automates dynamic loss scaling with fp16 autocast:
tf.keras.mixed_precision.LossScaleOptimizer wraps an optimizer to scale the loss and unscale/check gradients under 'mixed_float16':
Optax provides no automatic loss scaler (JAX primarily targets TPUs and modern GPUs with native bf16); if training in fp16, multiply the loss by \(S\) before backward and divide gradients by \(S\) before the optimizer update.
Gluon’s Trainer provides no automatic loss scaler; if training in fp16, multiply the loss by \(S\) before backward and divide gradients by \(S\) before the optimizer update.
net = mlp()
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
scaler = torch.amp.GradScaler('cpu')
for X, y in batches[:20]:
with torch.autocast('cpu', dtype=torch.float16):
loss = F.cross_entropy(net(X), y)
optimizer.zero_grad()
scaler.scale(loss).backward() # Gradients of S * loss
scaler.step(optimizer) # Divide by S, skip the step on inf/NaN
scaler.update() # Adjust S
print(f'loss {loss.item():.3f}, loss scale {scaler.get_scale():.0f}')loss 2.030, loss scale 65536
tf.keras.mixed_precision.set_global_policy('mixed_float16')
net = mlp()
tf.keras.mixed_precision.set_global_policy('float32')
optimizer = tf.keras.mixed_precision.LossScaleOptimizer(
tf.keras.optimizers.SGD(learning_rate=0.1))
for X, y in batches[:20]:
with tf.GradientTape() as tape:
loss = tf.reduce_mean(tf.keras.losses.sparse_categorical_crossentropy(
y, tf.cast(net(X), tf.float32), from_logits=True))
scaled_loss = optimizer.scale_loss(loss) # S * loss
grads = tape.gradient(scaled_loss, net.trainable_variables)
# Divide by S, skip the step on inf/NaN, adjust S
optimizer.apply_gradients(zip(grads, net.trainable_variables))
print(f'loss {float(loss):.3f}, '
f'loss scale {float(optimizer.dynamic_scale):.0f}')loss 1.994, loss scale 32768
Consequently, on modern hardware with native bf16 support (recent GPUs, TPUs, and server CPUs), bf16 mixed precision without loss scaling is the standard recipe; fp16 with dynamic loss scaling remains essential on older GPUs.
One final hardware feature accelerates fp32 models without changing any tensor dtypes at all. Starting with NVIDIA’s Ampere architecture, fp32 matrix multiplications can run on tensor cores in tf32 mode: inputs are truncated to fp16’s 10-bit mantissa while keeping fp32’s 8-bit exponent, and inner products accumulate in full fp32, delivering substantial speedups while matching strict fp32 to three or four significant digits.
PyTorch defaults to strict fp32 matmuls; torch.set_float32_matmul_precision('high') (Section 5.7) enables tf32.
TensorFlow enables tf32 on supported GPUs by default (controlled via tf.config.experimental.enable_tensor_float_32_execution(False)).
JAX enables tf32 on supported GPUs by default (controlled via jax.default_matmul_precision('float32')).
MXNet enables tf32 on supported GPUs by default (controlled via NVIDIA_TF32_OVERRIDE=0).
5.5.4 Numerical Failure Modes
Three concrete hazards explain the vast majority of numerical bugs in 16-bit code: an upstream overflow that surfaces downstream as NaN, an unshifted exponential that blows up before the final logarithm can shrink it, and a long reduction that stops growing once individual terms fall below the accumulator’s rounding threshold.
5.5.4.1 From Overflow to NaN
A NaN loss is rarely the root cause: it is usually the aftermath of an earlier overflow to inf, because indeterminate arithmetic like inf - inf or inf / inf produces NaN:
s = torch.tensor(60000., dtype=torch.float16) * 2 # Overflows
s, s - s(tensor(inf, dtype=torch.float16), tensor(nan, dtype=torch.float16))
s = tf.constant(60000., dtype=tf.float16) * 2 # Overflows
s, s - s(<tf.Tensor: shape=(), dtype=float16, numpy=inf>,
<tf.Tensor: shape=(), dtype=float16, numpy=nan>)
s = jnp.array(60000., dtype=jnp.float16) * 2 # Overflows
s, s - s(Array(inf, dtype=float16), Array(nan, dtype=float16))
s = mnp.array(60000., dtype='float16') * 2 # Overflows
s, s - s(array(inf, dtype=float16), array(nan, dtype=float16))
That initial overflow may occur layers upstream before NaN ever reaches the loss, and once a single parameter update carries a NaN, every subsequent step is poisoned. Whenever a loss turns NaN, check value ranges first (is any operation running in fp16 near its 65504 ceiling?) before blaming the learning rate or architecture.
To halt immediately at the first op producing inf or NaN during debugging, enable tf.debugging.enable_check_numerics().
To halt immediately at the first op producing inf or NaN during debugging, enable jax.config.update('jax_debug_nans', True).
5.5.4.2 Log-Sum-Exp
Softmax cross-entropy requires computing \(\log \sum_i \exp(x_i)\). Evaluating that expression literally overflows in fp16 even when the final answer is small:
x = torch.tensor([12.0, 11.0, 10.0], dtype=torch.float16)
x.exp().sum().log(), torch.logsumexp(x, dim=0)(tensor(inf, dtype=torch.float16), tensor(12.4062, dtype=torch.float16))
x = tf.constant([12.0, 11.0, 10.0], dtype=tf.float16)
tf.math.log(tf.reduce_sum(tf.exp(x))), tf.math.reduce_logsumexp(x)(<tf.Tensor: shape=(), dtype=float16, numpy=inf>,
<tf.Tensor: shape=(), dtype=float16, numpy=12.40625>)
x = jnp.array([12.0, 11.0, 10.0], dtype=jnp.float16)
jnp.log(jnp.exp(x).sum()), jax.scipy.special.logsumexp(x)(Array(inf, dtype=float16), Array(12.41, dtype=float16))
x = mnp.array([12.0, 11.0, 10.0], dtype='float16')
m = x.max()
mnp.log(mnp.exp(x).sum()), m + mnp.log(mnp.exp(x - m).sum())(array(inf, dtype=float16), array(12.41, dtype=float16))
Although the true answer is a modest 12.4, the intermediate term \(e^{12} \approx 163{,}000\) easily blows past fp16’s 65504 limit. The fix is the exact shift we introduced in Section 3.3.5.2: subtract the maximum entry \(m = \max_i x_i\) before exponentiating and add \(m\) back afterward,
\[\log \sum_i \exp(x_i) = m + \log \sum_i \exp(x_i - m). \tag{5.5.2}\]
Every exponent on the right is nonpositive, making overflow impossible, and the largest term is exactly \(e^0 = 1\), preventing underflow to \(\log 0\). In practice you rarely need to code this shift yourself: built-in log-softmax and cross-entropy routines apply it automatically.
5.5.4.3 Accumulation in fp32
Long sums accumulated in 16 bits stall silently: once the running total grows large enough, each small summand falls below half the local grid spacing and rounds to zero. Below we add \(2^{-10}\) (represented exactly in fp16) 4096 times into an fp16 accumulator versus an fp32 accumulator:
total16, total32 = np.float16(0), np.float32(0)
term = np.float16(2**-10)
for _ in range(4096):
total16 += term # fp16 accumulator
total32 += term # fp32 accumulator, same fp16 terms
total16, total32(np.float16(2.0), np.float32(4.0))
(np.float16(2.0), np.float32(4.0))
(np.float16(2.0), np.float32(4.0))
(2.0, 4.0)
The exact total is 4, which the fp32 accumulator hits on the nose. The fp16 accumulator freezes at 2 after 2048 steps: between 2 and 4, adjacent fp16 values lie \(2^{-9}\) apart, so \(2 + 2^{-10}\) lands right on the midpoint and round-to-nearest-even snaps it back to 2 forever. Batch averages, epoch loss totals, and variance calculations in normalization layers all share this hazard, which is why mixed-precision policies keep reductions and normalizations in fp32, and why any custom reduction over 16-bit tensors should accumulate in fp32.
All three failure modes trace back to the same root: an intermediate quantity outstripping the range or precision of a 16-bit format even when the final answer fits comfortably. Remember also that mixed precision and tf32 alter the lowest bits of arithmetic by design, so they will never match pure fp32 bit for bit. When runs can be made bit-for-bit repeatable, and how to achieve it, is the focus of Section 5.8.
5.5.5 Summary
Floating-point formats trade dynamic range (exponent bits) against precision (mantissa bits): fp16 gives finer local steps but a narrow range (overflowing past 65504 and underflowing tiny gradients), whereas bf16 keeps fp32’s full 8-bit exponent at just two to three decimal digits of precision. Storing weights directly in 16 bits rounds away small gradient updates and stalls training, so mixed-precision training keeps fp32 master weights while running matrix multiplications and storing activations in 16 bits, matching fp32 accuracy on our Fashion-MNIST MLP where pure bf16 weights fall behind. With fp16, dynamic loss scaling lifts gradients out of the subnormal/underflow zone during backpropagation; bf16 avoids this step altogether. Finally, guard low-precision code against overflow-induced NaNs by using shifted log-sum-exp operations and fp32 accumulators for long reductions and normalizations.
5.5.6 Exercises
Mixed-precision memory. Training with Adam in fp32 stores 16 bytes per parameter (Section 5.2). Suppose that
trainused Adam instead of SGD.- In which dtype does the mixed-precision recipe of your framework store the weights, the gradients, and Adam’s running averages between steps? Does mixed precision reduce the bytes per parameter?
- Count as stored activations the input of each linear layer and the logits. For the MLP of
train, convert the per-example count to bytes in fp32 and in the 16-bit formattrainuses. At which batch size does the activation saving equal the persistent training state of this MLP?
Loss scaling on overflow. Under dynamic loss scaling (Section 5.5.3.3), a step whose unscaled gradients contain an
infor NaN is skipped and the scale is halved. After \(N\) consecutive clean steps, the scale is doubled.- A skipped step must leave Adam’s running averages untouched. Explain what would go wrong if the step instead updated them with the non-finite gradient, and what would go wrong if it updated them with the non-finite entries replaced by zeros.
- Explain why the scale must grow again after a run of clean steps instead of only shrinking.
- Suppose that every step overflows when the scale is above a fixed threshold and that no step overflows below it. Once the scale has settled, what fraction of steps is skipped as a function of \(N\)? Without the assumption of a fixed threshold, what does a larger \(N\) cost?
[code] Normalization in fp16. Mixed-precision recipes run normalization layers in fp32. To see why, consider RMSNorm with its gain set to one (Section 5.4 implements it as a module). It rescales an input row \(\mathbf{x}\) of width \(d\) by its root mean square,
\[\frac{\mathbf{x}}{\sqrt{\frac{1}{d} \sum_{i=1}^{d} x_i^2 + \epsilon}}, \tag{5.5.3}\]
where the small constant \(\epsilon\) guards against division by zero. Compute it entirely in fp16 for a batch of 64 rows of width \(d = 1024\) whose entries have a standard deviation of about 100.
- Which intermediate quantity is the first to become
inf, and what does the layer return for the affected rows? - Take the squares as exact. At what input standard deviation does their mean exceed the fp16 maximum, and at what standard deviation does their sum over the \(d\) entries exceed it?
- Which intermediate quantity is the first to become
[code] The e4m3fn format. ● Print
torch.finfo(torch.float8_e4m3fn)and compare itsmax,tinyandepswith those of fp16 and bf16. Explain the namee4m3fn. A format with a 4-bit exponent and a 3-bit mantissa that followed the IEEE convention would reserve the all-ones exponent forinfand NaN. Compute that format’s largest finite value, and explain howe4m3fnreaches amaxof 448 instead.
Mixed-precision memory. Training with Adam in fp32 stores 16 bytes per parameter (Section 5.2). Suppose that
trainused Adam instead of SGD.- In which dtype does the mixed-precision recipe of your framework store the weights, the gradients, and Adam’s running averages between steps? Does mixed precision reduce the bytes per parameter?
- Count as stored activations the input of each linear layer and the logits. For the MLP of
train, convert the per-example count to bytes in fp32 and in the 16-bit formattrainuses. At which batch size does the activation saving equal the persistent training state of this MLP?
Loss scaling on overflow. Under dynamic loss scaling (Section 5.5.3.3), a step whose unscaled gradients contain an
infor NaN is skipped and the scale is halved. After \(N\) consecutive clean steps, the scale is doubled.- A skipped step must leave Adam’s running averages untouched. Explain what would go wrong if the step instead updated them with the non-finite gradient, and what would go wrong if it updated them with the non-finite entries replaced by zeros.
- Explain why the scale must grow again after a run of clean steps instead of only shrinking.
- Suppose that every step overflows when the scale is above a fixed threshold and that no step overflows below it. Once the scale has settled, what fraction of steps is skipped as a function of \(N\)? Without the assumption of a fixed threshold, what does a larger \(N\) cost?
[code] Normalization in fp16. Mixed-precision recipes run normalization layers in fp32. To see why, consider RMSNorm with its gain set to one (Section 5.4 implements it as a module). It rescales an input row \(\mathbf{x}\) of width \(d\) by its root mean square,
\[\frac{\mathbf{x}}{\sqrt{\frac{1}{d} \sum_{i=1}^{d} x_i^2 + \epsilon}},\]
where the small constant \(\epsilon\) guards against division by zero. Compute it entirely in fp16 for a batch of 64 rows of width \(d = 1024\) whose entries have a standard deviation of about 100.
- Which intermediate quantity is the first to become
inf, and what does the layer return for the affected rows? - Take the squares as exact. At what input standard deviation does their mean exceed the fp16 maximum, and at what standard deviation does their sum over the \(d\) entries exceed it?
- Which intermediate quantity is the first to become
[code] The e4m3fn format. ● Print
ml_dtypes.finfo(ml_dtypes.float8_e4m3fn)and compare itsmax,tinyandepswith those of fp16 and bf16. Explain the namee4m3fn. A format with a 4-bit exponent and a 3-bit mantissa that followed the IEEE convention would reserve the all-ones exponent forinfand NaN. Compute that format’s largest finite value, and explain howe4m3fnreaches amaxof 448 instead.
Mixed-precision memory. Training with Adam in fp32 stores 16 bytes per parameter (Section 5.2). Suppose that
trainused Adam instead of SGD.- In which dtype does the mixed-precision recipe of your framework store the weights, the gradients, and Adam’s running averages between steps? Does mixed precision reduce the bytes per parameter?
- Count as stored activations the input of each linear layer and the logits. For the MLP of
train, convert the per-example count to bytes in fp32 and in the 16-bit formattrainuses. At which batch size does the activation saving equal the persistent training state of this MLP?
Loss scaling on overflow. Under dynamic loss scaling (Section 5.5.3.3), a step whose unscaled gradients contain an
infor NaN is skipped and the scale is halved. After \(N\) consecutive clean steps, the scale is doubled.- A skipped step must leave Adam’s running averages untouched. Explain what would go wrong if the step instead updated them with the non-finite gradient, and what would go wrong if it updated them with the non-finite entries replaced by zeros.
- Explain why the scale must grow again after a run of clean steps instead of only shrinking.
- Suppose that every step overflows when the scale is above a fixed threshold and that no step overflows below it. Once the scale has settled, what fraction of steps is skipped as a function of \(N\)? Without the assumption of a fixed threshold, what does a larger \(N\) cost?
[code] Normalization in fp16. Mixed-precision recipes run normalization layers in fp32. To see why, consider RMSNorm with its gain set to one (Section 5.4 implements it as a module). It rescales an input row \(\mathbf{x}\) of width \(d\) by its root mean square,
\[\frac{\mathbf{x}}{\sqrt{\frac{1}{d} \sum_{i=1}^{d} x_i^2 + \epsilon}},\]
where the small constant \(\epsilon\) guards against division by zero. Compute it entirely in fp16 for a batch of 64 rows of width \(d = 1024\) whose entries have a standard deviation of about 100.
- Which intermediate quantity is the first to become
inf, and what does the layer return for the affected rows? - Take the squares as exact. At what input standard deviation does their mean exceed the fp16 maximum, and at what standard deviation does their sum over the \(d\) entries exceed it?
- Which intermediate quantity is the first to become
[code] The e4m3fn format. ● Print
jnp.finfo(jnp.float8_e4m3fn)and compare itsmax,tinyandepswith those of fp16 and bf16. Explain the namee4m3fn. A format with a 4-bit exponent and a 3-bit mantissa that followed the IEEE convention would reserve the all-ones exponent forinfand NaN. Compute that format’s largest finite value, and explain howe4m3fnreaches amaxof 448 instead.
Mixed-precision memory. Training with Adam in fp32 stores 16 bytes per parameter (Section 5.2). Suppose that
trainused Adam instead of SGD.- In which dtype does the mixed-precision recipe of your framework store the weights, the gradients, and Adam’s running averages between steps? Does mixed precision reduce the bytes per parameter?
- Count as stored activations the input of each linear layer and the logits. For the MLP of
train, convert the per-example count to bytes in fp32 and in the 16-bit formattrainuses. At which batch size does the activation saving equal the persistent training state of this MLP?
Loss scaling on overflow. Under dynamic loss scaling (Section 5.5.3.3), a step whose unscaled gradients contain an
infor NaN is skipped and the scale is halved. After \(N\) consecutive clean steps, the scale is doubled.- A skipped step must leave Adam’s running averages untouched. Explain what would go wrong if the step instead updated them with the non-finite gradient, and what would go wrong if it updated them with the non-finite entries replaced by zeros.
- Explain why the scale must grow again after a run of clean steps instead of only shrinking.
- Suppose that every step overflows when the scale is above a fixed threshold and that no step overflows below it. Once the scale has settled, what fraction of steps is skipped as a function of \(N\)? Without the assumption of a fixed threshold, what does a larger \(N\) cost?
[code] Normalization in fp16. Mixed-precision recipes run normalization layers in fp32. To see why, consider RMSNorm with its gain set to one (Section 5.4 implements it as a module). It rescales an input row \(\mathbf{x}\) of width \(d\) by its root mean square,
\[\frac{\mathbf{x}}{\sqrt{\frac{1}{d} \sum_{i=1}^{d} x_i^2 + \epsilon}},\]
where the small constant \(\epsilon\) guards against division by zero. Compute it entirely in fp16 for a batch of 64 rows of width \(d = 1024\) whose entries have a standard deviation of about 100.
- Which intermediate quantity is the first to become
inf, and what does the layer return for the affected rows? - Take the squares as exact. At what input standard deviation does their mean exceed the fp16 maximum, and at what standard deviation does their sum over the \(d\) entries exceed it?
- Which intermediate quantity is the first to become
The e4m3fn format. ● The fp8 format
float8_e4m3fnhas one sign bit, 4 exponent bits with bias 7, and 3 mantissa bits. Derive itstinyandepsand compare them with those of fp16 and bf16. Explain the namee4m3fn. A format with the same bit layout that followed the IEEE convention would reserve the all-ones exponent forinfand NaN. Compute that format’s largest finite value, and explain howfloat8_e4m3fnreaches a largest finite value of 448 instead.