5.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, already
overflows to inf, flooding training with inf and NaN values. In bf16, adding
to a weight of rounds right back to , 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 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))
In fp16 (half precision), 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 ,
an exponent , and a -bit mantissa encoding a fraction ,
representing
Exponent bits govern dynamic range (the largest and smallest magnitudes the format can represent), while mantissa bits govern relative precision: adjacent numbers between and sit apart, and between and they sit 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, spans , capping fp16 at . With 7 mantissa bits, bf16 values between and are spaced by , so 90000 falls between and and rounds to the closer value, 90112.
Figure 5.5.1 visualizes these bit budgets side by side (see Section 23.8 for a deeper treatment of IEEE floating-point arithmetic).
Bit layouts of the formats in the table, aligned at the sign bit, so that a longer bar means more bits: bf16 keeps the 8-bit exponent of fp32, and fp16 and bf16 split the same 16 bits in opposite ways.
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 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 , so a value near
still preserves 9 significant bits, whereas one near
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
Because bf16 shares fp32's 8-bit exponent, it matches fp32's tiny and nearly
matches its max, while its eps of gives two to three decimal digits
of precision. fp16 resolves three to four decimal digits, but overflows above
65504, slips into subnormals below , and cannot represent
any positive value below . 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 , often or less of the weight's magnitude. Under round-to-nearest, any step smaller than half the local spacing vanishes completely. Below we add and to a weight of 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
In fp32, both increments register cleanly. In bf16, whose spacing near 1 is , both round right back to 1, leaving the weight completely frozen. In fp16 (spacing ), the step survives (rounded to one grid step) while 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.
The bf16 grid (top) and the fp16 grid (bottom) near a weight of 1, drawn to one scale. A shaded interval holds the values that round back to 1; it reaches half a grid spacing to each side, and the spacing below 1 is half the spacing above it. In bf16 the update lies inside the interval and is lost. In fp16 it lies outside and rounds to the next grid point, .
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)
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 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
net.to(dtype) (or net.bfloat16()) casts all parameters and buffers; layers reject inputs whose dtype does not match their weights.
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
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.
One step of mixed-precision training: the fp32 master weights are cast to bf16 for the forward pass, which produces bf16 activations; the loss is computed in fp32; the backward pass produces gradients, and the optimizer applies them to the fp32 master weights. With fp16, the loss is also scaled up before the backward pass and the gradients are scaled back down before the update.
torch.autocast leaves parameters in fp32 and automatically casts eligible ops (matrix multiplies, convolutions) to 16 bits while keeping reductions and losses in fp32.
net = mlp()
with torch.autocast('cpu', dtype=torch.bfloat16):
Y = net(X)
Y.dtype, net[1].weight.dtype(torch.bfloat16, torch.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 (one-tenth the rate used in Section 4.2) and run for 1000 steps (about four epochs). Our rounding analysis explains why matters so dramatically: an update 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)))With the training minibatches and a 1,024-image validation slice preloaded in memory, train runs SGD steps at 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(), 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).
Before training, we check the rounding argument on the first minibatch. Of the nonzero first-layer updates at initialization, what fraction would bf16 storage round away at and at , 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
At 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 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 .
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
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.
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 drop into subnormals and shed significant bits, and anything below half the smallest subnormal () rounds straight to zero. A gradient of vanishes in fp16, yet multiplying it by 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))
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 :
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
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 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 . By linearity of differentiation, every intermediate gradient shifts up by during backpropagation. Before stepping the optimizer, divide the gradients back down by 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 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 , inspect the gradients on every step, and whenever an
inf or NaN appears, skip the optimizer update and halve ; after a streak of
clean steps, double to stay close to the top of fp16's range.
Figure 5.5.4 shows one step of this loop.
One step of dynamic loss scaling. The loss is multiplied by , the backward pass runs in fp16, and the gradients are divided by in fp32. If all of them are finite, the optimizer takes its step, and doubles after a streak of such steps. If any is inf or NaN, the step is skipped and is halved.
torch.amp.GradScaler automates dynamic loss scaling with fp16 autocast:
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
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.
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))
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.
5.5.4.2 Log-Sum-Exp#
Softmax cross-entropy requires computing . 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))
Although the true answer is a modest 12.4, the intermediate term 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 before exponentiating and add back afterward,
Every exponent on the right is nonpositive, making overflow impossible, and the largest term is exactly , preventing underflow to . 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 (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))
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 apart, so 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 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 ? Without the assumption of a fixed threshold, what does a larger 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 of width by its root mean square,
where the small constant guards against division by zero. Compute it entirely in fp16 for a batch of 64 rows of width 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 entries exceed it?
- [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.