Session S26

Efficiency & Scale

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

HW4 is due Wednesday, December 9, and Quiz 4 is next session

Welcome back from Fall Recess. Course items first; nothing is due today.

  • HW4 (evaluation and efficiency) went out before the break (S25) and is due Wednesday, December 9, at 11:59 PM Pacific. A 12-hour grace period follows, as for HW1–HW3.
  • Which tasks use which session: Tasks 5–6 (int8 quantization and its error) use today's Part 3. Tasks 2–3 (bootstrap intervals and a paired comparison) use next session (S27, reading 4.5). Tasks 1 and 4 (accuracy and perplexity) need nothing new. HW4 is NumPy only.
  • Quiz 4 is in the final 30 minutes of next session (S27). It covers Module 4, S23–S26, today included.
  • Final report: due Friday, December 11, at 11:59 PM Pacific. Presentation: in class at S28 or S29 (December 7 or 9; sign up through the link in the Canvas announcement), or a recording due with the report.

Today and the next session (S27) are the course's last two sessions of new material.

S25 compared three generative families

S25 closed the generative half of Module 4 with this table (reading 4.3); coverage and fidelity are S24's recall and precision:

familytrainingsamplingstrengthweakness
VAEstable (a likelihood bound)one decoder passa usable latent spaceblur
GANan adversarial gameone forward passsharp samplesunstable training, mode collapse
diffusionstable (regression on noise)many stepscoverage and fidelityslow, iterative sampling
  • Diffusion, S25's answer: the network learns the noise by mean squared error onto a target we drew, which is why training is stable; DDIM skips steps, and 10 network calls lose little against 200.

Diffusion's weakness is the cost of sampling.

Today asks what a model costs to train, to store and to serve

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.

partthe question it answers
1 · Number formatsWhat 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 memoryHow can several GPUs share the training memory? S19 counted 16 bytes per parameter, and three stages split them across GPUs.
3 · Shrinking a modelHow 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 · ServingWhat 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 · CloseA 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.

A float is stored as a sign, an exponent and a mantissa

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:

sign exponent: range mantissa: precision float32 1 8 23 float16 1 5 10 bfloat16 1 8 7 32 bits more precision, less range: max 65,504 keeps fp32's range, gives up precision: about 2–3 significant digits
\[\text{value}=\pm\,1.\text{mantissa}\times2^{\text{exponent}}\]
  • The mantissa's \(m\) bits are the binary digits after the point in \(1.\text{mantissa}\), so it runs from 1 to \(2-2^{-m}\). The exponent is an integer: 5 exponent bits give exponents from −14 to 15, and 8 bits from −126 to 127.
  • bfloat16 is "brain floating point", named for Google Brain, where it was conceived.

fp16's largest number is 65,504; bf16 has fp32's range

Consequences of \(\text{value}=\pm\,1.\text{mantissa}\times2^{\text{exponent}}\), with \(m\) mantissa bits:

  • The exponent sets the range, how large and how small a number can be: bf16 keeps fp32's 8 exponent bits, fp16 has only 5.
  • fp16's largest number is the largest mantissa at the largest exponent, \((2-2^{-10})\times2^{15}=65{,}504\).
  • Its smallest normal number is \(1\times2^{-14}\approx6.10\times10^{-5}\).

fp16 keeps about 3 significant digits, bf16 keeps 2 to 3

  • The mantissa sets the precision: at exponent 0 its smallest step is \(2^{-m}\), so the next number after 1 is \(1+2^{-m}\). That gap, called eps, is \(2^{-23}\) in fp32, \(2^{-10}\) in fp16 and \(2^{-7}\) in bf16.
  • At exponent \(e\) the same step is multiplied by \(2^e\): between \(2^e\) and \(2^{e+1}\) every gap is \(2^e\) times eps.
  • Precision is relative: fp16 keeps about 3 significant digits. It stores 0.000123 as \(1.23\times10^{-4}\), but 1.000123 becomes 1.00.
  • bf16's step is at most \(2^{-7}=1/128\) of the number's size, between 1/100 and 1/1000, so it keeps 2 to 3 significant digits.

Reading 4.4's script stores 70,000 and \(1+2^{-10}\) in each format

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?

fp16 overflows at 70,000; bf16 stores it, but as 70,144

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
  
  • fp16's largest number is 65,504, so 70,000 becomes inf. Arithmetic on inf can give NaN (\(\infty-\infty\), \(0\cdot\infty\)), and every later result computed from a NaN is NaN.
  • bf16 reaches fp32's range with 7 mantissa bits: 70,000 lies between \(2^{16}=65{,}536\) and \(2^{17}\), where bf16's numbers are \(2^{16}\cdot2^{-7}=512\) apart. \(70{,}000/512\approx136.7\), so it rounds to \(137\cdot512=70{,}144\): only the first 2–3 significant digits are kept.
  • Near 1, bf16's numbers are \(2^{-7}\) apart: \(1+2^{-10}\) is an eighth of a step and rounds to 1.

In pure fp16, 2048 + 1 is 2048, so training loses small updates

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.

adjacent fp16 numbers near 2048 are 2 apart 2048 2050 2048 + 1 = 2049.0 in fp32 fp16: 2048.0 2 An update of 1 is lost.
  • In general: an update smaller than half the gap at the weight is always lost. In fp16 half the gap is at most \(2^{-11}\), about 0.05%, of the weight, and a learning rate times a gradient is often smaller than that.

…and a gradient of \(10^{-8}\) rounds to 0, unless the loss is scaled

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.

a gradient of 1e-8 in fp16 rounds to 0 subnormal normal 2−25 ≈ 2.98 × 10−8 6.10 × 10−5 1e-8 → 0.0 1.025e-05 × 1024 (loss scaling) log scale
  • In fp16 this gradient is stored as 0, so that parameter stops learning.
  • Times 1024 it is \(1.024\times10^{-5}\), stored as \(1.025\times10^{-5}\), the nearest multiple of \(2^{-24}\).

Mixed precision keeps an fp32 master copy and scales the loss

One mixed-precision training step (Micikevicius et al., ICLR 2018), its four steps numbered:

fp32 master copy of the weights ① cast ② forward in 16-bit; loss × 1024, then backward in 16-bit ③ 16-bit gradients ④ in fp32: unscale (÷ 1024), then update the fp32 copy

A mixed-precision step computes in 16-bit and updates in fp32

The four steps of the previous page's figure:

  1. Cast the fp32 master copy of the weights to 16-bit.
  2. Forward in 16-bit, for speed. Multiply the loss by \(S=1024\), then run the backward pass in 16-bit.
  3. The 16-bit gradients are \(S\) times the true gradients, since \(\partial(SL)/\partial w=S\,\partial L/\partial w\). A gradient of \(10^{-8}\) is stored as \(1.025\times10^{-5}\), not 0.
  4. Unscale and update, both in fp32: divide the gradients by \(S\), then update the fp32 copy. fp32 stores \(10^{-8}\), and 2048 + 1 is 2049 there.

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.

PyTorch: 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
  
  • Outside the block, each backward operation still runs in the type its forward used.
  • 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.

Self-check on number formats, questions (a) and (b)

(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.

Self-check on number formats, question (c)

(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.

S19 counted 16 bytes per trained parameter, 104.3 GiB for a 7B model

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:

per parameter weights grads master Adam m Adam v fp16: 2 + 2 fp32 optimizer state: 4 + 4 + 4 = 12 16 bytes, so 16N in all
  • Optimizer state is 12 of the 16 bytes: the fp32 master copy and Adam's moments \(m\) and \(v\) (S06). For \(N\) parameters, \(2N+2N+12N=16N\) bytes.
  • Training a 7B model: \(7\times10^9\times16\) bytes is 104.3 GiB (1 GiB is \(1024^3\) bytes).
  • Inference keeps only the 2-byte weights: \(7\times10^9\times2\) bytes is 13.0 GiB.

Training holds 8 times the weights' bytes, and optimizer state is 12 of the 16.

Data parallelism puts all 16 bytes on every GPU, so it saves no memory

Plain data parallelism (plain DP) trains one model on \(P\) GPUs; PyTorch's version is DistributedDataParallel (DDP). Per trained parameter, each GPU holds:

weights grads optimizer state GPU 1 GPU 2 GPU P ⋮ full copy on every GPU, 16 bytes per parameter each
  • Each of \(P\) GPUs takes a slice of the batch, and the GPUs average their gradients (an all-reduce) before each step.
  • The copies raise throughput but save no memory.

With plain DP, each GPU still needs the full 104.3 GiB for the 7B model.

ZeRO's three stages shard the optimizer state, then the gradients, then the weights

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.

per GPU, with P GPUs plain DP full copy on every GPU, no memory saved ZeRO-1 ÷ P shards the optimizer state: each GPU updates 1/P of the weights ZeRO-2 ÷ P + the gradients: each GPU keeps its 1/P ZeRO-3 ÷ P + the weights, gathered just in time weights grads optimizer state
bytes per parameter, per GPUplain DPZeRO-1ZeRO-2ZeRO-3
with \(P\) GPUs16\(4+12/P\)\(2+14/P\)\(16/P\)
with \(P=8\)165.53.752

With 8 GPUs, the three stages cut 16 bytes per parameter on each GPU to 5.5, 3.75 and 2.

A 7B model needs 104.3 GiB on one GPU, 13.0 GiB per GPU at ZeRO-3 on 8

GiB per GPU is the previous page's bytes per parameter \(\times\,7\times10^9\,/\,1024^3\):

7B modeltraining on 1 GPUZeRO-1, 8 GPUsZeRO-2, 8 GPUsZeRO-3, 8 GPUs
bytes per parameter, per GPU165.53.752
GiB per GPU104.335.924.413.0
fp16 weights fp16 gradients fp32 optimizer state inference only 13.0 GiB training, 1 GPU 104.3 GiB: 8× inference ZeRO-1, 8 GPUs 35.9 GiB per GPU ZeRO-2, 8 GPUs 24.4 GiB per GPU ZeRO-3, 8 GPUs 13.0 GiB per GPU one 80 GB GPU Activations, communication buffers and fragmentation come on top of every bar; the dashed line is 80 GiB.

ZeRO-3 on 8 GPUs holds \(16/8=2\) bytes per parameter on each GPU, 13.0 GiB: the same as inference.

Stage 3 costs communication, and these numbers are a lower bound

Training takes 8 times the memory of inference before a single activation is stored.

  • Stage 3 costs communication: stages 1 and 2 send no more data than plain DP, but stage 3 gathers each layer's weights just before that layer's forward and backward pass, every step. PyTorch's FSDP (Fully Sharded Data Parallel) implements stage 3.
  • A lower bound, not a prediction: activations come on top and grow with batch size and sequence length (S19); the GPU runtime and communication add more. Leave real margin, or use activation checkpointing, which recomputes activations during the backward pass.
  • LoRA (S19): with 99.9% of the parameters frozen, the \(12N\) of optimizer state applies only to the adapters: a 7B model then needs about 13 GiB (S19), and the ZeRO stages become unnecessary.

Use the lowest ZeRO stage that fits in memory, and leave margin: these numbers exclude activations.

Self-check on training memory, questions (a) and (b)

(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.

Self-check on training memory, question (c)

(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.

One scale \(s\) maps every weight to an integer from −127 to 127

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):

  1. Scale: \(s=\max_i\lvert W_i\rvert/127\), one floating-point number for the whole tensor, so the largest weight maps to \(\pm127\).
  2. Store \(q_i=\operatorname{round}(W_i/s)\), one byte each, and \(s\): 4× smaller than fp32.
  3. Use \(\hat W_i=q_i\,s\), computed from \(q\) when needed and never stored. The values \(q\,s\) are multiples of \(s\), a grid with spacing \(s\), so each weight is off by at most \(s/2\).
\(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 errors

Reading 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.

One outlier among 65,536 weights turns a 1% error into 21.7%

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
  
  • Well-behaved: the largest weight error, 0.00090, is \(s/2\), so \(s=0.0018\); \(\hat WX\) is about 1% off (0.01032).
  • Outlier: \(s=5.0/127=0.039\), about 22 times the 0.0018 above: 21.7%. One scale per row (the printout's per-channel) leaves only row 0 coarse: 1.5%.

Per tensor, the outlier coarsens every grid; per row, only its own

The previous page's three cases, with each int8 grid point drawn:

the ordinary weights (all but one) relative matmul error well-behaved W, per-tensor scale about 1% one outlier (5.0), per-tensor scale → 5.0 21.7% one outlier (5.0), per-row scales row 0 the other 255 rows 1.5% Each tick is an int8 grid point, drawn to scale from the experiment's code (seed 0).
  • The same problem appears in activations, which int8 inference also rounds: from about 6.7B parameters up, every transformer layer has a few activation dimensions far larger than the rest (Dettmers et al., 2022). Their method, LLM.int8(), keeps those in 16 bits.
  • Later 4-bit methods, such as QLoRA's NF4 (S19), store 0.5 bytes per weight: \(7\times10^9\times0.5\) bytes is about 3.3 GiB, a quarter of the 13.0 GiB at 16 bits.

Pruning sets the smallest weights to zero, then retrains the rest

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.

① train ② threshold ③ prune (once) ④ retrain many steps, same mask
  1. Train the network as usual.
  2. Threshold: choose a sparsity, the fraction of weights to remove. The threshold is that quantile of the weights' magnitudes: this fraction of the weights lies below it.
  3. Prune, once: build a 0/1 mask, 0 where a weight's magnitude is below the threshold, and multiply the weights by it.
  4. Retrain the remaining weights for many steps (the code calls it a fine-tune). Each step also changes the zeroed weights, so the same mask is multiplied in again after each step.

The experiment prunes a small network with a global or a per-layer threshold

  • Reading 4.4's experiment: a 2 → 64 → 64 → 2 ReLU network trained on two interleaved moons, 99.0% test accuracy, \(2\cdot64+64\cdot64+64\cdot2=4{,}352\) weights.
  • It prunes that network to a sparsity, then retrains the remaining weights for 200 steps.
  • The threshold is computed in one of two ways:
schemehow the weights are rankedfraction removed from each layer
globalall weights together, with one thresholdcan differ from layer to layer
per-layereach layer's weights separately, with one threshold per layerthe same in every layer

Pruning removes weights by magnitude; the choice is where the threshold is computed.

The data are 2,000 training and 1,000 test points of two moons

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)
  

After 1,500 steps, the network gets 99.0% of the test points right

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 two schemes differ only in where the threshold is computed

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?

After pruning, 200 training steps retrain the remaining 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%}")
  

At 90%, the global threshold strips the output layer; in this run, all of it

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%
  
  • 50% and 80% (this run): at 50%, pruning costs no accuracy; at 80% accuracy falls, and 200 retraining steps bring both schemes within a point of the baseline (0.9840, 0.9890).
  • 90% and 95%: none of the 128 output weights is among the largest 10% of all 4,352, so the global threshold zeroes that layer. Both logits are then biases, the same for every input: all test points get one class, 0.5000, and the masks keep it so in the retraining. Per-layer keeps 10% of each layer: 0.87, then 0.89, a real loss.

A tensor full of zeros is not automatically faster

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:

unstructured: zeros anywhere saves storage, runs at dense speed 0 0 0 0 0 0 0 0 2:4: two zeros in every four accelerated on recent NVIDIA GPUs 0 0 0 0 0 0 0 0
  • Unstructured sparsity puts zeros at arbitrary positions, as in the experiment. It saves storage once the matrix is stored in a sparse format (only the nonzero values and their positions), and it saves time only where specialized sparse routines apply.
  • Structured sparsity removes whole neurons or channels, or keeps the 2:4 pattern that recent NVIDIA GPUs accelerate natively. At the same sparsity it usually costs more accuracy, because the pattern limits which weights can be dropped.

A sparsity number says little about speed without its structure and the hardware it was measured on.

For large language models, quantization is used far more than pruning

  • Retraining a pruned model at that scale is expensive. A pruned network has to be retrained: in the experiment, 80% per-layer pruning left 0.7230, and 200 retraining steps brought back 0.9890.
  • Unstructured zeros give no speed-up on dense matrix-multiply routines (the previous page).
  • 4-bit quantization already stores a quarter of the bytes with no retraining: 3.3 GiB against 13.0 GiB at 16 bits for a 7B model.

Distillation trains a small student to match a large teacher's outputs

Quantization and pruning change one network's numbers; distillation trains a different, smaller network.

7 large teacher small student 7 2 0 soft targets 7 2 0 7 most, 2 some, 0 almost none matched after softening both logit sets with T > 1 7 2 0 a hard label: only 7 Schematic: bar heights are illustrative, not measured.
  1. Train the teacher, the large network, and then leave it unchanged.
  2. Soften: for each training example, divide the teacher's and the student's logits by a temperature \(T>1\) and apply softmax, \(p^{T}=\operatorname{softmax}(z/T)\). The teacher's softened outputs are the soft targets (Hinton, Vinyals & Dean, 2015).
  3. Train the student on a weighted average of two cross-entropy losses, one against the soft targets and one against the hard label \(y\), with a weight \(\alpha\) between 0 and 1:
\[L=\alpha\,T^{2}\,\mathrm{CE}\!\left(p^{T}_{\text{teacher}},\ p^{T}_{\text{student}}\right)+(1-\alpha)\,\mathrm{CE}\!\left(y,\ p_{\text{student}}\right)\]

A temperature above 1 makes the teacher's small probabilities large enough to learn from

  • The soft targets say more than the hard label. The hard label says only 7. On a 7 the teacher also gives a 2 some probability and a 0 almost none, so its outputs say that a 7 resembles a 2 more than a 0.
  • Softened with S20's temperature: \(p_i/p_j=e^{(z_i-z_j)/T}\), so a logit gap of 8 gives a ratio of \(e^{8}\approx2981\) at \(T=1\) but \(e^{2}\approx7.4\) at \(T=4\): the second class is then large enough for the student to learn from.
  • The factor \(T^{2}\) is there because the gradients of the soft-target loss scale as \(1/T^{2}\); the hard-label loss uses \(T=1\).
  • DistilBERT (Sanh et al., 2019): reported 40% smaller and 60% faster than BERT (S17's encoder-only model), with about 97% of its language-understanding performance.

Self-check on shrinking a model, questions (a) and (b)

(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.

Self-check on shrinking a model, question (c)

(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.

Serving keeps one copy of the weights and one KV cache per conversation

Part 4 · Serving. A trained model on a GPU generates text for many users at once.

weights, stored once, shared by every conversation one GPU's memory free one KV cache per conversation, growing with every token
  • Memory limits how many conversations fit: the weights take a fixed part, and each conversation's KV cache (S20) takes more as the conversation gets longer.
  • Time limits how fast each conversation gets its next token: every generated token needs a pass over all the weights.

Serving has two costs: memory per conversation and time per token.

The KV cache stores \(2\cdot L\cdot H_{\text{kv}}\cdot d_{\text{head}}\) floats 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:

query heads keys, cached values, cached multi-head attention (MHA) grouped-query attention (GQA) per layer and token: 2 × 32 × 128 = 8,192 floats per layer and token: 2 × 8 × 128 = 2,048 floats × 32 layers × 2 bytes: 524,288 bytes per token × 32 layers × 2 bytes: 131,072 bytes per token Each block is one head of 128 floats. In GQA, 4 query heads read one shared key head and value head.
  • Multi-head attention (MHA, Llama-2-7B-like): \(L=32\), \(H_{\text{kv}}=32\), \(d_{\text{head}}=128\), fp16: \(2\cdot32\cdot32\cdot128\cdot2=524{,}288\) bytes. Here \(32\cdot128=4096\) is the width \(d\).
  • Grouped-query attention (GQA; Ainslie et al., 2023) caches 8 key-value heads. Each is shared by 4 query heads, which keep their own queries: 4 times fewer bytes.

At 128k tokens, one MHA conversation's cache is five times the weights

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.

An 80 GB GPU holds 16 MHA conversations of 8k tokens, or 65 with GQA

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)
  
fp16 weights one 8,192-token sequence's KV cache 7B, MHA 16 sequences 8B, GQA 65 sequences 0 20 40 60 80 GiB

GQA serves 4 times as many conversations, at nearly no quality cost (Ainslie et al., 2023).

Each token reads every weight once, so memory bandwidth sets the speed

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 tokenhow muchthe A100's ratean 8B model
arithmeticabout \(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 reuses each weight read, so extra conversations add little time per step

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}}\]
  • The 8B GQA model in fp16: \(2\times8\times10^9=16\times10^9\) weight bytes. Its cache at 4,096 tokens, 0.5 GiB per conversation, is \(0.5\times1024^3=0.54\times10^9\) bytes.
  • One conversation: \((16+0.54)\times10^{9}/(2\times10^{12})\approx8.27\) ms per step. Each further conversation adds \(0.54\times10^9\) bytes, 0.27 ms, about 3% of that step.

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.

The simulation applies the step-time formula to batches of 1 to 256

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?

From batch 1 to 8, throughput grows 6.5× and each conversation slows 19%

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
  
total tokens per second 0 1,000 2,000 3,000 1 2 4 8 16 32 64 128 256 121 788 3,337 tokens per second for each conversation 0 50 100 1 2 4 8 16 32 64 128 256 120.9 98.5 13.0 batch size (log scale). Blue: batch 1–8, mostly weight bytes; orange: 64–256, mostly cache bytes; dashed: equal, near 30.

The provider wants total throughput; each user wants a fast conversation

The previous page's printout shows two regimes:

  • Batch 1 to 8: the batch shares weight reads that had to happen anyway.
  • Batch 256: the caches, \(256\times0.5=128\) GiB, are about 8.6 times the weights' 14.9 GiB. Throughput flattens, and each conversation gets 13 tokens per second.
  • Cost per million tokens falls 28-fold across the table: the provider wants the largest batch users will tolerate, and users want the reverse.
  • What the model leaves out: whether the caches fit (128 GiB does not fit on one 80 GB GPU; reading 4.4's Try it yourself #6 adds that limit) and processing the prompt before the first new token (prefill), which is compute-bound (reading 4.4).

"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.

Self-check on serving, questions (a) and (b)

(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.

Self-check on serving, question (c)

(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.

What each technique saves, and what it changes

Part 5 · Close. Today's techniques, by the cost each one lowers:

the cost it lowerstechniquewhat it saveswhat it changes
trainingmixed precisiontime and activation bytesthe outputs, a little
the ZeRO stagesmemory on each GPUstage 3 adds communication
the trained modelquantizationbits per weightthe outputs, a little
pruningthe number of weightsthe outputs, a little
distillationthe size of the networkthe outputs, a little
servingGQAcache bytes per conversationit is a different model, trained with fewer key-value heads
batchingGPU time per tokeneach conversation gets slower

Every saving comes with a change, so neither the saving nor "no loss" can be claimed without measuring it.

Six mistakes in your own runs, each with its cause and its fix

Reading 4.4's list, one mistake per row:

symptomcausefix
the loss becomes NaN partway through fp16 trainingusually overflow past 65,504 to inf, then invalid arithmetic; underflow alone gives zeros, not NaNfind the first non-finite value; autocast with GradScaler, or bf16
a bf16 run's sensitive metric drifts from the fp32 baseline2–3 significant digits; sums over many terms accumulate roundingkeep losses, norms and other long sums in fp32
"7B parameters: 13 GiB", but training needs 104 GiBonly the low-precision weights were countedcount all 16 bytes per parameter, then the activations
a quantized model's average score is fine, but specific behaviors breakoutliers stretch per-tensor scalesper-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 notunstructured zeros still run through dense matrix-multiply routinesstructured sparsity your hardware accelerates; measure the running time
out of memory in week three of serving, at week one's trafficlonger conversations grow their KV cachesdo the KV arithmetic for the longest context and the largest number of conversations

Today's answer takes the title page's question clause by clause

  • 16-bit numbers: fp16 has more precision and less range (largest 65,504); bf16 keeps fp32's range and gives up precision. Training copes with an fp32 master copy, loss scaling and 16-bit passes; bf16 needs no loss scaling.
  • Training memory: mixed-precision Adam keeps 16 bytes per parameter (S19), 12 of them optimizer state, so a 7B model needs 104.3 GiB, 8 times inference. ZeRO shards them across GPUs, 13.0 GiB each at stage 3 on 8, and stage 3 costs communication.
  • Shrinking: int8 is 4 times smaller than fp32; in the experiment it cost about 1% error, unless one outlier coarsened the grid (21.7%; per row, 1.5%). Pruning removed half of this network's weights at no cost in accuracy; it saves time only when structured, and large language models are mostly quantized instead. Distillation trains a smaller network.
  • Serving: each conversation's KV cache limits how many conversations fit; reading the weights limits the speed. Batching shares each read: the throughput grows, each conversation slows, and the total flattens once the caches exceed the weights.

For next time

  • Next session (S27): evaluating models honestly, and safety. Read: 4.5 Evaluating Models Honestly and 4.6 Safety, Bias, and Responsible Release.
  • S28 and S29 are in-class project presentations; students who are not presenting need not attend.
  • CS 5715: all four paper responses are due Friday, December 4, at 11:59 PM Pacific.
  • Optional: reading 4.4's Try it yourself #4, the memory arithmetic of LoRA fine-tuning for a 7B model.