A 7B model's weights take 3.4 GB in 4 bits instead of 13.4 GB, so decoding can run about 4 times faster. AWQ does it for a perplexity cost of 0.13.
Learn how to make a large language model small, sparse and fast enough to serve: quantization, pruning, paged memory, batching and speculation.
Pick a bit width and a method. Watch memory, the speed ceiling and the quality loss move together. Then we build, piece by piece, every trick that makes the trade work.
You need a little linear algebra (a matrix times a vector) and a little Python for the code. We build the rest from zero.
Based on Lecture 13 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Course page and slides. Every idea is re-taught here in our own words and devices. It follows Lecture 12 and leads to Lecture 14.
Perplexity (lower is better) is Llama-2 7B with group size 128, from the AWQ paper table shown in the lecture. Memory is 6.7 billion weights times the bits, without the small scale tables. The speed ceiling divides an illustrative 1 TB/s of memory bandwidth (about an RTX 4090) by the bytes read per token.
Chapter 0
See why a model that fits in the lab does not fit in the product, and learn the one trick every later chapter uses: store fewer bits
A 7B language model in 16 bits is a 13.4 GB file. A laptop GPU with 8 GB cannot load it. Serving it to ten thousand people adds a growing chat history for each.
The lecture closes the gap in three parts. Quantization stores each number in fewer bits. Pruning and sparsity skip numbers the input does not need. Serving systems run many users on one machine without waste.
A weight usually takes 16 bits (FP16, a 16-bit floating-point number): about 65,000 patterns. Four bits allow 16. Quantization snaps each value to the nearest allowed level, like rounding prices to the dollar.
Take one group of weights and its bit width N. The gap between two levels is the step, Δ, set by the largest weight. The value the integers give back for a weight w is Q of w:
Q of w equals delta times round of w over delta, where delta equals the max of absolute w, over 2 to the N minus 1.
Divide the largest weight by 2 to the N minus 1 to get delta. Divide each weight w by delta, round, and store the integer. To use it, multiply by delta.
The made-up group (0.12, −0.25, 0.30, 0.90) at 4 bits has delta = 0.90 / 8 = 0.1125. Divided: 1.07, −2.22, 2.67, 8.00. Rounded: 1, −2, 3, and 8 clips to 7. Back: 0.1125, −0.225, 0.3375, 0.7875. The worst miss is 0.1125, on the clipped weight.
Four 16-bit numbers (64 bits) go in. Four 4-bit integers and one 16-bit step (32 bits) come out. The general form also has a zero point, the integer that stands for 0. This lecture sets it to 0.
Hollow dots are the original weights. Ticks are the levels the integers allow. Filled dots are the rounded weights. Lower the bits and the ticks spread out.
Toy weights made up for this lesson: −0.9, −0.55, −0.31, −0.12, 0.05, 0.2, 0.38, 0.62, 0.9. The outlier toggle replaces the last weight with 9.0, to show what one big number does to the step size.
Symptom: a 4-bit model outputs nonsense. Measure: put 9.0 in the group instead of 0.90. Delta becomes 9.0 / 8 = 1.125, and 0.12, −0.25 and 0.30 all round to 0. Fix: do not let one number set the grid for the rest.
| Tag | What it counts | Changes while the model runs? |
|---|---|---|
| W, weights | Numbers learned in training | No |
| A, activations | Numbers that flow from one layer to the next | Yes, with every prompt |
| KV, the KV cache | Stored keys and values of earlier tokens (Lecture 12) | Yes, it grows by one token each step |
So W4A16 means 4-bit weights and 16-bit activations. It turns the integers back into 16-bit numbers before it multiplies, so it saves memory, not arithmetic. W8A8 multiplies integers in fast 8-bit hardware, so both sides must be integers.
Chapter 1
Find the few giant numbers that break 8-bit activations, then trade them into the weights, which can take it
In 2024, W8A8 was standard for image networks but failed on language models. In plain W8A8, OPT accuracy tracks 16-bit up to 2.7B parameters, then falls to about 40 percent at 6.7B and 33 beyond.
The cause is systematic outliers in the activations. A channel is one column of the activation table. A few channels reach about 70 while weights stay tame, and they are the same channels every time.
Divide an activation column by 4 and multiply its weight row by 4: the product stays the same. Call the activations X, the weights W, the output Y, and channel j's smoothing factor sj.
Y equals X times diag of s inverse, times diag of s times W, which equals X-hat times W-hat.
Divide activation channel j by s-j and multiply weight row j by s-j. They cancel, so Y stays the same before rounding.
The slide's outlier column (−16, 8, 16) with s = 4 becomes (−4, 2, 4), and its weight row (1, −1, −1) becomes (4, −4, −4). Token 1 gives −16 × 1 = −16 before and −4 × 4 = −16 after.
Each factor mixes the channel's two peaks. The migration strength α, from 0 to 1, sets the mix.
S-j equals the max of absolute X-j to the alpha, over the max of absolute W-j to the one minus alpha.
Raise the activation peak to alpha, the weight peak to one minus alpha, and divide.
The slide's peaks are (2, 16, 2, 9) for X and (2, 1, 2, 1) for W. At alpha 0.5, s = (1, 4, 1, 3). The top activation falls from 16 to 4, and the top weight rises from 1 to 4.
Calibration records the activation peaks offline on a few prompts. Smoothing scales the weight rows and folds 1/s into the LayerNorm before. FasterTransformer then runs Linear layers and BMM (batched matrix multiply) in INT8, the rest in FP16.
Top: the biggest value in each channel, for activations (left) and weights (right). Bottom: the output error for every α, with a dot at yours.
Illustrative: a seeded random layer whose channels 3 and 11 are about 40 times louder, with one scale for all of X̂ and one for all of Ŵ. Real outliers are bigger, so the paper's effect is larger.
The slide's OPT-175B ablation keeps W8A8 accurate only for α from 0.4 to 0.6.
| Measure | FP16 | SmoothQuant |
|---|---|---|
| LAMBADA accuracy: OPT-175B, BLOOM-176B, GLM-130B | 71.6, 68.2, 73.8 % | 71.2, 68.3, 73.7 % |
| OPT-175B memory, sequence 1,024 | 389 GB on 8 GPUs | 200 GB on 4 GPUs |
| OPT-175B latency, sequence 1,024 | 848 ms | 720 ms |
| LLaMA Wikitext perplexity, 7B and 65B | 11.51 and 6.17 | 11.56 and 6.20 |
Symptom: you calibrate on English, serve code, and accuracy drops. Measure: the outlier channels are fixed but their size varies, so one can pass its calibrated peak and clip. Fix: calibrate on text like your traffic.
pythondef smooth_scales(x_absmax, w, alpha=0.5): # x_absmax (C,) from calibration; w (C, out) w_absmax = w.abs().amax(dim=1) # biggest weight in each input channel, (C,) s = x_absmax.pow(alpha) / w_absmax.pow(1 - alpha) # s_j from the slide return s.clamp(min=1e-5) # offline: ln.weight /= s ; ln.bias /= s ; w *= s[:, None]
Chapter 2
Measure why one user at a time cannot use the chip, and see why weight-only quantization wins there
SmoothQuant made 8-bit activations work. For one user at a time, 8 bits is still not enough. The slide title says why: decoding is highly memory-bound, W8A8 is not enough.
A GPU has two limits. Compute is operations per second: 312 trillion for an A100 in FP16. Memory bandwidth is bytes per second: about 2 trillion. Arithmetic intensity is operations per byte moved. A job with low intensity is memory-bound: the chip waits for bytes. A job with high intensity is compute-bound.
Each decode step multiplies every weight matrix by one vector. In FP16 that is 2 bytes and 2 operations per weight (a multiply and an add), so the intensity is 1. The A100 needs 312 / 2 = 156 operations per byte to stay busy.
With b users, the chip reads the weights once and uses them b times, so the intensity becomes b. The slide's roofline (LLaMA-65B decoding on an A100) puts batch 1 far down the memory slope and batch 128 near the compute roof. W8A8 suits batch 128. A local user has batch 1.
The RTX 4090 slide measures it. A 200-token prompt takes 10 ms, but 20 generated tokens take 310 ms. An attention layer holds 134 MB of weights and 1.69 MB of activations. A feed-forward layer holds 271 MB and 0.2 MB. So the cure is W4A16, or weight-only quantization: 4-bit weights in groups of 128 that share one scale.
A 7B model on an A100, with 2 TB/s and 312 TFLOPS:
Each bar is the tokens per second all users get together. The label says which limit binds. Slide the batch from 1 user to 256.
Illustrative: a 7B model on an A100 with 2 TB/s, 312 TFLOPS (FP16 activations) and 624 TOPS (INT8 activations), figures read from the lecture's roofline slide. It ignores the KV cache, attention, dequantization cost and kernel overhead, so real numbers are lower.
At batch 1 every bar is memory-bound and W4A16 wins. Near 39 users W4A16 meets its 16-bit compute roof, but it leads up to about 64. At 128, W8A8 wins with faster 8-bit arithmetic. Chapter 5 combines the two.
Symptom: a team ships W8A8 for an on-device assistant and users still wait. Measure: at batch 1, W8A8 reads 7 GB per token (3.5 ms) and W4A16 reads 3.5 GB (1.75 ms). Fix: use 4-bit weights for single-query use. Keep W8A8 for large batches.
Chapter 3
Learn why 1 percent of weight channels carry the quality, and protect them by scaling instead of mixed precision
AWQ (Activation-aware Weight Quantization, Lin et al., MLSys 2024) targets group-wise W4A16: runs of 64, 128 or 256 weights share one scale. Plain round-to-nearest (RTN) still hurts. On OPT-6.7B at 3 bits, perplexity (lower is better) rises from 12.29 to 43.16.
Keep 1 percent of the weight channels in 16 bits, picked by activation size, and perplexity falls to about 13. Picked by weight size, it only reaches about 38. A weight matters when its activation is large.
Mixed precision is slow, so AWQ scales instead. It multiplies a salient channel's weights by s before rounding and divides its activation by s, folded into the operation before.
A rounding miss averages a quarter of the group's step Δ. Scaling keeps the grid, so dividing by s shrinks the miss. With x the activation:
The error is about 0.25 times delta times x, over s.
Take a quarter of delta, multiply by x, divide by s. It holds while s leaves the group's largest weight, and so delta, alone.
Made-up: a largest weight of 0.40 at 4 bits gives delta 0.05; take x = 30. At s = 1 the error is 0.25 × 0.05 × 30 = 0.375. At s = 2 it is 0.19.
If s makes the scaled weight the group's largest, Δ grows and every other channel loses. So AWQ searches an exponent α over each channel's average activation size sX:
S equals s-X to the alpha. Alpha-star is the alpha that minimizes the norm of Q of W s, times s inverse X, minus W X.
For each alpha, round the scaled weights, run the calibration activations, and measure the error against W X. Keep the best alpha.
The slide tries three scales on OPT-6.7B at 3 bits: 1.5 times gives perplexity 14.49, 2 times 14.07, 4 times 14.42, against 43.16 for RTN. The middle one wins.
Top: one row of scaled weights, with the protected channels in purple and a dashed line at the group's biggest weight. Bottom: the output error against s for each way to pick channels.
Illustrative: seeded heavy-tailed weights, one 4-bit group of 128, 200 random activation vectors, two channels 30 times louder. Error is the output's relative RMS error. The shape matches the slide's OPT-6.7B result; the numbers are the toy's own.
| Group 128 (Llama-2 7B rows: perplexity) | FP16 | RTN | GPTQ | AWQ |
|---|---|---|---|---|
| INT4 | 5.47 | 5.73 | 5.69 | 5.60 |
| INT3 | 5.47 | 6.66 | 6.43 | 6.24 |
| VILA-7B and 13B, 12-benchmark average (higher is better), INT4 | 65.7 and 68.4 | not shown | not shown | 65.2 and 68.2 |
AWQ needs less calibration data, since it does not fit weights to the data.
Symptom: you push s to 8 and perplexity gets worse. Measure: in the device, the error at s = 8 is near the unscaled error, because the scaled weights set the step. Fix: let the output error choose α.
pythondef awq_search(w, x, n_grid=20): # w (out, C) weights, x (T, C) calibration activations x_mean = x.abs().mean(0) # s_X: mean activation size per channel, (C,) best, best_s = 1e30, None for i in range(n_grid): alpha = i / n_grid s = x_mean.pow(alpha).clamp(min=1e-4) wq = quantize_groupwise(w * s, bits=4, group=128) / s # Q(W s) s^-1 err = ((x @ wq.T) - (x @ w.T)).pow(2).mean() # error of the OUTPUT if err < best: best, best_s = err, s return best_s
Chapter 4
See how packing, fusion and a small engine turn saved bytes into saved milliseconds on a laptop and a Jetson
A chip does not multiply 4-bit numbers directly. It unpacks them, converts them to FP16, then multiplies. If unpacking is slow, it eats the saved memory time. TinyChat is the lecture's inference engine for the edge: the program that loads weights, runs kernels (routines on the chip) and makes tokens.
The slide lists its aims: lightweight, efficient, Python-native (it composes with stacks such as vLLM) and multi-platform, from cloud GPUs to phone CPUs. Running on the edge buys privacy, work with no network, and personalization.
A 128-bit SIMD register (single instruction, multiple data) holds 32 four-bit weights. Packed in order, byte 0 holds w0 and w1, so unpacking splits even from odd weights and needs extra shuffles. TinyChat reorders offline: byte k holds wk in its low half and wk+16 in its high half. Three logical operations then decode all 32 in order:
The reorder costs once. The saving repeats every token: 1.2 times faster on ARM NEON, says the slide.
Top: sixteen bytes, each with two four-bit weights (high half above, low half below). Below: the two result vectors. Pick a layout, then run the operations one at a time.
Illustrative: weight indices 0 to 31 stand for any 32 weights. The three operations are the ones on the lecture slide. The shuffle count for the in-order layout is this toy's count of extra work, not a figure from the paper.
Kernel fusion runs several steps in one kernel, so in-between results never reach slow memory. In attention, BMM, softmax and BMM run as one kernel. In the matrix multiply, INT4 weights become FP16 in registers and never go back to DRAM. For one 4,096 by 4,096 layer at one token:
Does a 7B model fit a board with 7 GB free? FP16 needs 6.7 billion × 2 bytes = 13.4 GB. Four bits need 3.35 GB, and the scales 0.1 GB more: 3.45 GB, with 3.5 GB left.
| Where | What the slides show |
|---|---|
| RTX 4090, RTX 4070 laptop, Jetson Orin | More than 3 times faster than Huggingface FP16. Models that ran out of memory in FP16 now run. |
| Jetson Orin | At least 2.6 times faster than AutoGPTQ, more flexible than llama.cpp and exllama. |
| Llama-3-VILA1.5-8B, tokens/s | A100 74.9 to 168.9, RTX 4090 57.4 to 150.2, Orin 10.2 to 28.7. |
| VILA1.5-13B on an RTX 4090 | Out of memory in FP16, 105.7 tokens/s in AWQ INT4. |
| Demos | A 7B model on a Jetson Orin Nano with about 7 GB free. VILA-7B on a MacBook ARM CPU. |
| Adoption | 19 million downloads of AWQ models on HuggingFace. Used in TensorRT-LLM, vLLM, the HuggingFace quantization API, LMDeploy, FastChat, Intel Neural Compressor, Google Vertex AI and IBM's Granite. |
Symptom: the 4-bit model fits but runs no faster. Measure: a profile shows the chip busy with unpack and shuffle instructions, not waiting for memory. Fix: reorder the packed weights offline, and fuse dequantization into the matrix multiply.
pythonimport numpy as np def pack_reordered(w4): # w4: (32,) uint8 values 0..15 -> (16,) uint8 bytes return (w4[16:] << 4) | w4[:16] # byte k = w[k+16] high, w[k] low def unpack(p): # the 3 logical operations low = p & 0x0F # w0..w15, in order high = (p >> 4) & 0x0F # w16..w31, in order return np.concatenate([low, high]) # (32,), no shuffle needed
Chapter 5
Follow the cloud and the edge to their different settings, then see how one design takes the best of both
The cloud and the edge use different settings. QServe (W4A8KV4) takes the best of both. A scale serves a tensor, a channel, a token's row or a group of 128.
| Recipe | Weights | Activations | KV cache |
|---|---|---|---|
| Cloud, W8-A8-KV8 | 8-bit, per channel | 8-bit, per token | 8-bit, per tensor |
| Edge, W4-A16-KV16 | 4-bit, per group of 128 | FP16 | FP16 |
| QServe, W4-A8-KV4 | 4-bit | 8-bit | 4-bit |
Take batch b and bits per weight w. A weight costs w / 8 bytes and does b multiply-adds (2b operations). The bandwidth is 2 TB/s:
Perf equals the min of peak, and 2 terabytes per second times 16 b over w.
Multiply the bandwidth by the operations per byte for the memory slope. The smaller of that and the peak is the speed.
At b = 128: FP16 reaches 256 TOPS, W8A8 min(624, 512) = 512, W4A16 its 312 roof, and W4A8 min(624, 1,024) = 624. W4A8 has the slope of 4-bit weights and the roof of 8-bit arithmetic.
Four curves show the TOPS each setting can reach at each batch size. The vertical line is your batch. Slide it and read the four numbers.
Idealized A100 numbers from the lecture's roofline slide. It ignores dequantization cost (next section), so real W4A16 and W4A8 curves sit lower.
W4A4 loses accuracy and runs slowly on current GPUs. On an A100, Llama-2-7B makes 2,104 tokens/s in W8A8, 1,474 in W4A16 and 1,468 in FP16 (TensorRT-LLM). Atom and QuaRot, both W4A4, make 986 and 817.
A GEMM (matrix multiply) runs a main loop on the tensor cores, then an epilogue once. CUDA-core work inside the loop repeats thousands of times:
| Design | CUDA-core work | Where it runs |
|---|---|---|
| W8A8 (TensorRT-LLM) | Rescale the final sums | Epilogue only |
| W4A16 (TensorRT-LLM) | Turn each 4-bit weight into FP16 | Main loop |
| W4A4 (Atom) | Dequantize partial sums, with double the registers | Main loop |
| W4A8 (QServe) | Register-level parallel dequantization, no partial-sum dequantization | Main loop, much cheaper |
Decode attention has intensity about 1, since each request owns its cache. But keys after RoPE (rotary position embedding) have outlier channels. Take queries Q, keys K and a factor λi per channel:
Z equals Q times Lambda, times the transpose of K times Lambda inverse. Lambda is diag of lambda, and lambda-i equals the max of absolute K-i to the alpha.
Multiply query channel i by lambda-i and divide key channel i by it. Each product stays the same, and only the flat keys enter the cache.
Made-up: a key channel peaks at 16 and alpha is 0.5, so lambda = 4. A key of 16 becomes 4, its query of 0.5 becomes 2, and 0.5 × 16 = 2 × 4 = 8.
QServe matches the best WikiText2 accuracy of RTN, AWQ, QuaRot and Atom. Its throughput is up to 2.4 times TensorRT-LLM on an A100, 3.5 times on an L40S, and 1.7 to 3.1 times TensorRT-LLM W4A16 on average.
Symptom: a team moves to W4A4 and throughput drops. Measure: Atom makes 986 tokens/s against 2,104 for W8A8. Fix: judge the whole data path, not the bit count.
Chapter 6
Skip weights, heads, experts and cached tokens, and learn which ones the current input can do without
A zero weight costs nothing to multiply. Pruning sets weights to zero, which makes the matrix sparse. The lecture skips three things: weights (for all inputs), active parts (per input) and cached tokens.
Magnitude pruning drops the smallest weights in the layer. Wanda applies the AWQ lesson. It scores each weight Wij (output row i, input channel j) by its size times the size of channel j on sample prompts:
S-i-j equals the absolute value of W-i-j, times the two-norm of X-j.
Multiply each weight's size by its channel's size. In each output row, drop the half with the lowest scores. There is no retraining.
The slide's row 1 is (4, 0, 1, −1) and the channel sizes are (1, 2, 8, 3), so S = (4, 0, 8, 3). Wanda keeps the 4 and the 1 on the loud channel. On the input (1, 2, 8, 3) the row should give 9: Wanda gives 12, magnitude pruning 4.
The grid is the weight matrix. Pruned weights fade. The right side compares each output row before and after. Change the loudness of channel 3.
Matrix and channel sizes from the lecture's Wanda slide. The test input equals the channel sizes. Magnitude pruning ranks the whole layer; Wanda ranks inside each row, as on the slide.
| LLaMA-7B, dense 59.99 | Magnitude | SparseGPT | Wanda |
|---|---|---|---|
| 50 percent | 46.94 | 54.94 | 54.21 |
| 4:8 | 46.03 | 52.80 | 52.76 |
| 2:4 | 44.73 | 50.60 | 48.53 |
SparseGPT also updates the kept weights; Wanda does not. N:M sparsity keeps N of every M weights, a regular pattern that hardware can skip.
Static sparsity hurts accuracy at medium and high sparsity. Contextual sparsity uses, per input, only the heads and neurons that matter. DejaVu predicts that set one layer ahead.
A mixture of experts (MoE) builds this in: a router sends each token to a few experts. With made-up numbers, 8 experts of 100 million parameters and the top 2 per token: the model holds 800 million, a token touches 200 million. More experts give lower loss (Switch Transformer).
| Method | Decides by | Drops tokens for good? |
|---|---|---|
| SpAtten | Cumulative attention, in a cascade over layers. It also skips V when QK is small and quantizes progressively. | Yes. On the slide's BERT example, 11 tokens and 12 heads become 5 and 10, then 2 and 8. |
| H2O | Recent tokens plus heavy hitters: the tokens past queries attended to most | Yes |
| Quest | The current query: read only the cache pages it scores highest | No. On its slide, query-aware attention scores 100 percent, a query-agnostic method 2. |
Each bar is how much the current query attends to one cached token. Green bars are kept. A red outline marks an important token that was dropped.
Illustrative: 12 tokens with hand-made logits. Query A looks like past queries; B and C do not. H2O keeps the two newest tokens plus the highest past totals. Quest keeps the top scores for this query.
Symptom: a long-context model answers one question well and the next badly, from the same document. Measure: at budget 4 in the device, H2O keeps about 71 percent of the attention for Query A but 10 for Query B. Fix: select per query, as Quest does.
pythondef wanda_prune(W, X, sparsity=0.5): # W (out, in) weights; X (tokens, in) sample activations norm = X.norm(dim=0) # ||X_j||_2 for each input channel, (in,) S = W.abs() * norm # score S_ij = |W_ij| * ||X_j||, (out, in) k = int(W.shape[1] * sparsity) idx = S.argsort(dim=1)[:, :k] # lowest k scores in EACH output row mask = torch.ones_like(W).scatter_(1, idx, 0) return W * mask
Chapter 7
Name the four numbers a serving team watches, then compute why the cache of a long chat outgrows the weights
You press send. Nothing, then words stream. Those are two waits, and a serving team measures each. Following a Databricks post, the lecture names four numbers:
| Metric | What it is | Who feels it |
|---|---|---|
| Time to first token (TTFT) | Prompt processing plus the first token | The user, at the start |
| Time per output token (TPOT) | The gap between later tokens. 100 ms is 10 tokens/s, about 450 words a minute. | The user, while reading |
| Latency | Total time for the full answer | The user |
| Throughput | Tokens per second across all requests | The company, on its bill |
Take the first-token wait TTFT, the gap per later token TPOT, and the answer length of n tokens. The total time is the latency:
Latency equals T-T-F-T plus T-POT times n.
Start with the first-token wait TTFT. Add one TPOT for every token of the answer.
A 200-token reply with TTFT 400 ms and TPOT 50 ms takes 0.4 + 0.05 × 200 = 10.4 s. Only 0.4 s went to the prompt: output length dominates latency.
The goals conflict. More requests at once raise throughput but stretch each user's TPOT. Input length drives prefill time, cache memory and decode cost. Larger models are slower, but not in proportion to their size.
Prefill reads the prompt in parallel, so it is compute-bound and sets TTFT. Decode makes one token per step, so it is memory-bound and sets TPOT. A 7B model costs 14 billion operations per prompt token, so a 2,000-token prompt needs at least 90 ms at 312 trillion operations per second.
The KV cache stores the keys and values of every earlier token, so each step computes them only for the new token (Lecture 12). Every step reads the whole cache again. The slide counts it for Llama-2-70B with multi-head attention (MHA: each head keeps its own keys and values):
Change how many users share the server and how long their prompts and answers are. Watch which of the five bars moves.
Illustrative timing model, made up for this lesson: TTFT = 20 ms + 0.12 ms per prompt token, and TPOT = 30 ms × (1 + requests / 32). The cache size is the lecture's 2.5 MB per token for Llama-2-70B with multi-head attention, times requests times total tokens.
Symptom: a service passes its load test with short prompts, then runs out of memory on long chats. Measure: Llama-2-70B weights take 140 GB in FP16, and sixteen 4,096-token chats add 160 GB. Fix: budget weights plus the cache at the longest context you promise.
pythondef kv_cache_bytes(batch, n_tokens, layers=80, kv_heads=64, head_dim=128, dtype_bytes=2): per_token = layers * kv_heads * head_dim * 2 * dtype_bytes # K and V: 2.6 MB for Llama-2-70B MHA return batch * n_tokens * per_token # kv_cache_bytes(16, 4096) is about 172 GB (the slide rounds to 160 GB)
Chapter 8
Borrow the operating system's page table to stop wasting cache memory on requests that never use it
Early servers reserved one continuous strip of cache per request, as long as the longest possible answer. The slide counts three kinds of waste:
In the slide's request, the prompt "Artificial Intelligence is" fills 3 slots, 2 hold generated tokens, 3 sit reserved, and 2,040 are never used.
Operating systems solved this with virtual memory. A program sees one continuous block, real memory is cut into fixed pages, and a page table says where each page lives. PagedAttention in vLLM (Kwon et al., 2023) copies it. The cache is cut into KV blocks of B tokens. Each request's block table maps its logical blocks to physical blocks anywhere on the GPU.
With B = 4 and a request of 7 tokens:
A request now wastes at most B − 1 slots, not 2,040. The attention kernel follows the table to each physical block, laid out as num_blocks × B × kv_heads × head_dim. The math stays the same.
The pool has 64 slots. The same stream of requests arrives each time. Blue slots hold real tokens. Red slots are reserved but unused. Pick a block size, or reserve the full length.
Illustrative toy: 64 slots, a maximum length of 16 tokens, and a made-up queue with lengths 5, 9, 3, 12, 7, 4, 10, 6, 8 and so on. Real systems use thousands of slots.
At block size 16, paging equals full reservation: 4 requests fit. At size 1, 9 fit. Small blocks waste little but make the table longer and the reads scattered, so real systems use about 16 tokens.
In parallel sampling, several answers grow from one prompt. Their tables point to the same prompt blocks. The server copies a block only when one answer writes to it (copy-on-write). Four samples of a 1,000-token prompt at 2.5 MB per token need 10 GB as copies, 2.5 GB shared.
Symptom: the server refuses requests while most GPU memory holds no real tokens. Measure: in the device, reserving 16 slots per request wastes 35 of 64 slots. Fix: allocate blocks on demand through a block table.
pythondef paged_scores(q, k_cache, block_table, n_tokens, B): # q (heads, d); k_cache (num_blocks, B, heads, d) scores = [] for j, phys in enumerate(block_table): # logical block j -> physical block k = k_cache[phys] # (B, heads, d): any place on the GPU n = min(B, n_tokens - j * B) # the last block may be partly full scores.append((k[:n] * q).sum(-1)) # (n, heads) dot products return torch.cat(scores) # (n_tokens, heads), then softmax as usual
Chapter 9
Compare four ways to group requests, then see how tiling keeps the attention matrix out of slow memory
One request leaves the GPU idle, because each token reads all the weights for one user. A batch runs several requests together and reads the weights once for all. The slides name four ways to form it:
| Method | Rule | Suits |
|---|---|---|
| No batching | Each request runs alone | Nothing: the GPU is under-used |
| Static | Wait for a full batch, return when the last one ends | Scheduled offline work. It adds latency online. |
| Dynamic | Run when full or when a timer expires, like a bus | Models with uniform run time, such as Stable Diffusion |
| Continuous | Token by token: a finished request's slot refills at the next step | LLMs, whose answers vary in length |
Dynamic batching trades wait for size. With a batch of 8, a 50 ms timer and one request every 20 ms, the timer fires first, with 3 requests.
Eight requests of 3, 9, 4, 12, 2, 7, 5 and 10 tokens wait for 4 slots. Each slot makes one token per step: 52 token-steps of work.
With paged memory (Chapter 8) a new request needs only a few blocks, so it can join at the next step.
Each row is a slot. Each colour is one request. Gaps are idle slot-steps. All three charts share one time scale.
Toy model: the eight requests above, all queued at time 0, one token per step per slot, no prompt cost, and a step time that does not change with batch size. Dynamic batching acts like static here, because everything arrives together.
Attention builds an N by N table of scores. For N = 4,096 in FP16 that is 33.5 MB per head per layer, and standard code writes it to GPU memory and reads it back several times. The slide's hierarchy shows the cost:
FlashAttention (Dao et al., 2022) uses tiling: it computes one block of Q, K and V at a time in SRAM and folds it into the output. Softmax needs a whole row, so each row keeps a running max m and a running sum l:
The result is exact. On an H100, FlashAttention-2 reaches close to 300 TFLOPs/s at long sequences, where plain PyTorch runs out of memory at 16,000 tokens (chart readings). See FlashAttention.
Symptom: the queue is full, the GPU is half idle, and short requests take as long as long ones. Measure: in the device, static batching keeps 4 slots busy 59 percent of the time, continuous 68. Fix: schedule per token.
pythondef serve_loop(queue, slots): running = [] while queue or running: while len(running) < slots and queue: # fill free slots at EVERY step running.append(queue.pop(0)) tokens = model_step(running) # one new token for each running request running = [r for r, t in zip(running, tokens) if not r.add(t)] # drop finished
Chapter 10
Turn one slow step per token into one check per several tokens, with exactly the same output distribution
Decoding is memory-bound and makes one token per step. Speculative decoding attacks that. A small draft model (say 7B) guesses, and the large target model (say 175B) checks:
On the slide, the draft writes "Several famous songs are". If the target accepts all four, the same pass adds a fifth, "composed". If it rejects "songs", we keep "Several famous" plus the target's own word. A round always gives at least one token.
Checking is cheap for the reason in Chapter 2: one pass reads all the weights, and the extra positions use idle compute.
Take the draft's probability for a token, q, and the target's, p. Leviathan et al. (2023) keep the token with probability min(1, p / q). After a rejection they sample from the mass where p exceeds q. The output then has exactly the target's distribution. With q = 0.6 and p = 0.3, the keep chance is 0.5.
Take the keep chance α, the draft length K and the draft cost c, in target steps. The first i drafts survive with chance α to the i, and the target adds one token. The average tokens per round is E:
E equals 1 plus alpha, up to alpha to the K, which is 1 minus alpha to the K plus 1, over 1 minus alpha. The speedup is E over 1 plus K c.
Add the chances of keeping 1, 2, up to K draft tokens in a row, plus the target's token. That is E. Divide E by the cost of the round.
Alpha 0.8, K = 4, c = 0.05: E = (1 − 0.328) / 0.2 = 3.36 tokens. The round costs 1 + 4 × 0.05 = 1.2 target steps. The speedup is 3.36 / 1.2 = 2.8 times.
Top: one sampled round, with kept draft tokens in green, the first rejection in red, and the target's own token in teal. Bottom: the speedup for each draft length K, with a dot at yours.
The geometric-series result of Leviathan et al., with the same keep chance α at every position. Real rates vary. A seeded generator makes the same clicks give the same rounds.
At α = 0.8 the curve over K rises, flattens and falls: the target keeps each extra draft less often, but it still costs a step. At α = 0.3 it stays near 1.
Symptom: speculation is on and the service is no faster. Measure: with α = 0.3, K = 8 and c = 0.05, E is 1.43 and a round costs 1.4 steps, a speedup of 1.02. Fix: pick a draft from the target's family, and set K from the curve.
pythondef speculative_step(target, draft, ctx, K): drafts, qs = [], [] for _ in range(K): # K cheap draft steps q = draft(ctx + drafts) # (vocab,) draft probabilities x = sample(q); drafts.append(x); qs.append(q) ps = target(ctx + drafts) # ONE target pass: (K+1, vocab) probabilities out = [] for i, x in enumerate(drafts): if random() < min(1, ps[i][x] / qs[i][x]): out.append(x) # keep with prob min(1, p/q) else: out.append(sample(residual(ps[i], qs[i]))); return out # correction, stop return out + [sample(ps[K])] # all kept: add the bonus token
Chapter 11
Keep the numbers, the terms, the checklist and the core code in one place, and find where to go next
The lecture asked how to make a large language model small and fast enough to serve. Quantization stores fewer bits: SmoothQuant, AWQ and QServe. Pruning and sparsity skip what the input does not need: Wanda, DejaVu, MoE, SpAtten, H2O and Quest. Serving systems keep the hardware full: metrics, paged memory, continuous batching, tiled attention and speculation.
One thread ran through every chapter: look at the activations, not only the weights. SmoothQuant, AWQ, Wanda and SmoothAttention all use the same fact. A weight matters in proportion to the size of what multiplies it.
| Case | Number | Why it matters |
|---|---|---|
| 4 weights with an outlier of 9.0, 4 bits, absmax step | Step 1.125, three small weights round to 0 | One outlier ruins the grid (Ch 0) |
| SmoothQuant, max|X| 16, max|W| 1, α 0.5 | s = 4, both maxima become 4 | Difficulty moves into the weights (Ch 1) |
| OPT-175B, sequence 1,024, FP16 vs SmoothQuant | 389 GB to 200 GB, 848 ms to 720 ms | Half the memory, fewer GPUs (Ch 1) |
| 7B model, one token on an A100 (2 TB/s) | FP16 7.0 ms, W8A8 3.5 ms, W4A16 1.75 ms | Batch 1 is memory-bound (Ch 2) |
| OPT-6.7B, INT3 group 128, perplexity | FP16 12.29, RTN 43.16, AWQ at 2x 14.07 | Scaling protects salient channels (Ch 3) |
| Llama-2 7B, INT4 group 128, perplexity | FP16 5.47, RTN 5.73, AWQ 5.60 | Small loss for a 4 times smaller model (Ch 3) |
| 32 four-bit weights in one 128-bit register | 3 logical operations to unpack | Pack for the instruction set (Ch 4) |
| 7B model in 4 bits with group-128 scales | About 3.45 GB, against 13.4 GB | Fits a board with 7 GB free (Ch 4) |
| Roofline at batch 128 (TOPS) | FP16 256, W8A8 512, W4A16 312, W4A8 624 | W4A8 takes both advantages (Ch 5) |
| Llama-2-7B on an A100, tokens/s | W8A8 2,104, Atom W4A4 986, QuaRot W4A4 817 | Fewer bits can be slower (Ch 5) |
| Wanda toy matrix, output errors per row | Magnitude 5, 8, 2. Wanda 3, 1, 2 | Activations decide importance (Ch 6) |
| 200 tokens, TTFT 400 ms, TPOT 50 ms | 10.4 s, 20 tokens/s | Output length dominates (Ch 7) |
| Llama-2-70B MHA cache | 2.5 MB per token, 16 × 4,096 tokens = 160 GB | The cache outgrows the GPU (Ch 7) |
| Paging toy, 64 slots | 4 requests fit reserved, 9 fit in blocks of 1 | Waste is at most one block (Ch 8) |
| Eight requests, 52 token-steps, 4 slots | Static 22 steps (59%), continuous 19 (68%) | Do not wait for the longest (Ch 9) |
| Attention matrix, N = 4,096, FP16 | 33.5 MB per head per layer | Tiling keeps it off slow memory (Ch 9) |
| α 0.8, K 4, c 0.05 | 3.36 tokens per round, 2.8 times faster | Check K tokens for one step (Ch 10) |
| Term | Plain meaning | Where |
|---|---|---|
| W8A8, W4A16, W4A8KV4 | Bits for weights, activations and the KV cache | 0, 2, 5 |
| Scale, zero point | The gap between levels, and the integer that means 0 | 0 |
| Activation outlier, channel | A giant value that stays in a fixed column of the activations | 1 |
| Smoothing, migration strength α | Divide a channel, multiply the matching weights, by s | 1 |
| Memory-bound, compute-bound | Limited by bytes moved, or by operations done | 2 |
| Arithmetic intensity, roofline | Operations per byte; the chart of speed against it | 2, 5 |
| Group-wise quantization, RTN | One scale per 128 weights; plain rounding to the grid | 3 |
| Salient channel, AWQ | A channel big activations make important; protected by scaling | 3 |
| Kernel, fusion, packing | One routine on the chip; merged steps; bit layout for fast unpack | 4 |
| GEMM, main loop, epilogue | A matrix multiply; the repeated part; the part that runs once | 5 |
| SmoothAttention | Smoothing applied to queries and keys for a 4-bit cache | 5 |
| Wanda, contextual sparsity, MoE | Prune by weight times activation; per-input active parts; routed experts (a token picks its top-K experts, an expert picks its top-K tokens, or a global assignment) | 6 |
| SpAtten, H2O, Quest | Prune tokens by cumulative, heavy-hitter or per-query attention | 6 |
| TTFT, TPOT, latency, throughput | First-token wait; later-token gap; total time; tokens per second overall | 7 |
| KV cache | Stored keys and values of earlier tokens | 7 |
| PagedAttention, block table | Cache in fixed blocks, with a list from logical to physical | 8 |
| Static, dynamic, continuous batching | Wait for full; full or timer; refill slots every step | 9 |
| FlashAttention, tiling | Exact attention in on-chip blocks, never storing the N by N matrix | 9 |
| Draft model, target model | The small guesser and the large checker | 10 |
A sketch of each rule, with shapes in the comments.
pythonimport torch, math def quant_absmax(w, bits=4): # w (G,) one group -> rounded copy (G,) step = w.abs().max() / 2**(bits - 1) # delta = max|w| / 2^(N-1) return step * (w / step).round().clamp(-2**(bits - 1), 2**(bits - 1) - 1) def smooth_scales(x_absmax, w, alpha=0.5): # SmoothQuant: x_absmax (C,), w (C, out) -> s (C,) return x_absmax.pow(alpha) / w.abs().amax(1).pow(1 - alpha) def awq_scales(x_mean, alpha): # AWQ: s = s_X ^ alpha, searched on a grid of alpha return x_mean.pow(alpha) def wanda_mask(w, x, sparsity=0.5): # w (out, in), x (tokens, in) -> keep-mask (out, in) score = w.abs() * x.norm(dim=0) # |W_ij| * ||X_j||_2 drop = score.argsort(1)[:, :int(w.shape[1] * sparsity)] return torch.ones_like(w).scatter_(1, drop, 0) def step_time_ms(params, wbits, batch, bw=2e12, peak=312e12): # one decode step: the larger of the two limits t_mem = params * wbits / 8 / bw t_cmp = 2 * params * batch / peak return 1000 * max(t_mem, t_cmp) def kv_bytes(batch, n, layers=80, kv_heads=64, d=128, nb=2): # the KV cache of Chapter 7 return batch * n * layers * kv_heads * d * 2 * nb def latency_s(ttft_ms, tpot_ms, n_tokens): # latency = TTFT + TPOT * n return (ttft_ms + tpot_ms * n_tokens) / 1000 def spec_speedup(alpha, K, c): # speculative decoding, same keep chance at every position E = (1 - alpha**(K + 1)) / (1 - alpha) return E / (1 + K * c)
Checks: step_time_ms(7e9, 16, 1) gives 7.0, and step_time_ms(7e9, 4, 1) gives 1.75. The call latency_s(400, 50, 200) gives 10.4. The call spec_speedup(0.8, 4, 0.05) gives 2.8. The call quant_absmax rounds the small weights of a group with a 9.0 outlier to zero.
Lecture 12 built the efficient transformer and its KV cache. Lecture 14 moves on to post-training. Lectures 5 and 6 (quantization) and 3 and 4 (pruning) are the base. Production engines such as vLLM ship the serving ideas.
This lesson follows Lecture 13 (84 slides) of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. The course page links the slides. Quantization papers taught from the slides: SmoothQuant, AWQ (Lin et al., MLSys 2024), TinyChat, VILA (Lin et al., CVPR 2024) and QServe. Sparsity papers: Wanda (Sun et al., 2023), DejaVu (Liu et al., 2023), Switch Transformers (Fedus et al., 2022), SpAtten (Wang et al., 2020), H2O (Zhang et al., 2023) and Quest (Tang et al., 2024). Serving: PagedAttention and vLLM (Kwon et al., 2023), FlashAttention (Dao et al., 2022), speculative decoding (Leviathan et al., 2023), and the Databricks and Baseten posts. The figures and devices are our own, and we label toy numbers as illustrative.
Now press Teach and explain, from memory, why SmoothQuant divides a channel and multiplies its weights, and why decoding wants 4-bit weights. Then go back to the dial at the top and compare 4 bits and 3 bits once more.