Session S26
S19 showed that a 7B model needs 104 GiB to train in full, more than a single 80 GB GPU holds. What do 16-bit numbers give up, and how does training cope? How can several GPUs share that training memory? How far can a trained model be shrunk? What limits how many users one GPU can serve, and how fast?
Deep Learning · CS 4715/5715 · University of Idaho
Welcome back from Fall Recess. Course items first; nothing is due today.
Today and the next session (S27) are the course's last two sessions of new material.
S25 closed the generative half of Module 4 with this table (reading 4.3); coverage and fidelity are S24's recall and precision:
| family | training | sampling | strength | weakness |
|---|---|---|---|---|
| VAE | stable (a likelihood bound) | one decoder pass | a usable latent space | blur |
| GAN | an adversarial game | one forward pass | sharp samples | unstable training, mode collapse |
| diffusion | stable (regression on noise) | many steps | coverage and fidelity | slow, iterative sampling |
Diffusion's weakness is the cost of sampling.
All semester our models trained in seconds on a laptop CPU. Scaling laws (S18) tie a model's quality to its compute. Every printout today comes from reading 4.4's scripts, which run on a CPU in seconds, or from arithmetic on them.
| part | the question it answers |
|---|---|
| 1 · Number formats | What do 16-bit numbers give up, and how does training cope? Two formats split 16 bits differently, and mixed precision makes training work in them. |
| 2 · Training memory | How can several GPUs share the training memory? S19 counted 16 bytes per parameter, and three stages split them across GPUs. |
| 3 · Shrinking a model | How far can a trained model be shrunk? Quantization stores each weight in 8 bits, pruning removes weights, and distillation trains a smaller network to imitate a larger one. |
| 4 · Serving | What limits how many users one GPU can serve, and how fast? Each conversation holds memory on the GPU, and each generated token costs time. |
| 5 · Close | A summary of what each technique saves and what it changes, six common mistakes, and today's answer. |
At scale, whatever lowers the cost gives a better model for the same budget.
Part 1 · Number formats. Every tensor so far was float32. Halving to 16 bits doubles the parameters per GB and, on recent GPUs, can more than double arithmetic throughput (reading 4.4). fp32, fp16 and bf16 are short for PyTorch's float32, float16 and bfloat16. Three fields give a float's value:
bfloat16 is "brain floating point", named for Google Brain, where it was conceived.Consequences of \(\text{value}=\pm\,1.\text{mantissa}\times2^{\text{exponent}}\), with \(m\) mantissa bits:
The script's first half, comments left out: torch.finfo reports a format's largest number, smallest normal number (the smallest positive number stored at full precision) and eps; .to(dtype) rounds a tensor into that format.
import torch
for dt in [torch.float32, torch.float16, torch.bfloat16]:
fi = torch.finfo(dt)
print(f"{str(dt):15} max {fi.max:.3e} smallest normal {fi.tiny:.3e} eps {fi.eps:.3e}")
print()
x = torch.tensor(70000.0)
print(f"70000 in fp16: {x.to(torch.float16).item()}")
print(f"70000 in bf16: {x.to(torch.bfloat16).item()}")
y = torch.tensor(1.0 + 2**-10)
print(f"1 + 2^-10 in fp32: {y.item():.10f}")
print(f"1 + 2^-10 in fp16: {y.to(torch.float16).item():.10f}")
print(f"1 + 2^-10 in bf16: {y.to(torch.bfloat16).item():.10f}")
Predict from the previous page: which format turns 70,000 into inf, and which one rounds \(1+2^{-10}\) back to 1?
Answer: fp16 overflows at 70,000, and bf16 rounds \(1+2^{-10}\) back to 1. The printout:
torch.float32 max 3.403e+38 smallest normal 1.175e-38 eps 1.192e-07
torch.float16 max 6.550e+04 smallest normal 6.104e-05 eps 9.766e-04
torch.bfloat16 max 3.390e+38 smallest normal 1.175e-38 eps 7.812e-03
70000 in fp16: inf
70000 in bf16: 70144.0
1 + 2^-10 in fp32: 1.0009765625
1 + 2^-10 in fp16: 1.0009765625
1 + 2^-10 in bf16: 1.0000000000
inf. Arithmetic on inf can give NaN (\(\infty-\infty\), \(0\cdot\infty\)), and every later result computed from a NaN is NaN.The script's second half asks what training does with these numbers (torch as on the previous pages). First, an update of 1 added to a weight of 2048, both stored in fp16:
w32 = torch.tensor(2048.0); w16 = w32.to(torch.float16)
print(f"fp32: 2048 + 1 = {(w32 + 1).item()}")
print(f"fp16: 2048 + 1 = {(w16 + torch.tensor(1.0, dtype=torch.float16)).item()}")
fp32: 2048 + 1 = 2049.0
fp16: 2048 + 1 = 2048.0
Near 2048 fp16's numbers are \(2^{11}\cdot2^{-10}=2\) apart: it can store 1, 2048 and 2050, but not 2049. The sum is rounded to 2048, so the weight does not change.
Second, a small gradient. Below fp16's smallest normal number, \(6.10\times10^{-5}\), fp16 keeps subnormal values, the multiples of \(2^{-14}\cdot2^{-10}=2^{-24}\approx5.96\times10^{-8}\); values under half of \(2^{-24}\) round to 0.
g = torch.tensor(1e-8)
print(f"gradient 1e-8 in fp16: {g.to(torch.float16).item()}")
print(f"after 1024x loss scaling: {(g * 1024).to(torch.float16).item():.3e}")
gradient 1e-8 in fp16: 0.0
after 1024x loss scaling: 1.025e-05
Loss scaling multiplies the loss by a factor \(S\) before the backward pass, so every gradient is \(S\) times larger. The code applies \(S=1024\) to the gradient directly.
One mixed-precision training step (Micikevicius et al., ICLR 2018), its four steps numbered:
The four steps of the previous page's figure:
The 16-bit gradients keep about 3 significant digits, and nothing restores the rest; training tolerates that. The fp32 copy is there because weight + small update does not fit in 16 bits.
autocast runs the 16-bit passes, GradScaler scales the loss
import torch
device = "cuda" if torch.cuda.is_available() else "cpu" # the GPU if there is one
model = torch.nn.Linear(8, 2).to(device) # its weights stay fp32: the master copy
opt = torch.optim.SGD(model.parameters(), lr=0.1)
scaler = torch.amp.GradScaler(device) # holds the loss scale S
x, y = torch.randn(64, 8, device=device), torch.randint(0, 2, (64,), device=device)
for step in range(3):
opt.zero_grad()
with torch.autocast(device_type=device, dtype=torch.float16): # steps 1-2: 16-bit forward
loss = torch.nn.functional.cross_entropy(model(x), y)
scaler.scale(loss).backward() # steps 2-3: backward on S * loss, outside the block
scaler.step(opt) # step 4: gradients / S, then update; skipped on inf or NaN
scaler.update() # lowers S after a skipped step
# with bf16: dtype=torch.bfloat16, then loss.backward(); opt.step() and no scaler
GradScaler chooses \(S\) itself: it starts at \(2^{16}\) and halves it on overflow. The earlier 1024 was an example.bf16 has fp32's range, so it needs no loss scaling; its precision is coarser.
(a) bf16 has 7 mantissa bits. Which one is stored exactly in bf16: \(1+2^{-6}\) or \(1+2^{-9}\)?
(b) An fp16 weight of 4096 receives an update of +1. What value is stored after the update? What does mixed precision do so that the update is kept?
(a) \(1+2^{-6}\). Near 1, bf16's numbers are \(2^{-7}\) apart. \(2^{-6}\) is two of these steps, so \(1+2^{-6}\) is stored exactly. \(2^{-9}\) is a quarter of a step, so \(1+2^{-9}\) rounds to 1.
(b) 4096 is stored. Near 4096, fp16's numbers are \(2^{12}\cdot2^{-10}=4\) apart, so 4097 is rounded back to 4096. Mixed precision adds the update to the fp32 master copy, which stores 4097 exactly.
(c) You train in bf16, and one gradient is \(10^{-8}\). Does bf16 need loss scaling to store this gradient?
(c) No. bf16 has fp32's 8 exponent bits, so its smallest normal number is \(1.175\times10^{-38}\), far below \(10^{-8}\). The gradient is stored as a nonzero number without scaling.
fp16 has more precision, bf16 more range; mixed precision updates fp32 and scales the loss.
Part 2 · Training memory. A recap of S19, for Part 1's mixed precision with Adam, activations excluded; S19 counted it in bf16, and fp16 is also 2 bytes per number. Per trained parameter:
Training holds 8 times the weights' bytes, and optimizer state is 12 of the 16.
Plain data parallelism (plain DP) trains one model on \(P\) GPUs; PyTorch's version is DistributedDataParallel (DDP). Per trained parameter, each GPU holds:
With plain DP, each GPU still needs the full 104.3 GiB for the 7B model.
ZeRO, the Zero Redundancy Optimizer (Rajbhandari et al., 2020; DeepSpeed), shards those 16 bytes in three stages: a sharded part is cut into \(P\) pieces, and each GPU stores one.
| bytes per parameter, per GPU | plain DP | ZeRO-1 | ZeRO-2 | ZeRO-3 |
|---|---|---|---|---|
| with \(P\) GPUs | 16 | \(4+12/P\) | \(2+14/P\) | \(16/P\) |
| with \(P=8\) | 16 | 5.5 | 3.75 | 2 |
With 8 GPUs, the three stages cut 16 bytes per parameter on each GPU to 5.5, 3.75 and 2.
GiB per GPU is the previous page's bytes per parameter \(\times\,7\times10^9\,/\,1024^3\):
| 7B model | training on 1 GPU | ZeRO-1, 8 GPUs | ZeRO-2, 8 GPUs | ZeRO-3, 8 GPUs |
|---|---|---|---|---|
| bytes per parameter, per GPU | 16 | 5.5 | 3.75 | 2 |
| GiB per GPU | 104.3 | 35.9 | 24.4 | 13.0 |
ZeRO-3 on 8 GPUs holds \(16/8=2\) bytes per parameter on each GPU, 13.0 GiB: the same as inference.
Training takes 8 times the memory of inference before a single activation is stored.
Use the lowest ZeRO stage that fits in memory, and leave margin: these numbers exclude activations.
(a) With ZeRO stage 2 on 4 GPUs, how many bytes per parameter does each GPU hold? How many GiB is that for the 7B model?
(b) A 70B model is trained with ZeRO stage 3 on 80 GB GPUs, counted as 80 GiB each. How many GPUs does the training state alone need, at least?
(a) Stage 2 keeps the 2 bytes of weights on every GPU and shards the other 14 bytes, so each GPU holds \(2+14/4=5.5\) bytes per parameter. For the 7B model, \(5.5\times7\times10^9\) bytes is 35.9 GiB, the same as ZeRO-1 on 8 GPUs.
(b) Stage 3 shards all 16 bytes, so the GPUs together hold \(16\times70\times10^9\) bytes, 1,043 GiB. \(1{,}043/80=13.04\), so at least 14 GPUs, and more once activations are counted.
(c) ZeRO stage 3 uses the least memory of the three stages. Why is it not always the stage to use?
(c) Stage 3 costs communication: at every step it gathers each layer's weights from the other GPUs. Use the lowest stage that fits in memory.
ZeRO shards the 16 bytes per parameter across GPUs, and stage 3 costs communication.
Part 3 · Shrinking a model. A trained model needs no gradients and no optimizer state, only its weights, so the goal changes to storing and running the weights cheaply. Symmetric int8 quantization (reading 4.4):
| \(W\) | \(s\) | \(q\) | \(\hat W\) | largest error (bound \(s/2\)) |
|---|---|---|---|---|
| \((1.27,\ -0.613,\ 0.004)\) | \(0.01\) | \((127,\ -61,\ 0)\) | \((1.27,\ -0.61,\ 0)\) | \(0.004\ (0.005)\) |
| \((12.7,\ -0.613,\ 0.004)\) | \(0.1\) | \((127,\ -6,\ 0)\) | \((12.7,\ -0.6,\ 0)\) | \(0.013\ (0.05)\) |
One large weight sets \(s\), and with it the grid of every other weight.
quantize_int8 rounds \(W\) to an int8 grid; report measures two errorsReading 4.4's script, docstrings left out. quantize_int8 returns \(\hat W\); with per_channel=True, max(dim=1, keepdim=True) gives one scale per output row, a (256, 1) column that broadcasts across its row.
def quantize_int8(w, per_channel=False):
if per_channel:
scale = w.abs().max(dim=1, keepdim=True).values / 127
else:
scale = w.abs().max() / 127
wq = (w / scale).round().clamp(-127, 127) # keep q within ±127
return wq * scale # dequantized floats; HW4 returns (int8 q, scale)
def report(name, w, x):
y = w @ x
for mode, pc in [("per-tensor", False), ("per-channel", True)]:
wdq = quantize_int8(w, per_channel=pc)
w_err = (wdq - w).abs().max()
y_err = (wdq @ x - y).norm() / y.norm()
print(f"{name}, {mode:11}: max weight err {w_err.item():.5f} "
f"relative matmul err {y_err.item():.5f}")
report prints the largest weight error \(\max\lvert\hat W-W\rvert\) and the relative error \(\lVert\hat WX-WX\rVert/\lVert WX\rVert\), where \(\lVert\cdot\rVert\) is the square root of the sum of squared entries.
The previous page's functions on a \(256\times256\) Gaussian \(W\) and a (256, 64) \(X\), then with one weight set to 5.0:
import torch
torch.manual_seed(0)
w = torch.randn(256, 256) * 0.05 # typical trained-weight scale
x = torch.randn(256, 64)
report("well-behaved W", w, x)
w_out = w.clone()
w_out[0, 0] = 5.0 # one outlier weight, 100x the rest
report("W with outlier", w_out, x)
well-behaved W, per-tensor : max weight err 0.00090 relative matmul err 0.01032
well-behaved W, per-channel: max weight err 0.00090 relative matmul err 0.00687
W with outlier, per-tensor : max weight err 0.01968 relative matmul err 0.21665
W with outlier, per-channel: max weight err 0.01964 relative matmul err 0.01491
The previous page's three cases, with each int8 grid point drawn:
LLM.int8(), keeps those in 16 bits.Quantization keeps every weight and stores it in fewer bits; pruning deletes weights. Han et al. (NeurIPS 2015) rank the weights by magnitude, set the smallest to zero and retrain the rest; they report 9 times fewer parameters for AlexNet and 13 times fewer for VGG-16, without accuracy loss.
| scheme | how the weights are ranked | fraction removed from each layer |
|---|---|---|
| global | all weights together, with one threshold | can differ from layer to layer |
| per-layer | each layer's weights separately, with one threshold per layer | the same in every layer |
Pruning removes weights by magnitude; the choice is where the threshold is computed.
From seed 0, moons adds noise 0.15 to two interleaved moons; labels alternate 0, 1, so each class is half the test set. torch.where takes the upper arc \((\cos t,\sin t)\) for even indices and the lower arc \((1-\cos t,\ 0.5-\sin t)\) for odd ones; unsqueeze(1) makes the condition (n, 1), so it broadcasts over both coordinates.
import torch
import torch.nn as nn
torch.manual_seed(0)
# Classification data: two interleaved moons
def moons(n, gen=None):
t = torch.rand(n, generator=gen) * torch.pi
x = torch.where(
(torch.arange(n) % 2 == 0).unsqueeze(1),
torch.stack([torch.cos(t), torch.sin(t)], dim=1),
torch.stack([1 - torch.cos(t), 0.5 - torch.sin(t)], dim=1),
) + 0.15 * torch.randn(n, 2, generator=gen)
y = (torch.arange(n) % 2).long()
return x, y
g = torch.Generator().manual_seed(0)
x_tr, y_tr = moons(2000, g)
x_te, y_te = moons(1000, g)
The script trains with Adam for 1,500 steps on batches of 128, then keeps the three weight matrices, and a copy of them, for pruning:
net = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(),
nn.Linear(64, 2))
opt = torch.optim.Adam(net.parameters(), lr=1e-2)
for step in range(1500):
idx = torch.randint(0, len(x_tr), (128,))
loss = nn.functional.cross_entropy(net(x_tr[idx]), y_tr[idx])
opt.zero_grad(); loss.backward(); opt.step()
def accuracy():
with torch.no_grad():
return (net(x_te).argmax(1) == y_te).float().mean().item()
weights = [m.weight for m in net.modules() if isinstance(m, nn.Linear)]
original = [w.detach().clone() for w in weights]
print(f"trained baseline: {sum(w.numel() for w in weights)} prunable weights, "
f"test acc {accuracy():.4f}")
trained baseline: 4352 prunable weights, test acc 0.9900
The first half of prune_and_eval, steps 2 and 3: it starts from the trained weights each time and multiplies each weight matrix by a mask, 1 where the magnitude is above the threshold and 0 below:
def prune_and_eval(sparsity, per_layer):
with torch.no_grad():
for w, orig in zip(weights, original):
w.copy_(orig)
if per_layer:
masks = [(w.abs() > w.abs().flatten().quantile(sparsity)).float()
for w in weights]
else: # one global threshold across all layers
th = torch.cat([w.abs().flatten() for w in weights]).quantile(sparsity)
masks = [(w.abs() > th).float() for w in weights]
for w, m in zip(weights, masks):
w.mul_(m)
acc = accuracy()
out_kept = masks[-1].mean().item() # surviving fraction in the output layer
Predict: a global threshold compares all 4,352 weights at once. If one layer's weights are smaller than the others', what happens to that layer at 90% sparsity? And what does the network output if the output layer loses all 128 weights?
The rest of prune_and_eval, step 4. Pruning happened once, on the previous page; these 200 steps retrain the remaining weights, and the same masks are multiplied in again after each step. Then the loop runs both schemes at four sparsities:
# brief fine-tune with the masks enforced after each step
opt_ft = torch.optim.Adam(net.parameters(), lr=1e-3)
for step in range(200):
idx = torch.randint(0, len(x_tr), (128,))
loss = nn.functional.cross_entropy(net(x_tr[idx]), y_tr[idx])
opt_ft.zero_grad(); loss.backward(); opt_ft.step()
with torch.no_grad():
for w, m in zip(weights, masks):
w.mul_(m)
return acc, accuracy(), out_kept
print(f"{'sparsity':>9} {'scheme':>10} {'acc pruned':>11} {'after tune':>11} "
f"{'output layer kept':>18}")
for sparsity in [0.5, 0.8, 0.9, 0.95]:
for per_layer in [False, True]:
acc, acc_ft, kept = prune_and_eval(sparsity, per_layer)
scheme = "per-layer" if per_layer else "global"
print(f"{sparsity:>9.0%} {scheme:>10} {acc:>11.4f} {acc_ft:>11.4f} {kept:>17.0%}")
Answer: the layer with the smaller weights loses the most. Here it is the output layer: in this run (seed 0) the global threshold keeps none of its 128 weights, so every input gets the same output. The printout:
sparsity scheme acc pruned after tune output layer kept
50% global 0.9890 0.9880 65%
50% per-layer 0.9910 0.9900 50%
80% global 0.9620 0.9840 4%
80% per-layer 0.7230 0.9890 20%
90% global 0.5000 0.5000 0%
90% per-layer 0.6020 0.8660 10%
95% global 0.5000 0.5000 0%
95% per-layer 0.7540 0.8880 5%
Dense matrix-multiply routines spend the same time on a zero as on any other number (reading 4.4). Two ways to place the same number of zeros:
A sparsity number says little about speed without its structure and the hardware it was measured on.
Quantization and pruning change one network's numbers; distillation trains a different, smaller network.
(a) Quantize the tensor \(W=(0.508,\,-2.54,\,0.02)\) to int8 with one scale for the whole tensor. What are the scale \(s\), the integers \(q\) and the largest error?
(b) A model pruned to 90% unstructured sparsity is smaller on disk but runs no faster. Why does it run no faster, and what would make it faster?
(a) The largest magnitude is 2.54, so \(s=2.54/127=0.02\). Dividing by \(s\) and rounding gives \(q=(25,\,-127,\,1)\), since \(0.508/0.02=25.4\). Then \(\hat W=q\,s=(0.50,\,-2.54,\,0.02)\). Only 0.508 changes, by 0.008, which is under the bound \(s/2=0.01\).
(b) Dense matrix-multiply routines spend the same time on a zero as on any other number. Structured sparsity that the hardware accelerates, such as the 2:4 pattern, makes it faster, and the running time has to be measured.
(c) Quantization, pruning and distillation each make a model cheaper to run. Which of the three gives you a different network to run?
(c) Distillation. The student is a separate, smaller network trained to match the teacher. Quantization and pruning change the weights of the original network.
One scale per row limits an outlier's effect to its own row; zeros alone do not make a model faster.
Part 4 · Serving. A trained model on a GPU generates text for many users at once.
Serving has two costs: memory per conversation and time per token.
A KV cache (S20) stores a key and a value for every past token, in each key-value head of each layer. With \(L\) layers, \(H_{\text{kv}}\) key-value heads of \(d_{\text{head}}\) floats each and \(b\) bytes per float, one token costs \(2\cdot L\cdot H_{\text{kv}}\cdot d_{\text{head}}\cdot b\) bytes:
Reading 4.4's KV script, first half, for 4,096, 32,768 and 131,072 tokens of context (in GiB; the script's KB is 1,024 bytes, a KiB):
GB = 1024**3 # GiB (binary); hardware sizes like '80 GB' are names
def kv_bytes_per_token(n_layers, n_kv_heads, head_dim, bytes_per_val=2):
return 2 * n_layers * n_kv_heads * head_dim * bytes_per_val
configs = [
("7B, MHA (Llama-2-7B-like)", 32, 32, 128),
("8B, GQA (Llama-3-8B-like)", 32, 8, 128),
]
print(f"{'model':28} {'KV/token':>9} {'4k ctx':>8} {'32k ctx':>8} {'128k ctx':>9}")
for name, L, H, D in configs:
per_tok = kv_bytes_per_token(L, H, D)
row = [per_tok * n / GB for n in (4096, 32768, 131072)]
print(f"{name:28} {per_tok/1024:>7.0f}KB {row[0]:>7.2f}G {row[1]:>7.2f}G {row[2]:>8.2f}G")
model KV/token 4k ctx 32k ctx 128k ctx
7B, MHA (Llama-2-7B-like) 512KB 2.00G 16.00G 64.00G
8B, GQA (Llama-3-8B-like) 128KB 0.50G 4.00G 16.00G
At 131,072 tokens the MHA cache is 64 GiB, about five times the 7B model's 13.0 GiB of weights, for one conversation. GQA divides every entry by 4.
The script's second half loads the fp16 weights, then adds 8,192-token caches (80 * GB is 80 GiB):
weights = {"7B, MHA (Llama-2-7B-like)": 2 * 7e9, "8B, GQA (Llama-3-8B-like)": 2 * 8e9}
print("concurrent 8k-token sequences that fit in 80 GB alongside the weights:")
for name, L, H, D in configs:
kv_per_seq = kv_bytes_per_token(L, H, D) * 8192
budget = 80 * GB - weights[name]
print(f"{name:28} {int(budget // kv_per_seq):>4d} sequences "
f"({kv_per_seq/GB:.2f} GiB per sequence)")
concurrent 8k-token sequences that fit in 80 GB alongside the weights:
7B, MHA (Llama-2-7B-like) 16 sequences (4.00 GiB per sequence)
8B, GQA (Llama-3-8B-like) 65 sequences (1.00 GiB per sequence)
GQA serves 4 times as many conversations, at nearly no quality cost (Ainslie et al., 2023).
Time, serving's second cost. Each new token runs the whole model forward once (S20). That takes arithmetic, and it takes reading every weight from the GPU's memory. For \(N\) parameters in fp16, on an A100:
| per token | how much | the A100's rate | an 8B model |
|---|---|---|---|
| arithmetic | about \(2N\) floating-point operations (FLOPs; S18) | \(312\times10^{12}\) FLOP/s at peak (S18) | 0.05 ms |
| reading the weights | \(2N\) bytes | \(2\times10^{12}\) bytes/s, its memory bandwidth (reading 4.4) | 8 ms |
Reading takes about 160 times as long as the arithmetic, so decoding for one conversation is memory-bandwidth-bound.
Decoding for one conversation is limited by reading the weights, not by arithmetic.
Batching: the GPU generates the next token for \(B\) conversations in one forward pass. One read of the weights then serves \(B\) tokens. Each conversation's KV cache is also read at every step, because attention uses every past key and value. The reading's model of one decoding step:
\[\text{step time}=\frac{\text{weight bytes}+B\cdot\text{cache bytes per conversation}}{\text{bandwidth}}\]Each extra conversation adds about 3% to the step time; at about 30 conversations the caches equal the weights, and a step takes twice as long.
Reading 4.4's script applies the previous page's formula to the 8B GQA model, with 4,096 tokens of context (0.5 GiB of cache) per conversation. Each conversation gets one token per step, so the batch produces batch / step_time tokens per second in total, its throughput.
weights_bytes = 2 * 8e9 # 8B model, fp16
kv_per_seq = 131072 * 4096 # 4,096 tokens of GQA cache, 128 KB each
bandwidth = 2.0e12 # 2 TB/s HBM, an A100-80GB-class figure
print(f"{'batch':>6} {'step time':>10} {'per-user tok/s':>15} {'total tok/s':>12} "
f"{'GPU-seconds/1M tok':>19}")
for batch in [1, 2, 4, 8, 16, 32, 64, 128, 256]:
bytes_per_step = weights_bytes + batch * kv_per_seq
step_time = bytes_per_step / bandwidth # seconds per decode step
per_user = 1 / step_time # each user gets 1 token per step
total = batch / step_time
cost = 1e6 / total
print(f"{batch:>6} {step_time*1000:>8.2f}ms {per_user:>15.1f} {total:>12.0f} "
f"{cost:>19.1f}")
Predict with the previous page's formula: from batch 1 to batch 8, how much does the throughput grow, and how much slower does each conversation get?
Answer: the throughput grows about 6.5 times, and each conversation is 19% slower. The printout:
batch step time per-user tok/s total tok/s GPU-seconds/1M tok
1 8.27ms 120.9 121 8268.4
2 8.54ms 117.1 234 4268.4
4 9.07ms 110.2 441 2268.4
8 10.15ms 98.5 788 1268.4
16 12.29ms 81.3 1301 768.4
32 16.59ms 60.3 1929 518.4
64 25.18ms 39.7 2542 393.4
128 42.36ms 23.6 3022 330.9
256 76.72ms 13.0 3337 299.7
The previous page's printout shows two regimes:
"3,300 tokens per second" and "13 tokens per second per conversation" describe the same configuration, so a serving speed means little without its batch size and context length.
(a) A 70B model has 80 layers and 8 key-value heads of 128 floats each, in fp16. How many bytes of KV cache does one token take? How many GiB does a conversation of 131,072 tokens take?
(b) The 8B GQA model has \(16\times10^9\) bytes of weights, and each 8,192-token conversation holds 1 GiB of cache. How many conversations in a batch make the caches together as large as the weights? How long is a decoding step then, compared with one conversation alone?
(a) Per token: 2 (key and value) × 80 layers × 8 heads × 128 floats × 2 bytes = 327,680 bytes, 320 KiB. For 131,072 tokens: 327,680 × 131,072 bytes = 40 GiB.
(b) 1 GiB is \(1.07\times10^9\) bytes, so \(16\times10^9/(1.07\times10^9)\approx15\) conversations. A step then reads twice the bytes, so it takes about twice as long.
(c) A vendor quotes 3,300 tokens per second. What do you ask before trusting your chat app's speed?
(c) At what batch size and context length it was measured, and how many tokens per second each conversation gets.
The KV caches limit how many conversations fit; each added conversation slows the others, and the throughput flattens.
Part 5 · Close. Today's techniques, by the cost each one lowers:
| the cost it lowers | technique | what it saves | what it changes |
|---|---|---|---|
| training | mixed precision | time and activation bytes | the outputs, a little |
| the ZeRO stages | memory on each GPU | stage 3 adds communication | |
| the trained model | quantization | bits per weight | the outputs, a little |
| pruning | the number of weights | the outputs, a little | |
| distillation | the size of the network | the outputs, a little | |
| serving | GQA | cache bytes per conversation | it is a different model, trained with fewer key-value heads |
| batching | GPU time per token | each conversation gets slower |
Every saving comes with a change, so neither the saving nor "no loss" can be claimed without measuring it.
Reading 4.4's list, one mistake per row:
| symptom | cause | fix |
|---|---|---|
| the loss becomes NaN partway through fp16 training | usually overflow past 65,504 to inf, then invalid arithmetic; underflow alone gives zeros, not NaN | find the first non-finite value; autocast with GradScaler, or bf16 |
| a bf16 run's sensitive metric drifts from the fp32 baseline | 2–3 significant digits; sums over many terms accumulate rounding | keep losses, norms and other long sums in fp32 |
| "7B parameters: 13 GiB", but training needs 104 GiB | only the low-precision weights were counted | count all 16 bytes per parameter, then the activations |
| a quantized model's average score is fine, but specific behaviors break | outliers stretch per-tensor scales | per-row scales, or keeping the outlier dimensions in 16 bits (LLM.int8()); evaluate beyond one average score |
| pruned to 90%, storage shrinks, inference speed does not | unstructured zeros still run through dense matrix-multiply routines | structured sparsity your hardware accelerates; measure the running time |
| out of memory in week three of serving, at week one's traffic | longer conversations grow their KV caches | do the KV arithmetic for the longest context and the largest number of conversations |