Where the bytes go, why decoding is slow, and the techniques that fix it. Each technique gets one picture, one formula with a worked number, its trade-offs, what to do on a Jetson versus a datacenter GPU, and a check you can run on a laptop CPU.
Efficiency track · a reference for every module; first read it after the Transformer moduleLab: efficient-inference/efficient_inference.py (torch ≥ 2.1, CPU, about 20 s)Device facts and tool status checked Oct 2026
About 90 min to read and play with the two widgets; 20 s to run the lab; 1–2 h for the exercises.
Notation
Same letters as Module 1: N = tokens in the context, B = batch (sequences), L = layers, d = hidden size, h = query heads, nkv = K/V heads, dk = head dim, P = parameters, b = bytes per value (bw weights, bkv cache). Exceptions: in the quantization cards (c) and the 2:4 card (i), b counts bits per stored number and g is the group size; T appears only as the distillation temperature (card i).
What you'll learn
Estimate memory (weights, KV cache, the rest) and a decode-speed ceiling for any model on any device.
Tell memory-bound from compute-bound with the roofline, and why prefill and decode differ.
The maths of quantization: scale, zero-point, groups, FP8/FP4, and why outliers matter.
How FlashAttention, paging, prefix caching, speculative decoding and fusion actually save time.
How to fit training into memory, and a Jetson deployment workflow you can trust.
Diagram colours (same in every guide)
data, tokenslearned weightsmixing across tokensper-token compute, outputscost, memory trafficcontext
🎬 Learn it visually
Watch or read one of these first if a section feels abstract. Ordered: best intuition first, code last. Each technique card below also has its own ▶ pick.
EfficientML.ai Lecture 5: Quantization (Part I), MIT 6.5940 (Song Han's course, MIT HAN Lab), Fall 2026 (video, 68 min). Number formats, then linear quantization with scales and zero-points, from the course that covers this whole page. The course page has the whole series: pruning, distillation, LLM deployment, efficient training.
Large Transformer Model Inference Optimization, Lilian Weng (blog post). A map of the whole field (distillation, quantization, pruning, sparsity, architecture changes) with the key papers.
In plain words: a model in memory is four piles of bytes. Two are big and predictable (weights and the KV cache); two are smaller and messier (activations and the runtime's own workspace). Know which pile is biggest before you pick a fix.
temporary per-layer tensors; tiny at decode, larger during prefill (and huge in training)
tokens processed at once
chunked prefill, FlashAttention (d), checkpointing in training (j)
Workspace and runtime
CUDA context, kernel scratch, allocator slack; on Jetson also the OS and every other process, because CPU and GPU share one DRAM
runtime and system
measure it: tegrastats or nvidia-smi before and after loading
Memory budget
Intuition. Bytes = how many numbers × bytes per number, for the two big piles.
M ≈ P · bw + 2 · L · nkv · dk · bkv · N · B + Mother
Read it aloud
P parameters times bw bytes each (2 for BF16, 0.53 for INT4 with group scales), plus the cache: 2 tensors (K and V) × L layers × nkv KV heads × dk numbers per head × bkv bytes, for each of N context tokens in each of B sequences, plus everything else.
Why it exists
It tells you which pile to attack. If weights dominate, quantize weights; if the cache dominates (long context, many users), shrink or page the cache.
Cache: 2 × 36 × 8 × 128 × 2 B = 147,456 B = 144 KiB per token; × 8,192 tokens = 1.125 GiB. With 1 GiB for everything else: 6.18 GiB, 77% of an 8 GB Orin Nano.
Intuition. To produce one token per sequence, the GPU must stream every weight, and every sequence's cache, from DRAM once. Bandwidth sets the speed limit, not FLOPs.
tokens/s ≤ B · BW / (P · bw + KV bytes)
Read it aloud
B sequences each get one token per step; a step moves the weights once plus every sequence's cache; BW is DRAM bandwidth in bytes per second.
Why it exists
At small batch the arithmetic units sit idle (§2), so bandwidth is the real limit. The bound tells you at once whether a target speed is possible at all; good runtimes reach roughly half to three quarters of it.
Tiny example
The Qwen3-8B INT4 case above on an Orin Nano 8GB in Super mode (102 GB/s): 102 / (4.35 + 1.21) GB = 18.3 tokens/s at 8K context, 102 / 4.35 = 23.4 tokens/s with an empty cache.
Reality check from the VLM guide (§8, measured on the same board): a 2B VLM with W4A16 weights has a floor of 8.4–13 ms per token and measured 17 ms, so runtimes reach roughly 50–78% of peak bandwidth.
Code
steps_per_s = bandwidth / (w_bytes + kv_bytes) # one step = one token per sequence
tokens_per_s = batch * steps_per_s
Will it fit? Memory and decode-speed calculator
Model
Precision and workload
weightsKV cacheotherdevice memory (dashed line)
Weights
-
KV cache
-
Total vs device
-
Decode ceiling
-
What to notice: on the Orin Nano, Qwen3-8B fits only at 4 bits, and doubling the context or the batch adds whole GiB of cache. On the H100 the same model is a sliver of the bar and its cache, not its weights, decides how many users fit. The page flags anything above 75% of device memory as tight, because on Jetson the OS and your other processes share the same DRAM.
Device facts used on this page
Device
Memory
Bandwidth
Dense FP16 TFLOPS
Ridge, FLOP/B
FP8 / FP4
Jetson Orin Nano 8GB, Super mode (JetPack 6.2+)
8 GB LPDDR5, shared by CPU and GPU
102 GB/s
17
167
no / no
Jetson AGX Orin 64GB
64 GB LPDDR5, shared
204.8 GB/s
≈ 42.5 ¹
208
no / no
Jetson AGX Thor T5000
128 GB LPDDR5X, shared
273 GB/s
≈ 259 ²
948
yes / yes
GeForce RTX 4090
24 GB GDDR6X
1,008 GB/s
165.2 ³
164
yes / no
H100 SXM
80 GB HBM3
3,350 GB/s
989.5 ⁴
295
yes / no
Sources: Orin Nano Super spec table (8 GB, 102 GB/s, 17 FP16 TFLOPS, 33 dense INT8 TOPS; the original mode is 68 GB/s and 10 TFLOPS); Jetson AGX Orin technical brief (64 GB, 204.8 GB/s; ¹ 170 sparse INT8 TOPS on the GPU, so dense FP16 = 170 ÷ 2 ÷ 2); Jetson Thor page and datasheet (128 GB, 273 GB/s; ² from 2,070 sparse FP4 TFLOPS: 2,070 ÷ 2 ÷ 2 ÷ 2, our derivation, not an NVIDIA figure); Ada architecture whitepaper, Appendix A (RTX 4090; ³ BF16/FP16 with FP32 accumulate, 330.3 with FP16 accumulate); H100 product page (⁴ 1,979 BF16 TFLOPS with sparsity, halved). "8 GB" etc. are nominal sizes; the calculator treats them as GiB, and usable memory is always a little lower. Orin's FP8 status follows the TensorRT Edge-LLM docs ("Jetson Orin supports FP16, INT8, and INT4 runtime precisions only").
For a mixture-of-experts model, use the active parameters in the bandwidth formula and the total parameters in the memory formula; the MoE guide §5 has the numbers for Qwen3-30B-A3B and gpt-oss on AGX Orin and Thor.
2 Roofline in plain words
In plain words: a GPU has two speed limits: how fast it does maths (FLOP/s) and how fast it fetches numbers from memory (bytes/s). A kernel runs into whichever limit it meets first. Which one depends on how many FLOPs it does per byte it fetches.
Arithmetic intensity and the roofline
AI = FLOPs ÷ bytes moved · attainable = min(peak, AI × BW) · ridge = peak ÷ BW
Read it aloud
AI is how many operations a kernel does for each byte it moves between DRAM and the chip. Below the ridge it can go no faster than AI × bandwidth (memory-bound); above it, no faster than the peak FLOP/s (compute-bound).
Why it exists
It tells you which fix can help. A memory-bound kernel only speeds up if it moves fewer bytes or reuses each byte more; more TOPS do nothing for it.
Tiny example
A linear layer with a d × d weight (d = 4096) applied to M tokens: FLOPs = 2Md², bytes ≈ bw·d² (weights) + 4Md (FP16 activations in and out), so AI = 2M / (bw + 4M/d).
Decode, M = 1, FP16 weights: AI = 1.0. INT4 weights: 4.0. Prefill of 2,048 tokens: AI = 1,024. The Orin Nano's ridge is 17 × 10¹² / 102 × 10⁹ = 167 FLOP/byte, so batch-1 decode uses about 0.6% of its tensor-core peak, and prefill is compute-bound.
Code
ai = 2 * M / (bytes_per_weight + 4 * M / d)
attainable = min(peak_flops, ai * bandwidth)
What to notice: the red arrow (bytes read from DRAM) is the same in both rows. Prefill shares that cost across M tokens; decode pays it for one token. That ratio is the arithmetic intensity.
Interactive roofline: where does your kernel land?
Arithmetic intensity
-
Ridge point
-
Attainable
-
Verdict
-
What to notice: slide M from 1 (decode) to 2,048 (prefill) and the dot climbs the slope onto the flat roof. Switch to INT4 at M = 1 and it moves right: same maths, a quarter of the bytes. Pick the attention kernel and the slider stops mattering: every sequence reads its own cache, so batching cannot raise its intensity (AI = 2g/b for g query heads per KV head); only fewer KV bytes can.
fewer bytes or more uses per byte: INT4 weights, GQA/MLA, KV quantization, batching, speculative decoding
Three levers for a memory-bound step, which organise most of §3: move fewer bytes (quantization, GQA/MLA, KV quantization, sparsity), use each byte more (batching, speculative decoding), and stop moving the same bytes twice (FlashAttention, fusion). The transformer guide has a second roofline view for a single GEMM in §4, arithmetic intensity.
3 Technique cards
Each card stands alone. The chips say what it saves; the lab line says which function in efficient_inference.py checks it. Run one section with python efficient_inference.py <section>.
Intuition. The keys and values of past tokens never change, so compute them once and keep them. Each new token then computes only its own row, but must read all of the stored rows.
What to notice: the cache grows by one column per generated token, and every step reads every column. The cache trades compute for memory and bandwidth.
Size of the cache, and what it saves
KV bytes = 2 · L · nkv · dk · b · N · B · work without it = G·Np + G(G−1)/2 token-passes
Read it aloud
K and V (the 2), for each of L layers and nkv KV heads, dk numbers of b bytes, for N tokens in B sequences. Without a cache, generating G tokens after an Np-token prompt re-runs the model on Np, Np+1, …, Np+G−1 tokens; with it, on Np tokens once and then 1 token per step.
Why it exists
Recomputing the past is quadratic in length. The cache makes each step cost one token's worth of compute, at the price of memory that grows linearly with context.
Tiny example
Llama-3.1-8B (L = 32, nkv = 8, dk = 128, BF16): 2 × 32 × 8 × 128 × 2 B = 128 KiB per token, so 1 GiB per 8K-token sequence. Eight such users hold 8 GiB of cache, over half the 14.96 GiB of BF16 weights.
Lab: Np = 32, G = 160 gives 17,840 token-passes without a cache versus 191 with it (93× fewer), and the 160 greedy tokens are identical; on a laptop CPU the cached loop ran 4–9× faster (more with fewer threads).
Code
k = torch.cat([past_k, k_new], dim=2) # append, never recompute
v = torch.cat([past_v, v_new], dim=2)
Trade-offs
Memory grows with context × batch; at long context the cache, not the weights, fills the device.
Each decode step reads the whole cache: attention's arithmetic intensity stays near 2·(h/nkv)/b FLOP per byte (h/nkv query heads share each cached K/V head), whatever the batch.
A growing, per-request buffer is awkward to allocate: hence paging (card e) and sharing (card f).
Jetson vs datacenter
Jetson: batch is 1–4, so context length is your knob. Set the runtime's maximum KV capacity explicitly (TensorRT Edge-LLM's llm_build --maxKVCacheCapacity, vLLM's --max-model-len) so it doesn't reserve memory you need.
Datacenter: the cache limits batch size, so throughput. Everything in cards b, c (KV), e and f exists to fit more sequences.
Intuition. Many query heads can share the same keys and values. Store fewer K/V heads (GQA, MQA), or one small compressed latent that every head expands on the fly (MLA).
What to notice: all four keep 8 query heads; only the red cache shrinks. The percentages are cache size relative to MHA (the MLA one is for DeepSeek-V3's own shape).
Cache per token per layer
MHA 2·h·dk → GQA 2·nkv·dk → MQA 2·dk → MLA dc + dR
Read it aloud
h query heads of dk numbers; nkv shared K/V heads (each serves h/nkv query heads); MLA stores one latent of dc numbers plus a small shared RoPE key of dR numbers, and rebuilds per-head K and V from the latent with learned up-projections.
Why it exists
At long context the cache dominates memory and decode traffic. Sharing K/V across heads loses little quality (the GQA paper reports GQA close to MHA at near-MQA speed), and cuts bytes by h/nkv.
Tiny example
Llama-3.1-8B's shape (32 layers, 32 query heads, dk = 128) at 32K context, BF16: MHA would need 16 GiB, its actual GQA with 8 KV heads 4 GiB, MQA 512 MiB.
DeepSeek-V3's MLA caches 512 + 64 = 576 numbers per layer: 61 × 576 × 2 B = 68.6 KiB per token versus 3,904 KiB for MHA at its shape, 56.9× smaller.
Code
k = k.repeat_interleave(n_heads // n_kv_heads, dim=1) # GQA: expand at use, not in the cache
v = v.repeat_interleave(n_heads // n_kv_heads, dim=1)
Trade-offs
Chosen at pre-training. Converting an MHA model needs extra training (the GQA paper "uptrains" checkpoints with 5% of the original compute).
MQA saves most but risks quality; GQA with 8 KV heads is the common middle ground (Llama 3, Qwen3).
MLA gives the smallest cache at strong quality, but costs FLOPs (each head works on the 576-number latent) and needs dedicated kernels; RoPE needs the separate "decoupled" key.
Jetson vs datacenter
Jetson: you choose it by choosing the model. Prefer GQA models: their cache competes with the weights for the same shared DRAM.
Datacenter: MLA models (DeepSeek, Kimi) need MLA-aware kernels; with tensor parallelism beyond the number of KV heads, the KV heads get replicated rather than split.
Lab:python efficient_inference.py kvsize → kv_bytes_per_token() checked against the real cache tensors for nkv = 8, 4, 2, 1, and LatentKVAttention, where attending on the latent equals rebuilding K and V. Deeper:MoE guide §4, MLA, including its FLOP cost. ▶ the grouped-query attention part of LLaMA explained (Umar Jamil).
c
Quantization 1: scale and zero-point
memory ↓↓decode ↓↓math ↑ (W8A8, FP8)
Intuition. Lay a ruler with 2b marks over the range of your numbers and store each number as the index of its nearest mark. Keep two extra numbers: the spacing of the marks (scale) and which mark means 0.0 (zero-point).
What to notice: 0.0 lands exactly on a mark (the zero-point), so zeros and padding stay exact. Every other value moves to its nearest mark, by at most half a step.
Asymmetric (scale + zero-point) and symmetric quantization
s is the scale (real distance between neighbouring integers), z the zero-point (the integer that stands for 0.0), q the stored b-bit integer, x̂ what you get back. Symmetric variant: s = max|x| / (2b−1 − 1) and z = 0, which is simpler for kernels and the usual choice for weights.
Why it exists
2b integers can only cover a range if you tell them where it is. The scale spreads the levels over the data's actual range; the zero-point lets a lopsided range (say −1.2 to 2.6) use all levels instead of wasting half on negatives that never occur.
Tiny example
x = [−1.2, 0.0, 0.5, 2.6] to INT4: s = 3.8 / 15 = 0.2533, z = round(4.74) = 5.
Intuition. One huge number stretches the ruler for everything that shares its scale. Give each scale fewer numbers to cover, and an outlier only hurts its own neighbours.
outlier weightcoarse steps (big error)fine steps
What to notice: the same single outlier coarsens everything (per-tensor), its whole row (per-channel) or just its group of 4 here (group-wise; real groups are 64–128 weights).
Step size, and the cost of more scales
step = max|w in group| / qmax · RMS error ≈ step / √12 · bits per weight = b + 32/g
Read it aloud
Each group of g weights gets its own step from its own largest magnitude; rounding error is spread evenly over ±step/2, giving an RMS error of step/√12. Each group also stores an FP16 scale and an FP16 zero-point: 32 extra bits shared by g weights.
Why it exists
Trained transformers have outliers: rare large weights, and in activations whole channels that are consistently huge (LLM.int8() calls them emergent outlier features). Smaller groups contain them.
Tiny example
Lab, toy GPT layer with heavy-tailed weights and one output channel ×20: INT8 per-tensor output error 0.117, per-channel 0.0086 (14× better; 17× on the normal rows' weights).
At 4 bits: one scale per row 0.169, groups of 64 0.071, FP4 in blocks of 16 0.058, both at 4 + 32/64 = 4 + 8/16 = 4.5 bits per weight. With g = 128 the overhead drops to 4.25 bits.
Code
scale = w.abs().amax(dim=1, keepdim=True) / 127 # per output channel (row)
wg = w.reshape(out, in_ // 128, 128) # group-wise: scales per 128 inputs
Why outliers matter, and four ways around them
Keep them in high precision. LLM.int8() routes the few outlier feature dimensions through a 16-bit matmul and the other 99.9% of values through INT8.
Move them.SmoothQuant divides each activation channel by sj and multiplies the matching weight row by sj: XWT = (X·diag(s)−1)(W·diag(s))T exactly, with sj = max|Xj|α / max|Wj|1−α. In the lab a 40× activation outlier gives W8A8 error 0.127; after smoothing (α = 0.5) 0.022, 5.9× lower. AWQ uses the same equivalence for weight-only INT4: it scales up the ~1% of weight channels that see large activations, so they lose less in rounding.
Compensate.GPTQ quantizes a matrix column by column and nudges the not-yet-quantized columns to cancel the error, using second-order (Hessian) information from calibration data.
Rotate.QuaRot and SpinQuant multiply by orthogonal matrices that spread outliers over all channels, then quantize.
Trade-offs
Smaller groups: better accuracy, more scale bytes, slightly slower kernels. g = 128 is the usual INT4 choice in AWQ/GPTQ checkpoints.
Per-channel scales on weights are free at runtime (fold into the output); per-channel scales on activations are not, which is why W8A8 needs SmoothQuant-style tricks.
Jetson vs datacenter
Jetson: INT4 AWQ (g = 128) is the standard LLM recipe in TensorRT Edge-LLM, vLLM and llama.cpp builds for Orin.
Datacenter: FP8 with per-tensor or 128 × 128 block scales (DeepSeek-V3), NVFP4 with 16-value blocks on Blackwell.
Lab:python efficient_inference.py quant → quant_sym(), quant_asym_groups(), quant_fp4_blocks(), and the SmoothQuant block. ▶A Gentle Introduction to 8-bit Matrix Multiplication (Hugging Face blog: outliers and LLM.int8() with pictures).
c
Quantization 3: formats, and what to quantize
memory ↓↓math ↑ on FP8/FP4 hardware
Intuition. A float spends its bits on two things: exponent bits buy range, mantissa bits buy precision. Fewer bits means choosing which one you can do without, and then quantizing whatever costs you most: weights, activations or the KV cache.
signexponent (range)mantissa / value bits (precision)
What to notice: BF16 keeps FP32's 8 exponent bits (same range, less precision), which is why it trains without loss scaling. The FP8 paper recommends E4M3 for weights and activations and E5M2 for gradients.
Scheme
What is low-precision
Saves
Needs
Weight-only INT8 / INT4 (GPTQ, AWQ; "W4A16")
weights; maths in FP16 after dequantizing in the kernel
memory and decode time (memory-bound)
good dequantizing kernels; light calibration
W8A8 INT8 (SmoothQuant)
weights and activations
also faster GEMMs: helps compute-bound prefill and big batches
Each value is one of the 15 FP4 (E2M1) numbers {0, ±0.5, ±1, ±1.5, ±2, ±3, ±4, ±6}, times a per-block scale, times (NVFP4 only) one FP32 scale for the whole tensor.
Why it exists
4 bits alone have almost no range; a scale per small block restores it locally. NVIDIA's NVFP4 uses 16-value blocks with an FP8 E4M3 scale; OCP's MXFP4 uses 32-value blocks with a power-of-two scale.
Tiny example
NVFP4: 4 + 8/16 = 4.5 bits per value; MXFP4: 4 + 8/32 = 4.25 bits. Qwen3-8B's 8.19B weights: 16.4 GB in BF16, 4.61 GB in NVFP4 (3.6× smaller).
KV cache in FP8 instead of BF16: Qwen3-8B's 144 KiB per token becomes 72 KiB; a 32K context drops from 4.5 GiB to 2.25 GiB. KIVI goes to 2 bits by quantizing keys per channel and values per token.
Code
scale = wb.abs().amax(-1, keepdim=True) / 6.0 # block max -> 6
scale = scale.to(torch.float8_e4m3fn).float() # the scale is 8-bit too
q = E2M1_GRID[((wb / scale).abs().unsqueeze(-1) - E2M1_GRID).abs().argmin(-1)] * wb.sign()
Trade-offs
Accuracy loss grows as bits shrink; check your own task, not only perplexity.
Keep sensitive parts in 16-bit when in doubt: embeddings, the LM head, the router of an MoE.
A format only speeds things up where hardware runs it natively; elsewhere it still saves memory and bandwidth if the kernel dequantizes on the fly.
Jetson vs datacenter
Orin: FP16, INT8, INT4. Thor: FP8 and NVFP4; the Jetson AI Lab calls NVFP4 "the recommended precision for Thor".
Datacenter: FP8 on Hopper/Ada is the default serving format; FP8 KV cache is common; NVFP4 on Blackwell.
Lab:python efficient_inference.py quant → fp_format_max() (448 and 57,344, checked against torch.finfo), quant_fp8_tensor(), quant_fp4_blocks(). Deeper:MoE guide §5.6 on MXFP4 experts in gpt-oss. ▶Quantization explained with PyTorch (Umar Jamil, 51 min).
d
FlashAttention: IO-aware tiling and online softmax
memory O(N²) → O(N)attention time ↓same FLOPs
Intuition. Do attention a tile at a time inside the GPU's small, fast on-chip memory, keeping a running softmax, so the N × N score matrix is never written to DRAM.
What to notice: the only DRAM traffic is reading Q, K, V tiles and writing O once. Standard attention would also write and re-read the dashed N × N matrix.
For each query row keep m (largest score so far), ℓ (sum of exponentials relative to m) and acc (unnormalised output). When a tile brings a larger max, multiply what you have by em−m′ to re-base it, then add the tile's share.
Why it exists
Softmax needs the whole row's max and sum before it can normalise; the rescaling trick (Milakov & Gimelshein, 2018) lets you see the row in pieces and still get the exact answer, so the row never has to exist in DRAM.
Tiny example
Scores [1, 2 | 3, 4] in two tiles. Tile 1: m = 2, ℓ = e−1 + e0 = 1.3679. Tile 2: m′ = 4, ℓ′ = 1.3679·e−2 + e−1 + e0 = 1.5530, exactly Σ ex−4 over all four.
Memory: at N = 8,192 with 32 heads in FP16 the score matrix is 32 × 8192² × 2 B = 4 GiB per layer; the running statistics are 2 MiB.
Exact (same result up to rounding) and the same FLOPs: it saves traffic and memory, not maths. The paper proves its DRAM traffic is Θ(N²d²/M) for SRAM size M, versus Θ(Nd + N²).
Kernels are hardware-specific (FlashAttention-2 for Ampere/Ada, FlashAttention-3 for Hopper, newer ones for Blackwell).
Decode has one query per sequence; its bottleneck is reading the KV cache, which Flash-Decoding parallelises along the cache length.
Jetson vs datacenter
Jetson: you rarely write it; TensorRT and Edge-LLM ship fused attention, and PyTorch's scaled_dot_product_attention picks a fused backend. It matters most for long prompts and image tokens (TTFT).
Datacenter: FA3 / FlashInfer-class kernels are standard in vLLM, SGLang and TensorRT-LLM.
Intuition. Store each sequence's cache in small fixed-size blocks, like an operating system's memory pages, and let new requests join the batch whenever blocks free up.
tokens actually storedreserved but empty
What to notice: a contiguous slab wastes everything past the sequence's real length; a paged sequence wastes at most part of its last block. The blocks can sit anywhere in one shared pool; a per-sequence block table maps logical to physical blocks.
A sequence of N tokens takes N/Bblk blocks (Bblk tokens each) rounded up, so it wastes less than one block; a contiguous allocation must reserve the maximum length Nmax up front because the final length is unknown.
Why it exists
Output lengths are unknown when a request arrives. The vLLM team measured existing systems wasting 60–80% of KV memory to fragmentation and over-reservation; with paging, under 4%. Freed memory means more sequences per batch: 2–4× throughput in the paper.
Tiny example
Lab: 12 requests of 30–700 tokens, Nmax = 2,048. Contiguous: 24,576 slots for 3,945 tokens, 83.9% wasted. Paged: 251 blocks of 16 = 4,016 slots, 1.8% wasted. At Llama-3.1-8B's 128 KiB per token that is 3.00 GiB versus 502 MiB.
Code
if n_tokens[seq] % block_size == 0: # last block full: grab any free one
block_table[seq].append(free_blocks.pop())
pool[block_table[seq][-1], n_tokens[seq] % block_size] = kv
Continuous batching (iteration-level scheduling, from Orca, OSDI 2022) is the scheduling half: after every decode step, finished sequences leave and waiting ones join, instead of the whole batch waiting for its longest member. Paging makes this cheap, because a joining request only needs a few free blocks, not a contiguous slab.
Trade-offs
The attention kernel gathers K/V through the block table: a little indexing overhead.
Block size: small blocks waste less but index more; the vLLM paper found 16–128 tokens worked best on its chat trace.
When memory runs out the scheduler must pause (preempt) and later recompute or swap a sequence.
Jetson vs datacenter
Jetson: single-user apps gain little; capping the maximum context matters more. It pays off when one board serves several streams (vLLM on Jetson; Edge-LLM also lists paged attention).
Datacenter: essential. It is why a server's batch can grow until the KV memory is actually full.
Lab:python efficient_inference.py paged → BlockAllocator, PagedKVCache (gathering through the block tables returns every sequence exactly). ▶Fast LLM Serving with vLLM and PagedAttention (Woosuk Kwon and Zhuohan Li, Anyscale, 32 min).
f
Prefix caching
time to first token ↓↓shared blocks
Intuition. When requests start with the same tokens (a system prompt, tool definitions, a long document, the chat so far), compute the KV cache of that prefix once and let later requests reuse its blocks.
What to notice: solid blocks are computed once and shared; dashed blocks belong to one request. A block is reusable only if every token before it matches too, because its keys and values depend on the whole prefix. So the lookup key of a block hashes its tokens together with its parent's key.
What a shared prefix saves
prefill FLOPs saved per request ≈ 2 · P · Nprefix
Read it aloud
A forward pass costs about 2 FLOPs per parameter per token, so skipping Nprefix tokens of prefill saves 2·P·Nprefix FLOPs (plus their attention).
Why it exists
Prefill is compute-bound and sets time to first token. Agents and chat repeat long, identical prefixes on every call.
Tiny example
Qwen3-8B with a 1,000-token shared prefix: 2 × 8.19 × 10⁹ × 1,000 = 16.4 TFLOP per request, about a second of an Orin Nano's 17 TFLOPS peak, which real kernels do not reach.
Lab: three requests share a 64-token prompt (4 blocks of 16): of 230 prompt tokens, 102 are computed and 128 reused, and the logits on top of the cached prefix equal a full forward pass.
Code
key = hash((parent_key, tuple(block_tokens))) # depends on the whole prefix
if key in cache: reuse(cache[key]) else: cache[key] = compute_block()
Trade-offs
Exact prefix matches only: put the stable parts first (system prompt, tools, documents) and the changing parts last.
Jetson: a robot or agent loop that re-sends the same system prompt and tool list every turn is the ideal case; Edge-LLM lists KV-cache reuse. Image tokens dominate a VLM's TTFT (VLM guide §3), so a reusable prefix is worth keeping.
Datacenter: automatic prefix caching in vLLM, RadixAttention in SGLang.
Lab:python efficient_inference.py prefix → section_prefix(): hash-chained block reuse, then cached-prefix logits vs a full forward pass. ▶vLLM's automatic prefix caching design (docs).
g
Speculative decoding and multi-token prediction
decode latency ↓↓extra compute, draft memory
Intuition. A small model guesses the next few tokens; the big model checks all of them in one forward pass. Decode is memory-bound, so checking five tokens costs about the same as generating one.
What to notice: three guesses accepted plus one token from the target itself (its correction t4′): four tokens for one target pass. Even when every guess is wrong you still get one token, so nothing is lost but the draft's time.
Expected tokens per target pass
E[tokens per pass] = (1 − αγ+1) / (1 − α) · speedup ≈ E / (1 + γ·c)
Read it aloud
α is the chance the target accepts a draft token, γ how many tokens the draft proposes, c the cost of one draft step relative to one target pass. The sum 1 + α + α² + … + αγ counts the accepted prefix plus the target's own token.
Why it exists
At batch 1 the target's weight read dominates each pass, and verifying γ + 1 positions reads the same weights. Spare compute turns into fewer passes, with exactly the target's output: identical under greedy decoding, and the same distribution under sampling thanks to the acceptance rule of Leviathan et al.
Lab: a draft with 5.2% of the target's parameters reaches α = 70.7% at γ = 4: 2.70 tokens per target pass measured (formula: 2.81), 35.5 target passes instead of 96, and the output equals the target's greedy output token for token. Rough speedup 2.70 / (1 + 4 × 0.052) = 2.24×.
Code
want = target(prefix_plus_guesses).argmax(-1)[:, -gamma-1:] # 1 pass checks all guesses
n_ok = longest_prefix_where(guesses == want[:, :gamma])
out += guesses[:, :n_ok] + want[:, n_ok] # + the target's own token
Multi-token prediction (MTP) trains the model itself with extra heads that predict tokens further ahead (Gloeckle et al., 2024); at inference the extra head is a built-in draft. DeepSeek-V3 reports 85–90% acceptance for its second token and 1.8× tokens per second. EAGLE and Medusa attach light draft heads to the target's hidden states instead of using a separate model.
Trade-offs
Gains depend on α: high for code, boilerplate and low temperature, lower for creative sampling.
At large batch, decode is less memory-bound, verification stops being free and gains shrink.
The draft and its cache need memory; for an MoE target, verifying several tokens touches more experts (MoE guide §5.8).
Jetson vs datacenter
Jetson: batch-1, memory-bound decode is the best case. TensorRT Edge-LLM supports EAGLE3 and MTP drafts; make sure the draft fits beside the target in shared DRAM.
Datacenter: for latency-sensitive, low-to-medium batch serving; vLLM and TensorRT-LLM ship EAGLE, MTP and n-gram drafts.
Intuition. Every separate kernel reads its inputs from DRAM and writes its output back. Fuse a chain of small operations into one kernel so the data stays on-chip, and launch a whole step's kernels with one call.
What to notice: the red arrows are the cost: each intermediate result makes a full trip to DRAM and back. In the fused kernel it stays in registers.
Bytes moved by a chain of elementwise kernels
unfused = Σk (readsk + writesk) · N · b vs fused = (1 + 1) · N · b
Read it aloud
Each kernel k reads its input tensors and writes one output, N numbers of b bytes each; a fused kernel reads the input once and writes the result once.
Why it exists
Elementwise operations do a few FLOPs per byte, far below the ridge, so their time is their bytes. Separately, each launch costs CPU time; at batch 1 a decode step is hundreds of small kernels, and the CPU can become the bottleneck.
Tiny example
tanh-GELU written as 9 elementwise kernels on 4M FP32 numbers: 13 reads + 9 writes = 22 tensor passes = 352 MiB, versus 32 MiB fused (11× less). At an Orin Nano's 102 GB/s that is at least 3.6 ms versus 0.33 ms. On a laptop CPU the lab measured the fused version about 2–3× faster (1.8–2.9× across runs).
Code
model = torch.compile(model) # fuses elementwise chains
model = torch.compile(model, mode="reduce-overhead") # ... and replays CUDA graphs
CUDA graphs record a sequence of kernel launches once and replay it with a single cudaGraphLaunch, skipping the Python, C++ and driver overhead of each launch; the price is static shapes and control flow (PyTorch blog). torch.compile captures your model's graph and generates fused kernels; its reduce-overhead mode adds CUDA graphs. TensorRT does both kinds of fusion when it builds an engine.
Trade-offs
Compilation time (seconds to minutes) and recompiles when shapes change.
CUDA graphs need fixed shapes: runtimes capture one graph per batch size.
Fused code is harder to debug and profile.
Jetson vs datacenter
Jetson: TensorRT fuses at build time; the CPU issuing launches is a modest Arm core, so CUDA graphs matter. Test with trtexec --useCudaGraph.
Datacenter: torch.compile for training and research; serving engines (vLLM, TensorRT-LLM) capture CUDA graphs for decode.
Lab:python efficient_inference.py fusion → gelu_tanh_unfused() vs F.gelu(x, approximate="tanh"); add --compile to try torch.compile. ▶Making Deep Learning Go Brrrr (Horace He) and the torch.compile tutorial.
i
Sparsity (2:4), pruning and distillation
memory ↓math ↑ (up to 2×)accuracy, retraining
Intuition. Zero out the least important weights in a pattern the hardware can skip, then let the original model teach the pruned one to win back what it lost.
kept weightzeroposition index
What to notice: in every group of 4 consecutive weights exactly 2 survive. Storage keeps those 2 values and a 2-bit position for each; sparse tensor cores skip the zeros.
Half the weights are kept at b bits, each with a 2-bit index. The distillation loss pulls the student's softened probabilities (logits zs divided by temperature T) towards the teacher's; the T² keeps gradient sizes comparable across temperatures (Hinton et al., 2015).
Why it exists
Random (unstructured) zeros rarely speed up a GPU. 2:4 is the pattern Ampere-and-later sparse tensor cores accelerate, at up to twice the dense math rate (Mishra et al., 2021). Pruning loses accuracy; matching a teacher's full output distribution recovers it faster than training on labels alone.
Lab: a 2:4-pruned MLP agrees with its teacher's top-1 prediction on 35.3% of inputs; after 300 distillation steps (keeping the 2:4 mask) 73.9%, and the KL drops from 0.594 to 0.084.
Code
g = w.abs().reshape(out, -1, 4)
mask = torch.zeros_like(g, dtype=torch.bool).scatter_(-1, g.topk(2, -1).indices, True)
loss = T * T * F.kl_div(F.log_softmax(z_s / T, -1), F.softmax(z_t / T, -1), reduction="batchmean")
Pruning LLMs. One-shot methods prune a trained model without retraining: SparseGPT (error compensation, like GPTQ) and Wanda (weight magnitude × activation norm). Structured pruning removes whole heads, channels or layers, so the result is a smaller dense model that runs fast everywhere; NVIDIA's Minitron pairs it with distillation and retrains on under 3% of the original data.
Trade-offs
2:4 without retraining usually costs accuracy; plan on fine-tuning or distillation.
The 2× applies to compute-bound GEMMs (prefill, large batch). Memory-bound decode gains only the 44% fewer bytes.
Distillation needs training compute and data that look like your task.
Jetson vs datacenter
Jetson: Orin's Ampere GPU has sparse tensor cores (the 275 TOPS headline is a sparse figure); TensorRT uses them with trtexec --sparsity=enable on 2:4 weights. Distilled small models are often the best edge win of all.
Datacenter: sparse numbers are the 2× column on spec sheets (H100: 1,979 vs 989.5 TFLOPS).
Intuition. Training stores much more than the weights: a gradient for every weight, the optimizer's running statistics, and every activation the backward pass will need. Each technique shrinks one of those piles.
What to notice: bytes per parameter before activations, for Llama-3.1-8B. Full Adam training is 8× inference; LoRA trains a red sliver (0.52% of the parameters) on a frozen base; QLoRA also stores the frozen base in 4-bit NF4.
BF16 weights and gradients for the maths, an FP32 copy of the weights so small updates are not rounded away, and Adam's two moment estimates in FP32: the 2Ψ + 2Ψ + 12Ψ of the ZeRO paper.
Why it exists
It tells you before you start whether a run can fit. Plain FP32 Adam (4 + 4 + 8) is also 16 B: mixed precision saves activation memory and time, not optimizer state.
Tiny example
Llama-3.1-8B: 8.03 × 10⁹ × 16 B = 128 GB before activations: more than one 80 GB H100. LoRA (r = 16 on all 7 linear layers) trains 41.9M parameters: 16.06 GB of frozen BF16 weights + 0.67 GB = 16.7 GB; QLoRA with an NF4 base (4.127 bits per weight with double quantization) 4.8 GB.
Code
bytes_per_param = 2 + 2 + 4 + 4 + 4 # W, grad, master, m, v
lora_params = sum(r * (d_in + d_out) for d_out, d_in in adapted_shapes)
Recipe (bytes per parameter: W + grad + optimizer)
per layer ≈ N·B·d·(34 + 5·h·N/d) bytes → full recompute: 2·N·B·d
Read it aloud
For a GPT layer with 16-bit activations, sequence length N, micro-batch B, hidden size d and h heads (Korthikanti et al., 2022, who write s, b, h, a for N, B, d, h); the 5·h·N²·B part is the stored attention scores, which FlashAttention removes. Checkpointing keeps only each layer's input (2·N·B·d) and recomputes the rest during backward.
Why it exists
Activations scale with tokens per step and often exceed the weights. Recomputing costs about one extra forward pass; the same paper observed 30–40% time overhead for full recomputation.
Tiny example
N = 4,096, d = 4,096, h = 32, B = 1: 3.25 GB per layer naive, 0.57 GB without stored scores, 33.6 MB with full recompute. Over 32 layers: 18.3 GB → 1.07 GB.
Lab: 8 MLP blocks save 9.00 MiB for backward; with torch.utils.checkpoint 1.00 MiB (9×, exactly the analytic count), and the gradients are bit-identical.
Code
from torch.utils.checkpoint import checkpoint
h = checkpoint(block, h, use_reentrant=False) # store h, recompute block's insides
Gradient accumulation: run K micro-batches, sum their gradients, then step: effective batch = micro-batch × K × GPUs, with activation memory set by the micro-batch alone. For a mean loss, divide each micro-batch loss by K and the update equals one big batch (up to rounding). LoRA (Hu et al.) learns W + (α/r)·B·A with B initialised to zero, so training starts exactly at the base model and merges back into one matrix afterwards; QLoRA (Dettmers et al.) keeps the frozen base in 4-bit NF4 and fine-tuned a 65B model on a single 48 GB GPU. ZeRO / FSDP (PyTorch FSDP) shard optimizer state, then gradients, then weights across GPUs.
Trade-offs
Checkpointing: +30–40% time. Accumulation: same maths, more wall-clock per update.
LoRA: far less memory, somewhat less capacity than full fine-tuning; QLoRA adds dequantization time and quantization noise.
ZeRO-3 / FSDP: needs fast interconnect; communication grows with sharding.
Jetson vs datacenter
Jetson: memory-wise, an AGX Orin 64GB or Thor 128GB can fine-tune small models with LoRA/QLoRA plus checkpointing (slowly); the 8 GB Orin Nano is for inference.
Datacenter: BF16 + FSDP/ZeRO + checkpointing + accumulation is the standard recipe.
Lab:python efficient_inference.py ckpt train → saved_activation_bytes(), RECIPES, zero_bytes_per_param(), lora_params(), LoRALinear. ▶ Hugging Face's efficient training on one GPU and the PyTorch FSDP tutorial.
k
Edge deployment workflow on Jetson
latencymemorymeasured honestly
Intuition. Export once, quantize with real calibration data into an explicit graph, build the engine on the device that will run it, then measure under a fixed power mode, after warm-up.
What to notice: only the engine build has to happen on the Jetson; export and quantization can run on a workstation. Engines are specific to the GPU and TensorRT version, so rebuild after a JetPack upgrade.
The steps, with the tools as of Oct 2026
Export.torch.onnx.export(model.eval(), example_inputs, "model.onnx"), then check the ONNX output against PyTorch on a few inputs.
Quantize explicitly with NVIDIA Model Optimizer (ModelOpt, github.com/NVIDIA/Model-Optimizer, formerly TensorRT Model Optimizer). Its ONNX PTQ inserts QuantizeLinear/DequantizeLinear (Q/DQ) nodes "following TensorRT rules" from calibration data (modes: int8, fp8, int4). Implicit INT8 calibration is deprecated in TensorRT 10 and removed in TensorRT 11, along with the precision-enabling "weak typing" builder flags such as --fp16; ModelOpt's AutoCast makes the FP16 graph explicit instead.
Build on the Jetson with the TensorRT that ships with your JetPack (TensorRT 10.16 in JetPack 7.2, June 2026, which brought Orin under JetPack 7; TensorRT 11.4 does not support JetPack yet). Use --stronglyTyped on an explicitly typed graph (the forward-compatible route), or --best on TensorRT 10 to let the builder choose precisions around the Q/DQ nodes.
LLMs and VLMs: TensorRT Edge-LLM, NVIDIA's C++ runtime for Jetson Orin and Thor, DRIVE Thor and DGX Spark: quantize and export on a host (tensorrt-edgellm-quantize, tensorrt-edgellm-export), build and run on the device (llm_build, llm_inference). Orin runs FP16, INT8 and INT4 only; Thor adds FP8 and NVFP4. It lists paged attention, FP8 KV cache, KV reuse and EAGLE3/MTP speculative decoding. TensorRT-LLM is the datacenter counterpart; its Jetson support stopped at a v0.12.0-jetson branch for AGX Orin on JetPack 6.1. vLLM and llama.cpp builds for Jetson are the Python-friendly alternatives (see Jetson AI Lab).
Fix the power mode and clocks (Jetson power docs): sudo nvpmodel -q to see the mode, sudo nvpmodel -m <id> to set it (Orin Nano 8GB Super: 0 = 15W, 1 = 25W, 2 = MAXN_SUPER; AGX Orin 64GB: 0 = MAXN, 1 = 15W, 2 = 30W default, 3 = 50W), and sudo jetson_clocks to pin CPU, GPU and memory clocks to the mode's maximum. Watch memory, clocks and power with tegrastats.
Measure after warm-up, many iterations, and report the median and p90; report TTFT and TPOT separately, with power mode, JetPack, precision, batch and context length.
bash
python -m modelopt.onnx.quantization --onnx_path=model.onnx --quantize_mode=int8 \
--calibration_data_path=calib.npy --output_path=model.int8.onnx # can run on a workstation
trtexec --onnx=model.int8.onnx --saveEngine=model.engine --best # TensorRT 10 (JetPack)
sudo nvpmodel -q && sudo jetson_clocks
trtexec --loadEngine=model.engine --warmUp=500 --iterations=200 --useCudaGraph
Time to first token (prefill, compute-bound) plus one time-per-output-token (decode, memory-bound) for each further token.
Why it exists
The two phases respond to different fixes (§2), so one "latency" number hides which one to work on.
Tiny example
From the VLM guide §8 (Cosmos-Reason2-2B with vLLM on an Orin Nano Super): image TTFT 75 ms and TPOT 17 ms, so a 100-token answer takes 75 + 99 × 17 = 1,758 ms, 96% of it decode.
Code
r = bench(lambda: model(x), warmup=3, iters=20) # cold call, then median and p90
print(r["median"], r["p90"]) # on a GPU: torch.cuda.synchronize() first
Trade-offs
Engines are tied to device and TensorRT version; keep the ONNX and the build command, not just the engine.
Calibration data must look like deployment inputs, or INT8 scales will be wrong.
DLA (Orin's deep-learning accelerators) runs only supported layers in INT8/FP16, and TensorRT 11.4 has no JetPack DLA support.
Jetson vs datacenter
Jetson: the whole card. Memory is shared with the OS, so the "Other" field in §1 is real.
Datacenter: same ModelOpt checkpoints (FP8, NVFP4) feed TensorRT-LLM, vLLM or SGLang.
Lab:python efficient_inference.py bench → bench() (cold call, warm-up, median, p90) and the Jetson checklist. Deeper: the VLM guide §8 for a real three-runtime comparison on an Orin Nano. ▶TensorRT Edge-LLM on Jetson (Jetson AI Lab tutorial: Qwen3-4B INT4 AWQ on an Orin Nano, Cosmos-Reason2-8B NVFP4 on Thor).
4 Decision guide
Find your symptom, try the first column first. Measure before and after (card k).
My problem is…
Try first
Then
Weights don't fit
INT4 weight-only (AWQ/GPTQ, g = 128); FP8 or NVFP4 on Thor / H100 (c)
a smaller or distilled model (i); for MoE, total params must fit
KV cache runs out (long context, many users)
cap the max context; FP8 KV cache (c3); a GQA/MLA model (b)
fix nvpmodel, run jetson_clocks, warm up, report median and p90 (k)
watch tegrastats for throttling and memory pressure
5 Review: takeaways, self-check, exercises
Key takeaways
Small-batch decode is memory-bound: time per token ≈ bytes read ÷ bandwidth. Every byte you remove is speed.
Memory = weights + KV cache + activations + runtime. Find the biggest pile before choosing a fix.
Quantization is the biggest single lever at the edge: INT4 weights are about 4× fewer bytes than BF16, and finer granularity is what keeps accuracy when outliers exist.
The KV cache grows with context × batch. GQA/MLA shrink it in the model; paging, prefix sharing and KV quantization shrink it in the server.
FlashAttention, fusion and CUDA graphs change memory traffic and launch overhead, not the maths.
Speculative decoding turns spare compute into fewer memory-bound passes, with identical output.
Training needs about 16 B per parameter with Adam, plus activations; LoRA/QLoRA, checkpointing and sharding each attack one term.
On Jetson: build engines on the device, quantize with explicit Q/DQ, fix the power mode, warm up, report median and p90.
Self-check
1. Does Qwen3-8B (8.19B parameters) fit on an 8 GB Orin Nano in BF16? In INT4 with g = 128?
Answer
BF16: 8.19 × 10⁹ × 2 B = 16.4 GB, about twice the whole device, before any cache. INT4 at 4.25 bits: 8.19 × 10⁹ × 4.25 / 8 = 4.35 GB (4.05 GiB), which leaves room for a few GiB of cache and runtime.
2. How many bytes of KV cache does Qwen3-8B (36 layers, 8 KV heads, dk = 128) need per token in BF16, and for one 32K-token sequence?
Answer
2 × 36 × 8 × 128 × 2 B = 147,456 B = 144 KiB per token. × 32,768 = 4.5 GiB. In FP8 it halves to 2.25 GiB.
3. Upper bound on batch-1 decode speed for Llama-3.1-8B with 4.25-bit weights on an AGX Orin (204.8 GB/s), ignoring the cache?
Answer
Weights: 8.03 × 10⁹ × 4.25 / 8 = 4.27 GB per token. 204.8 / 4.27 ≈ 48 tokens/s. Real runtimes reach roughly half to three quarters of that.
4. Why does batch-1 decode use under 1% of an Orin Nano's tensor cores, and what batch would reach the ridge with FP16 weights?
Answer
Each FP16 weight (2 bytes) is used for 2 FLOPs, so AI ≈ 1 FLOP/byte, while the ridge is 17 × 10¹² / 102 × 10⁹ ≈ 167 FLOP/byte: attainable ≈ 1 × 102 GFLOP/s = 0.6% of 17 TFLOPS. AI grows with the number of tokens per weight read, so a batch of about 167 sequences would reach the ridge (the KV-cache reads do not shrink with batching, so in practice even more).
5. Symmetric INT8 for weights whose largest magnitude is 0.5: what are the scale, the stored integer for w = 0.1, and the error?
6. Per-channel weight scales fix an outlier output channel. Why don't they fix an outlier activation channel in W8A8, and what does?
Answer
An activation channel is an input (reduction) dimension: it is shared by every output, so per-output-channel weight scales can't isolate it, and quantizing the activations with one scale per token or tensor wastes most levels on that channel. SmoothQuant divides the channel by sj and multiplies the matching weight column by sj (exact in full precision), moving the difficulty into the weights, which quantize easily. LLM.int8() instead keeps the outlier dimensions in 16-bit.
7. A draft is accepted with α = 0.6 and proposes γ = 3 tokens. Expected tokens per target pass?
Answer
(1 − 0.6⁴) / (1 − 0.6) = (1 − 0.1296) / 0.4 = 2.18 tokens per pass. If a draft step costs c = 0.05 of a target pass: 2.18 / (1 + 3 × 0.05) ≈ 1.89× speedup.
8. Three requests end at 100, 1,000 and 37 tokens. How much KV space is wasted with 16-token blocks, versus reserving 2,048 tokens each?
9. Can you fully fine-tune Qwen3-1.7B with mixed-precision Adam on a 24 GB RTX 4090? What would you change?
Answer
1.721 × 10⁹ × 16 B = 27.5 GB before activations: no. 8-bit Adam (10 B/param: 17.2 GB) plus activation checkpointing and a small micro-batch with gradient accumulation could fit; LoRA or QLoRA fits easily.
10. Does FlashAttention reduce attention's FLOPs? How big is the score matrix it avoids at N = 4,096 with 32 heads in FP16?
Answer
No: same FLOPs, same result up to rounding. It avoids writing and re-reading 32 × 4,096² × 2 B = 1 GiB per layer per sequence, keeping only per-row running max and sum.
Hands-on exercises
All against efficient_inference.py. Each says how to check yourself.
Make the outlier worse.easy In section_quant() set OUTLIER_GAIN = 100. Predict which rows of the table change. Check: the per-tensor INT8 error on the normal rows grows about 3× (0.228 → 0.729 in our run), while the per-channel error on the normal rows does not change at all: assert it equals the ×20 value.
E5M2 for weights.easy Copy quant_fp8_tensor() to use torch.float8_e5m2 (scale amax to 57,344). Check: its output error is larger than E4M3's, because it has one mantissa bit fewer.
Pick γ.medium In section_spec() loop γ over 1, 2, 4, 8 and print tokens per pass and the speedup estimate E / (1 + γ·c). Check: tokens per pass keep rising with γ (1.69, 2.19, 2.70, 3.15 in our run) but the speedup estimate flattens near γ = 4 (2.24× vs 2.22× at γ = 8); the output still equals greedy (the existing assert).
Quantize the KV cache.medium In CausalSelfAttention.forward, fake-quantize k per channel and v per token to INT8 before caching (reuse quant_sym). Check: generate_cached still matches generate_recompute (all 160 tokens did in our run), and teacher-forced logits differ by less than 1% (0.05% here).
Share prefix blocks for real.hard Extend PagedKVCache so a new sequence can start from another's full blocks using BlockAllocator.share(), with copy-on-write when it appends into a shared, partly filled block. Check: gather() returns the right tensors for both sequences and the pool uses fewer blocks.
Checkpoint every k blocks.hard Change section_ckpt() to checkpoint segments of k blocks. Derive the stored bytes (L/k inputs + 9·k·B·d for the segment being recomputed) and find the k that minimises the peak. Check the stored part with saved_activation_bytes() and that gradients stay bit-identical.
Dettmers et al. (2022). LLM.int8(); Xiao et al. (2022). SmoothQuant; Frantar et al. (2022). GPTQ; Lin et al. (2023). AWQ; Ashkboos et al. (2024). QuaRot; Liu et al. (2024). SpinQuant.