0 Start here
Read the primer first. Transformer, step by step follows 3 tokens through a toy model (d = 4, 2 heads) with every number shown. This guide assumes it and links back to its steps for toy numbers.
Open the primer →What this guide adds
- Real shapes: batch B, h heads, n_kv K/V heads, L layers.
- Every op of a forward pass with its equation, shapes, FLOPs and bytes moved.
- The inference lifecycle: prefill (the whole prompt in one pass) and decode (one token per step against the KV cache, the stored keys and values of earlier tokens).
- A matrix picture for every matmul, and a CUTLASS walk-through of how a GPU tiles one (§2.2).
- Time bounds on a Jetson AGX Orin (NVIDIA's embedded GPU module): time to first token (TTFT) from the FLOPs (floating-point operations), time per output token (TPOT) from the bytes moved.
- Memory: weights, KV cache, activations. Which optimization helps which phase.
- Prerequisites: the primer, matrix shapes, PyTorch tensors.
Reading map
| § | Question it answers | Primer steps |
|---|---|---|
| 1 | What exactly is computed, with which shapes and how many weights? | 19 |
| 2 | Prefill: what does each op cost when the whole prompt goes in at once? What lands in the KV cache? | 2–17 |
| 3 | Decode: why does every new token cost a full read of the weights and the cache? | 18 |
| 4 | Which phase is compute-bound, which is memory-bound, and what helps each? | |
| 5, 6 | What fills DRAM, and which optimization cuts what? | |
| 7, 8 | What changes for training, and since 2017? | 16 |
| 9 | Code, self-check, exercises. |
Abbreviations: a word with a dotted underline shows its meaning on hover or tap; all of them are listed in §1. Equations first: each cost is given as a formula in the symbols of §1, with at most one reference number.
Numbers: every worked number is printed by python3 transformer/inference_math.py (standard library only).
Colours (the same in every guide): data, residual streamweightsattention, mixing across tokensper-token FFN, outputscostcontext
🎬 Learn it visually
- Attention in transformers, step-by-step (3Blue1Brown, 26 min). Queries, keys, values and heads, animated. For the whole pipeline first: Chapter 5, Transformers, the tech behind LLMs (27 min).
- The Illustrated GPT-2 (Jay Alammar). A decoder-only model picture by picture, including processing one new token at a time.
- Transformer Explainer (Georgia Tech, interactive). GPT-2 in the browser: inspect every step of a forward pass.
- Let's build GPT: from scratch, in code, spelled out (Andrej Karpathy, 1 h 56 min). The best companion to §9 and the labs.
- The Annotated Transformer (Harvard NLP). The 2017 paper interleaved with runnable PyTorch.
Quick answers
Short answers to the questions this guide is built around. Open a question for the formula and a link to the full derivation.
What decides whether an operation is memory-bound or compute-bound?
Its arithmetic intensity, AI = FLOPs ÷ bytes moved to or from DRAM. A GPU runs an op at min(peak, AI × bandwidth), so the ridge peak ÷ bandwidth splits the two: ≈ 208 FLOP/byte on AGX Orin (42.5 TFLOPS ÷ 204.8 GB/s). Below the ridge, bytes set the time; above it, FLOPs do. More: §4 →
Why is LLM decode memory-bound?
Each decode step pushes only B new rows through every weight matrix, so each weight byte read does about 2·B FLOPs: AI ≈ B, far below 208 at B = 1. Time per token is then bytes ÷ bandwidth: TPOT ≥ (weights + KV cache) ÷ BW = 15.46 GB ÷ 204.8 GB/s ≈ 75.5 ms for the reference 7B model at t = 4,096. More: §3.3 →
Why is prefill compute-bound?
Prefill sends all N prompt tokens through each weight matrix at once, so a weight GEMM has M = B·N rows and, in FP16, AI = 1 / (1/M + 1/K + 1/P), in the thousands (1,365 for W_O at N = 4,096). That is above the ridge, so TTFT ≈ FLOPs ÷ peak: 61.57 TFLOP, ≥ 1.45 s at N = 4,096. More: §2.6 →
How big is the KV cache?
bytes = 2·L·B·t·n_kv·d_k·b: a K row and a V row per layer for every cached token. For the reference model (L = 32, n_kv = 32, d_k = 128, FP16) that is 512 KiB per token and 2 GiB at t = 4,096, and every decode step reads all of it. More: §2.4 →
What does grouped-query attention (GQA) save?
GQA keeps h query heads but only n_kv K/V heads, each shared by h / n_kv query heads. The cache and its per-step reads shrink by n_kv / h (¼ for 32 → 8); the attention FLOPs do not change, so decode attention AI rises from 1 to h / n_kv. More: §3.5 →
Does splitting d into heads lose information?
No. Reshaping Q = X̂·W_Q into h blocks of d_k columns is the same as giving head i its own [d × d_k] matrix, the i-th block of columns of W_Q. Every head still reads the whole d-dimensional token vector; only the outputs are split. More: block 4 →
Why does causal attention do only about half the work?
Token i attends only to tokens j ≤ i. With T = N / 128 tiles per side, only T(T + 1)/2 of the T² score tiles contain an allowed pair, so a causal kernel skips the rest outright and masks only the diagonal tiles. More: block 5 →
What does FlashAttention change?
Not the arithmetic, the memory traffic. Unfused attention writes and rereads the [N × N] scores, ≈ 6·b·B·h·N² bytes. FlashAttention streams K and V tiles through on-chip memory with an online softmax and writes only O, so only Q, K, V and O cross DRAM. More: blocks 5–8 fused →
How much does quantization speed up decode?
Weight bytes = params × bits ÷ 8, and decode time ≈ bytes ÷ bandwidth. FP16 → INT8 halves the weight bytes and INT4 quarters them, so the weight part of TPOT drops about 2× and 4× (≈ 65 → 16 ms for the reference model); the KV cache is unchanged unless it is quantized too. More: §5 →
1 Notation and the model as equations
| Symbol | Meaning | Reference | GPT-2 small | Primer toy |
|---|---|---|---|---|
| B | batch: sequences processed together | 1 | 1 | 1 |
| N | prompt length: rows in one prefill pass | 4,096 | 1,024 | 3 |
| t | cached length: K/V rows one decode step attends to | 4,096 | – | 4 |
| d | token vector size in the residual stream (d_model; also "model width", "hidden size"); every weight matrix is sized by it | 4,096 | 768 | 4 |
| h | query heads | 32 | 12 | 2 |
| n_kv | K/V heads: distinct key/value heads, each shared by h / n_kv query heads (= h for MHA; fewer for GQA/MQA, §3.5) | 32 | 12 | 2 |
| d_k | head size, d / h (also d_v) | 128 | 64 | 2 |
| d_ff | FFN hidden width | 16,384 = 4d | 3,072 | 8 |
| L | layers (blocks) | 32 | 12 | 1 |
| V | vocabulary size | 50,257 | 50,257 | 8 |
| b | bytes per element | 2 (FP16) | 2 | – |
Reference config (the primer's 7B-class model, step 19; GPT-3 6.7B shape): d = 4096, L = 32, h = n_kv = 32, d_k = 128, d_ff = 4d, V = 50,257, tied LM head, a 2,048-row learned position table, FP16 (16-bit floats, b = 2 bytes). 6.66 B parameters, 13.31 GB of weights.
Device: Jetson AGX Orin 64GB: 204.8 GB/s of LPDDR5 DRAM shared by CPU and GPU, ≈ 42.5 dense FP16 TFLOPS (10¹² FLOPs per second) on the Tensor Cores of 16 SMs (streaming multiprocessors). Ridge = peak ÷ bandwidth ≈ 208 FLOP/byte: an op needs more FLOPs per byte than that to be compute-bound (§4, device table).
Conventions: [m × k]·[k × n] costs 2·m·k·n FLOPs. Times are lower bounds at 100% of peak: t = max(FLOPs ÷ peak, bytes ÷ bandwidth). Bandwidth maths in GB (10⁹ B); tensor sizes in MiB/GiB (2²⁰, 2³⁰ B). Printed by inference_math.py.
The forward pass, numbered
Decoder-only, pre-norm, as in transformer.py and the primer. Prefill runs it on N rows; decode (§3) on 1 row per sequence.
| # | Equation | Shape |
|---|---|---|
| 1 | X = E[ids] + P[0:N] | [B, N] → [B, N, d] |
| for ℓ = 1 … L (weights of layer ℓ) | ||
| 2 | X̂ = LN₁(X) | [B, N, d] |
| 3 | [Q | K | V] = X̂ · W_QKV | [B, N, d]·[d, (h + 2·n_kv)·d_k] |
| 4 | Q → [B, h, N, d_k]; K, V → [B, n_kv, N, d_k] | view + transpose, no arithmetic |
| 5 | S = Q·Kᵀ / √d_k + M_c | [B, h, N, N] |
| 6 | A = softmax(S) (row-wise) | [B, h, N, N] |
| 7 | O = A · V | [B, h, N, d_k] |
| 8 | X ← X + merge(O) · W_O | [B, N, h·d_k]·[h·d_k, d] → [B, N, d] |
| 9 | X ← X + GELU(LN₂(X)·W₁ + b₁)·W₂ + b₂ | [B, N, d] → [B, N, d_ff] → [B, N, d] |
| after the stack | ||
| 10 | z = LN_f(X[:, N−1]) · Eᵀ | [B, d]·[d, V] → [B, V] |
| 11 | next ~ softmax(z / T) | [B] |
M_c is the causal mask, an [N × N] constant added to the scores: (M_c)ij = 0 if j ≤ i, −∞ if j > i, so softmax gives future tokens weight 0 (§2, block 6). It has no weights; the subscript c keeps it apart from M, the row count of a GEMM (§2.2). Eᵀ in (10) is the tied embedding table. In (3) the K and V columns are also written to the KV cache.
Parameters
| Tensor | Shape | Count | Reference |
|---|---|---|---|
| E (embedding = LM head, tied) | [V, d] | V·d | 205,852,672 |
| P (learned positions) | [N_max, d] | N_max·d | 8,388,608 |
| per block | |||
| W_QKV = [W_Q | W_K | W_V] | [d, 3d] | 3d² | 50,331,648 |
| W_O | [d, d] | d² | 16,777,216 |
| W₁, W₂ | [d, 4d], [4d, d] | 8d² | 134,217,728 |
| LN₁, LN₂ (γ, β; ignored below) | 4 × [d] | 4d | 16,384 |
| Block | 12d² | 201,326,592 | |
| Model | ≈ 12·L·d² + V·d (+ N_max·d) | 6,656,692,224 | |
Attention holds 4d² and the FFN 8d² of each block. Biases and norms are under 0.01% and ignored, as in the primer. GPT-2 small in transformer.py, biases and norms included: 124,402,944 (count_parameters()). Toy count (248): primer step 19. 🎬 3Blue1Brown ch. 6, “Counting parameters” (from 15:44)
- GEMM / GEMV
- general matrix × matrix / matrix × vector multiply. A GEMM with M rows reuses each weight M times; a GEMV uses it once.
- AI
- arithmetic intensity = FLOPs ÷ bytes moved. Below the ridge an op is memory-bound, above it compute-bound (§4).
- TTFT / TPOT
- time to first token (prefill) / time per output token (one decode step). Latency ≈ TTFT + (N_out − 1)·TPOT.
Abbreviations and terms
Words with a dotted underline show their meaning on hover or tap (the first use in each section, block and drop-down). The full list:
All abbreviations and terms
Model parts
- LN
- LayerNorm (layer normalization): scale each token's vector to mean 0, variance 1, then apply γ, β (block 2)
- RMSNorm
- root-mean-square norm: LayerNorm without the mean, x / √mean(x²)
- FFN
- feed-forward network: the per-token two-layer network d → d_ff → d (block 11)
- MLP
- multilayer perceptron; here the same thing as the FFN
- GELU
- Gaussian error linear unit, x·Φ(x): a smooth ReLU, used in the FFN
- ReLU
- rectified linear unit, max(0, x)
- SwiGLU
- Swish-gated linear unit, silu(x·W_g) ⊙ (x·W_u): the FFN of Llama-style models
- GLU
- gated linear unit: one projection gates another by an elementwise product
- QKV
- query, key, value: the three projections of each token that attention uses (block 3)
- MHA
- multi-head attention: h heads, each with its own K and V head (n_kv = h)
- GQA
- grouped-query attention: n_kv < h K/V heads, each shared by h/n_kv query heads; GQA-8 means n_kv = 8
- MQA
- multi-query attention: one K/V head for all query heads (n_kv = 1)
- MLA
- multi-head latent attention (DeepSeek): caches a small latent vector instead of K and V
- KV
- key–value, as in KV cache: the K and V rows of every past token, kept per layer so decode does not recompute them
- RoPE
- rotary position embedding: rotates pairs of q and k dimensions by an angle that grows with the position
- LM
- language model; the LM head is the final [d × V] matrix that turns a vector into one score (logit) per vocabulary token
- MoE
- mixture of experts: many FFNs, of which a router picks a few per token
- EOS
- end-of-sequence token: generation stops when it is sampled
Cost and speed
- FLOP
- floating-point operation, one multiply or one add. A dot product of K pairs is 2·K FLOPs
- GFLOP
- 10⁹ FLOPs (MFLOP 10⁶, TFLOP 10¹², PFLOP 10¹⁵): a count, not a rate
- TFLOPS
- 10¹² FLOPs per second: a rate
- AI
- arithmetic intensity = FLOPs ÷ bytes moved to or from DRAM. Below the device's ridge an op is memory-bound (§4)
- BW
- memory bandwidth: bytes per second between DRAM and the chip (204.8 GB/s on AGX Orin)
- TTFT
- time to first token: the prefill latency
- TPOT
- time per output token: the latency of one decode step
- tok/s
- tokens per second
- GEMM
- general matrix–matrix multiply, [M × K]·[K × P]: each weight read is reused M times
- GEMV
- general matrix–vector multiply (M = 1): each weight read is used once
- MiB
- 2²⁰ bytes (KiB 2¹⁰, GiB 2³⁰): used for tensor sizes
- GB
- 10⁹ bytes (KB 10³, MB 10⁶): used with bandwidth, so GB ÷ GB/s gives seconds
Number formats
- FP32
- 32-bit floating point, 4 bytes
- FP16
- 16-bit floating point, 2 bytes: the inference default in this guide
- BF16
- bfloat16: 16 bits with FP32's exponent range, common in training
- FP8
- 8-bit (FP4: 4-bit) floating point; Tensor Cores on Ada, Hopper and Blackwell GPUs (FP4: Blackwell), not Orin
- INT8
- 8-bit (INT4: 4-bit) integers, stored with a floating-point scale per group of values
- W8A8
- 8-bit weights and 8-bit activations, so the matmul itself runs in INT8
- AWQ
- activation-aware weight quantization: an INT4 weight-only method
- Q/DQ
- quantize / dequantize node pair that marks a tensor's precision in an ONNX graph
GPU hardware
- GPU
- graphics processing unit
- CPU
- central processing unit
- SM
- streaming multiprocessor: one of the GPU's cores, with its own Tensor Cores, registers and shared memory. AGX Orin has 16
- CTA
- cooperative thread array = thread block: threads that run on one SM and share its shared memory
- warp
- 32 threads that execute the same instruction together
- Tensor Core
- the matrix-multiply unit inside each SM
- MMA
- matrix multiply–accumulate: one Tensor Core instruction, e.g. mma.sync m16n8k16 = [16 × 16]·[16 × 8] + C
- FMA
- fused multiply–add, a·b + c: 2 FLOPs in one instruction
- ALU
- arithmetic logic unit
- SRAM
- on-chip memory: registers, shared memory, L1 cache. Fast, small
- DRAM
- off-chip main memory: slow, large. LPDDR5 on Jetson, HBM on data-centre GPUs
- LPDDR5
- low-power DDR5 DRAM, shared by Orin's CPU and GPU
- HBM
- high-bandwidth memory: stacked DRAM next to a data-centre GPU
- L2
- the cache shared by all SMs, between them and DRAM
- TMA
- Tensor Memory Accelerator: Hopper's asynchronous copy engine
- cp.async
- Ampere's asynchronous copy from DRAM into shared memory: loads overlap maths
- AGX Orin
- Jetson AGX Orin: NVIDIA's embedded module, Ampere GPU (compute capability 8.7, sm_87) with 64 GB LPDDR5
- A100
- NVIDIA data-centre GPUs: A100 (Ampere), H100 (Hopper)
- SXM
- NVIDIA's socketed server-GPU form factor
Software
- CUDA
- NVIDIA's GPU programming platform and C++ dialect
- CUTLASS
- CUDA Templates for Linear Algebra Subroutines: NVIDIA's open-source C++ library of GEMM building blocks (deep dive in block 3)
- CuTe
- CUTLASS's layout and tensor library, the base of CUTLASS 3 and its Python DSL
- cuBLAS
- NVIDIA's BLAS (basic linear algebra) library
- TensorRT
- NVIDIA's inference compiler and runtime; TensorRT-LLM adds LLM serving pieces
- ONNX
- Open Neural Network Exchange: a model file format between frameworks
- vLLM
- an open-source LLM serving engine; introduced PagedAttention
- LoRA
- low-rank adaptation: fine-tune small added matrices instead of all weights (QLoRA: on a 4-bit base model)
- ZeRO
- Zero Redundancy Optimizer: shards optimizer state across GPUs
Model families
- LLM
- large language model
- VLM
- vision–language model
- VLA
- vision–language–action model (robot control)
- ViT
- vision transformer
- BEV
- bird's-eye view: camera features mapped to a top-down grid
- GPT
- generative pre-trained transformer: OpenAI's decoder-only family
- BERT
- Bidirectional Encoder Representations from Transformers: encoder-only
- T5
- Text-to-Text Transfer Transformer: encoder–decoder
- NLP
- natural language processing
- OS
- operating system
Number formats on one line: FP16, BF16, FP8, FP4, INT8, INT4
A float stores x = (−1)sign · 1.m · 2e − bias: exponent bits set the range, mantissa bits set how many values fit between consecutive powers of 2, so the relative step is 2−mantissa bits at every size. An integer format stores x ≈ s · q with q evenly spaced and one floating-point scale s per tensor, channel or group.
| Format | Bits | Sign / exp / mantissa | Largest | Relative step | Tensor Cores |
|---|---|---|---|---|---|
| FP32 | 32 | 1 / 8 / 23 | 3.4·10³⁸ | 2⁻²³ | all (TF32 on Ampere+) |
| FP16 | 16 | 1 / 5 / 10 | 65,504 | 2⁻¹⁰ | Volta+, Orin |
| BF16 | 16 | 1 / 8 / 7 | 3.4·10³⁸ | 2⁻⁷ | Ampere+, Orin |
| FP8 E4M3 | 8 | 1 / 4 / 3 | 448 | 2⁻³ | Ada, Hopper, Blackwell |
| FP8 E5M2 | 8 | 1 / 5 / 2 | 57,344 | 2⁻² | Ada, Hopper, Blackwell |
| FP4 E2M1 | 4 | 1 / 2 / 1 | 6 | 2⁻¹ | Blackwell (with a scale per 16 or 32 values) |
| INT8 | 8 | q ∈ −128 … 127 | 127·s | s / x (uniform step s) | Turing+, Orin |
| INT4 | 4 | q ∈ −8 … 7 | 7·s | s / x | usually weight-only: dequantized to FP16 in the kernel |
2 Prefill: the whole prompt in one pass
Input: ids [B, N]. One forward pass over all N rows. Output: the KV cache of every layer, and the logits (one score per vocabulary token) of the last row, from which the first output token is sampled. Every weight GEMM (general matrix–matrix multiply) has M = B·N rows, so prefill is compute-bound (§2.6).
What to notice: one block is two read-modify-add branches on a residual stream that keeps the shape [B, N, d] through all L blocks. The bottom row opens the attention box: only the orange steps mix rows (tokens), and they carry the N² terms. Click any box to open its details below.
- 1Read: a branch copies x off the stream and normalizes it (LN).
- 2Compute: attention moves information between tokens; the FFN (d → 4d → d) transforms each token alone.
- 3Add back: x ← x + f(LN(x)).
Each block opens to: the equation, a matrix picture with prefill and decode shapes, shapes in → out, FLOPs, bytes moved, a kernel note, the decode shapes (§3), a PyTorch line and the matching primer step. The red figures are the reference config at B = 1, N = 4,096, FP16, one layer, on AGX Orin. Bytes are unfused: the op reads its inputs from DRAM and writes its output once. The badge says which roof binds the op in prefill.
2.1 Into the stack
- Eq
- X = E[ids] + P[0:N]
- Shape
- ids [B, N] → [B, N, d]; E [V, d], P [N_max, d]
- FLOPs
- B·N·d adds 16.78 M
- Bytes
- b·(B·N·d + N·d + B·N·d) = b·(2·B·N·d + N·d): read B·N rows of E, read N rows of P (shared by the batch), write B·N rows of X 96 MiB, 0.49 ms
- Kernel
- a gather plus an add, one kernel, no matmul. RoPE models have no P: they rotate q and k inside attention (§8).
- Decode
- [B, 1] → [B, 1, d]: one row of E and the row P[t − 1]
- Toy
- primer steps 2–3
x = tok_emb(ids) + pos_emb(torch.arange(N, device=ids.device)) # [B, N, d]; GPT-2: no sqrt(d) scale
GPU kernel deep dive
- A gather, not a GEMM. Each thread block copies one token's row of E (d·b bytes) and adds P's row. Nothing is reused, so time = bytes ÷ BW = b·(2·B·N·d + N·d) ÷ BW. Read more: GPU MODE lectures (lecture 4: compute and memory architecture).
- Decode: one row. d·b bytes per step is microseconds of DRAM traffic; the kernel launch costs more than the work, which is why decode engines fuse or graph-capture these small ops (block 12). Read more: cookbook card h, fusion and CUDA graphs.
- Eq
- LN(x) = γ ⊙ (x − μ) / √(σ² + ε) + β; RMSNorm(x) = γ ⊙ x / √(mean(x²) + ε)
- Shape
- [B, N, d] → [B, N, d]; μ, σ² per row over d (σ² divides by d); γ, β [d]
- FLOPs
- ≈ 7·B·N·d (RMSNorm ≈ 4·B·N·d) 117 M
- Bytes
- 2·b·B·N·d 64 MiB, 0.33 ms
- Kernel
- one row reduction. A fused kernel finds μ and σ² in one sweep (Welford) and is merged with the residual add before it (§6).
- Decode
- [B, 1, d]: 8 KiB in and out; tiny, but still one kernel launch
- Toy
- primer step 4
Why it exists: the residual stream grows as blocks add to it; LN feeds each sub-layer unit-scale inputs, so softmax and GELU stay in range. Pre-norm (here) normalizes the branch input; the 2017 paper normalized after the add (§8).
y = F.layer_norm(x, (d,), gamma, beta, eps=1e-5) # = nn.LayerNorm(d); Llama: nn.RMSNorm(d) (PyTorch >= 2.4)
🎬 Karpathy, “layernorm” (from 1:32:51)
GPU kernel deep dive
- One row per warp. Each of the 32 lanes holds d/32 of the row's values in registers; μ and σ² come from warp-shuffle reductions, then the lane normalizes its values and writes them: one read, one write. Read more: Triton tutorial: layer norm.
- Memory-bound by construction. ≈ 7 FLOPs per element against 2·b bytes (one read, one write): AI ≈ 7 / (2b) = 1.75 ≪ 208. Faster ALUs do nothing for it. Read more: NVIDIA, GPU performance background.
- Fused add + norm. The residual add (block 10) and the next norm in one kernel: read X and Y, write X + Y (the stream) and its normalized copy. It saves one read of the stream, b·B·N·d bytes per pair, and one launch. Read more: cookbook card h, fusion and CUDA graphs.
- Decode: launch-bound. d·b bytes in and out: at batch 1 the CPU cost of launching the kernel can exceed its GPU time. Read more: Horace He, Making deep learning go brrrr.
2.2 Attention, step by step
Read it aloud: each head i projects every row with its own [d × d_k] matrices, runs causal attention over the rows and returns [N, d_k]; the h results are glued side by side and mixed by W_O [h·d_k × d]. Blocks 3–9 compute exactly this for all heads at once. Toy numbers: primer steps 6–12.
FLOPs = 2·M·K·P, bytes ≈ b·(M·K + K·P + M·P), AI = (2/b) / (1/M + 1/K + 1/P)
Read it aloud: each of the M·P outputs is a dot product of K pairs, one multiply and one add each. In FP16 (b = 2), AI = 1 / (1/M + 1/K + 1/P): the smallest of the three sizes sets it. (P is the output width, because N is the prompt length.)
- Prefill weight GEMMs: M = B·N, and K, P are multiples of d. All three are large: AI in the thousands, compute-bound.
- Decode: M = B, so AI ≈ B. Every weight read makes only B outputs: memory-bound.
- Attention, per head: K or P is d_k, so AI < d_k = 128, under Orin's ridge of 208: memory-bound unless fused (FlashAttention).
The pictures: A sits on the left, B on top, C where they meet, so C[i, j] lines up with row i of A and column j of B. Hover or tap a cell of C. Each picture switches between prefill and decode shapes. Toy numbers for the same products: primer steps 6–15.
- Eq
- [Q | K | V] = X̂ · W_QKV, W_QKV = [W_Q | W_K | W_V]
- Shape
- [B, N, d]·[d, (h + 2·n_kv)·d_k] → [B, N, (h + 2·n_kv)·d_k] (= [B, N, 3d] for MHA)
- FLOPs
- 2·B·N·d·3d = 6·B·N·d² 412.32 GFLOP, 9.70 ms
- Bytes
- b·(B·N·d + 3d² + 3·B·N·d) 224 MiB · AI 1,755
- Kernel
- one GEMM on Tensor Cores instead of three (transformer.py keeps three nn.Linear; same maths). M = B·N = 4,096 rows reuse every weight 4,096 times.
- Cache
- the K and V columns are what prefill writes to the KV cache (§2.4).
- Decode
- [B, 1, d] → [B, 1, 3d]: 100.66 MFLOP over 96 MiB of weights, AI ≈ 1
- Toy
- primer step 6
q, k, v = (x_hat @ W_qkv).split([h * d_k, n_kv * d_k, n_kv * d_k], dim=-1)
GPU kernel deep dive
- Tiling on Tensor Cores. A thread block owns one BM × BN output tile and loops over K = d in BK-wide slices staged in shared memory; warps issue Tensor Core MMAs (16 × 8 × 16 FP16 on Ampere, Orin's architecture). Each staged value is reused BN or BM times. Step through it in the CUTLASS deep dive below. Read more: Boehm, How to optimize a CUDA matmul; NVIDIA, Matrix multiplication background.
- Prefill GEMM vs decode GEMV. AI = 1 / (1/M + 1/d + 1/(3d)). Prefill: M = B·N, compute-bound. Decode: M = B, so the same op becomes a GEMV that streams all 3d² weights for 6·B·d² FLOPs: AI ≈ B, paced by bandwidth. Read more: NVIDIA, Matrix multiplication background; cookbook §2, roofline.
- One GEMM, and K, V written in place. Fusing Q, K and V reads X̂ once instead of three times (2·b·B·N·d bytes less per layer) and launches once. The epilogue can apply RoPE and write K and V straight into the cache layout. Read more: cookbook card h, fusion and CUDA graphs.
- Split-K for small M. With M = B ≤ 8 there are only ⌈P/BN⌉ output tiles to hand out; split-K also cuts the K loop into s parts on s thread blocks and adds the s partial sums, so all 16 SMs of an AGX Orin stream weights. Read more: CUTLASS deep dive below; CUTLASS, Efficient GEMM in CUDA.
- Weight-only INT4 GEMV. The kernel loads 4-bit weights and dequantizes them in registers just before the FMA: weight bytes drop from 2 to 0.5 per weight while the maths stays FP16, so decode AI ≈ 4·B. Decode speeds up; prefill barely changes. Read more: cookbook card c, quantization.
Deep dive: how CUTLASS tiles this GEMM on the GPU (thread blocks, shared memory, Tensor Cores, epilogue)
CUTLASS (CUDA Templates for Linear Algebra Subroutines) is NVIDIA's open-source C++ library of GEMM building blocks; cuBLAS and TensorRT kernels follow the same plan. One GEMM D = f(α·A·B + β·C), [M × K]·[K × P], is cut into nested tiles, and each level reuses data from a faster memory:
| Level | What it owns | Data lives in | Reuse |
|---|---|---|---|
| Grid | one CTA (thread block) per BM × BN tile of C: ⌈M/BM⌉·⌈P/BN⌉ CTAs | DRAM, L2 | CTAs that run together share A row panels and B column panels in L2 |
| CTA main loop | for k₀ = 0, BK, 2·BK, … < K: copy A[BM × BK] and B[BK × BN], accumulate | shared memory, an S-stage ring filled by cp.async | each copied element is used BN (or BM) times: tile AI = 2·BM·BN / (b·(BM + BN)) |
| Warp | a WM × WN part of the CTA tile | registers (fragments loaded with ldmatrix) | each fragment feeds WN/8 (or WM/16) MMAs |
| Instruction | mma.sync m16n8k16: [16 × 16]·[16 × 8] FP16 → FP32 | Tensor Cores | (WM/16)·(WN/8)·(BK/16) MMAs per warp per K step |
| Epilogue | D = f(α·acc + β·C), stored once | registers → DRAM | bias, GELU, residual add at no extra DRAM traffic |
The same GEMM in CUTLASS (C++, 2.x device API)
W_O (block 9) with the residual add of block 10 fused into the epilogue: C = D = X and β = 1, so D = 1·(merge(O)·W_O) + 1·X is written straight back into the residual stream.
#include <cutlass/gemm/device/gemm.h>
#include <cutlass/epilogue/thread/linear_combination.h>
using T = cutlass::half_t;
using Row = cutlass::layout::RowMajor;
using Col = cutlass::layout::ColumnMajor;
// Epilogue: D = alpha * acc + beta * C, 8 FP16 values (128 bits) per access, maths in FP32.
// FFN W1 instead: cutlass::epilogue::thread::LinearCombinationGELU<T, 8, float, float>
using Epilogue = cutlass::epilogue::thread::LinearCombination<T, 8, float, float>;
using Gemm = cutlass::gemm::device::Gemm<
T, Row, // A [M, K]: activations, M = B*N
T, Col, // B [K, P]: column-major = nn.Linear weight [P, K], row-major
T, Row, // C, D [M, P]
float, // accumulate in FP32
cutlass::arch::OpClassTensorOp, // use Tensor Cores
cutlass::arch::Sm80, // Ampere kernels; Orin is sm_87 (build with -arch=sm_87)
cutlass::gemm::GemmShape<128, 128, 32>, // CTA tile BM x BN x BK
cutlass::gemm::GemmShape<64, 64, 32>, // warp tile WM x WN x BK: 2 x 2 = 4 warps
cutlass::gemm::GemmShape<16, 8, 16>, // mma.sync m16n8k16
Epilogue,
cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>,
3>; // pipeline stages S (cp.async ring)
int M = B * N, K = d, P = d; // CUTLASS names the sizes {M, N, K}; its N is our P
Gemm::Arguments args({M, P, K},
{o, K}, // A = merge(O) and its leading dimension
{w_o, K}, // B = W_O, stored [P, K] row-major
{x, P}, // C = residual stream X
{x, P}, // D = X, updated in place
{1.0f, 1.0f}); // alpha, beta
Gemm gemm;
cutlass::Status status = gemm(args); // expect cutlass::Status::kSuccess
- Epilogues per block. QKV: β = 0; a bias can come in through C with stride 0 (CUTLASS example 12). W_O and W₂: C = D = X, β = 1, the residual add. W₁: LinearCombinationGELU writes GELU(H) directly (header linear_combination_gelu.h).
- Alignment. 128-bit loads need K and P to be multiples of 8 FP16 values; d = 4,096 is.
- Decode (M = B). Set the template's SplitKSerial to true and pass split_k_slices in Arguments (with a workspace from get_workspace_size), so several CTAs share one K loop and every SM streams weights. Or use a GEMV kernel.
- Choosing tiles. cutlass_profiler times every tile shape and stage count on your GPU; TensorRT's auto-tuner does the same when it builds an engine.
The template order and Arguments follow include/cutlass/gemm/device/gemm.h and examples 00, 12 and 14; build it inside the CUTLASS examples' CMake (it is not compiled in this repo).
Read more: CUTLASS, Efficient GEMM in CUDA (the hierarchy above, pipelining, split-K); CUTLASS GEMM API; NVIDIA blog, CUTLASS: fast linear algebra in CUDA C++; example 00, basic GEMM; cutlass_profiler; CuTe quick start and the CuTe DSL in Python; from scratch: Boehm, How to optimize a CUDA matmul.
- Eq
- Q.view(B, N, h, d_k).transpose(1, 2) (K, V the same with n_kv)
- Shape
- [B, N, h·d_k] → [B, N, h, d_k] → [B, h, N, d_k]
- FLOPs
- 0
- Bytes
- 0: only the strides change; the attention kernel reads the strided view
- Decode
- q [B, h, 1, d_k]; k, v [B, n_kv, 1, d_k], appended to the cache [B, n_kv, t, d_k]
- Toy
- primer step 12
A common misreading: “the split cuts each token's d-vector into h slices, so each head sees only part of the token.” It does not. The reshape cuts Q's output columns, after a projection that reads all d inputs.
- The paper (Vaswani et al. 2017, §3.2.2) gives each head its own WiQ, WiK ∈ ℝd×d_k and WiV ∈ ℝd×d_v, and one W_O ∈ ℝh·d_v×d.
- Code stacks them side by side: W_Q = [W1Q | W2Q | … | WhQ], one [d × d] matrix.
- So the reshape is exact: columns i·d_k … (i+1)·d_k − 1 of X̂·W_Q are X̂·WiQ. Splitting the output columns does no arithmetic and loses nothing.
- Every head sees the whole token. Each column of Q is a dot product with all d numbers of the token: Q[n, c] = Σj=1…d X̂[n, j]·W_Q[j, c].
- Same parameters: h·d·d_k = d². The only difference is one large GEMM instead of h small ones, which keeps the GPU busy.
- Output side: concat(head₁ … head_h)·W_O = Σi head_i · W_O[rows i·d_k … (i+1)·d_k − 1]. W_O mixes all heads back into every output feature.
What to notice: the ✓ figure is the real computation with the primer's numbers (d = 4, h = 2, d_k = 2): column 0 of W_Q (outlined) runs over all four rows, so head 0's first number reads all four inputs. The ✗ figure is the lossy alternative: slicing x̂ before projecting is the same as zeroing the off-diagonal blocks of W_Q, so head 0 never sees 1.03 and −0.09. Transformers compute the ✓ figure.
Tiny example (x̂ of “sat” and W_Q from primer step 6): column 0 is −1.59·(−0.2) + 0.65·0.9 + 1.03·0.4 + (−0.09)·0.1 = 0.318 + 0.585 + 0.412 − 0.009 = 1.31, all four inputs. Head 0 = x̂·W_Q[:, 0:2] = [1.31, 0.51], head 1 = x̂·W_Q[:, 2:4] = [−0.54, −0.72], so Q[sat] = [1.31, 0.51, −0.54, −0.72]: the reshape only reads it as two rows. Slicing x̂ first would give [0.90, 0.35] and [0.07, −0.08]. Output side, with concat[sat] = [1.50, −0.08 | 0.34, −1.57] (step 12): [1.50, −0.08]·W_O[0:2] = [0.34, 0.65, 1.48, −0.24] plus [0.34, −1.57]·W_O[2:4] = [−0.48, −1.64, 0.82, 0.46] ≈ attn_out[sat] = [−0.15, −0.99, 2.29, 0.21] (the last digit differs by rounding). Parameters: 2 heads × [4 × 2] = 16 = 4².
W_heads = [W_Q[:, i*d_k:(i+1)*d_k] for i in range(h)] # the paper's W_i^Q, each [d, d_k] per_head = torch.stack([x_hat @ W_i for W_i in W_heads], dim=1) # h small GEMMs -> [B, h, N, d_k] fused = (x_hat @ W_Q).view(B, N, h, d_k).transpose(1, 2) # one GEMM + a view assert torch.allclose(per_head, fused) # identical: nothing is lost
Run it: python3 transformer/step_by_step.py --json prints xh, W_Q and Q. 🎬 3Blue1Brown ch. 6, “Multiple heads” (from 19:19)
GPU kernel deep dive
- A view is a stride change. Q.view(B, N, h, d_k).transpose(1, 2) only rewrites the strides: element (b, i, n, j) is still read at offset ((b·N + n)·h + i)·d_k + j. A .contiguous() copy would move 2·b·B·N·d bytes (read + write) per tensor. Read more: PyTorch docs: tensor views.
- Keep d_k innermost. Either layout keeps a head's d_k values contiguous (d_k·b bytes), which is what a kernel loads per (token, head); that is why [B, N, h, d_k] and [B, h, N, d_k] can be used interchangeably by strided kernels. Read more: Triton tutorial: matrix multiplication.
- Fused kernels skip both transposes. The flash-attention package takes q, k, v as (batch, seqlen, nheads, headdim) and writes O in the same order, so neither the split nor the merge copies data; K and V may have fewer heads (GQA). Read more: flash-attention README.
- The KV cache layout. Decode appends one [n_kv, d_k] row per layer; storing the cache as [B, n_kv, t_max, d_k] keeps each head's keys in one block that a decode kernel streams front to back. Paged caches store fixed-size blocks and a block table instead. Read more: PagedAttention paper (vLLM); cookbook card a, KV cache.
- Eq
- S[b, i, n, m] = Σj Q[b, i, n, j] · K[b, g(i), m, j]; g(i) = i for MHA, ⌊i·n_kv / h⌋ for GQA
- Shape
- [B, h, N, d_k]·[B, n_kv, d_k, N] → [B, h, N, N]
- FLOPs
- 2·B·h·N²·d_k = 2·B·N²·d 137.44 GFLOP, 3.23 ms
- Bytes
- b·(|Q| + |K| + B·h·N²) 1.06 GiB · AI 120 < 208 → 5.57 ms
- Kernel
- batched GEMM over (B, h): the inner d_k is summed away, the outer N × N stays. Written to DRAM, S is the largest activation of the layer (§5) and drags the GEMM below the ridge; FlashAttention keeps it on chip.
- Decode
- [B, h, 1, d_k]·[B, n_kv, d_k, t] → [B, h, 1, t]: 33.55 MFLOP over 32 MiB of cached K
- Toy
- primer step 7. GPT-2 small: [1, 12, 1024, 64]·[1, 12, 64, 1024] → [1, 12, 1024, 1024].
s = q @ k.transpose(-2, -1) # [B, h, N, d_k] @ [B, h, d_k, N] -> [B, h, N, N]
GPU kernel deep dive
- Why unfused attention writes N × N. A batched GEMM must finish writing S before the softmax kernel can read it, so b·B·h·N² bytes go to DRAM (§5); with an inner size of d_k the GEMM's AI stays under d_k = 128 < 208. Read more: FlashAttention paper.
- The causal mask as block skipping. With T = N / 128 tile rows, only T(T + 1)/2 of the T² score tiles have any j ≤ i; a causal kernel skips the other ≈ half outright and applies the mask only on the T diagonal tiles. Read more: FlashAttention-2 paper.
- Decode attention fills the GPU differently. q has one row, so the kernel is a GEMV over the cache: 2·t·d FLOPs over t·n_kv·d_k·b bytes per layer, AI ≈ h/n_kv. FlashAttention parallelizes over B·h (× query blocks): B·h thread blocks, enough for Orin's 16 SMs at h = 32 but few for a 108-SM A100, and only B·n_kv for a GQA kernel that keeps one K/V head per block. Flash-Decoding also splits the t keys across blocks and merges the parts with their log-sum-exp. Read more: Flash-Decoding (Dao et al.).
- GQA reads each K/V head once. A kernel that loads one K/V head and uses it for its h / n_kv query heads reads n_kv / h of the MHA cache bytes: ¼ for 32 → 8 K/V heads. Read more: cookbook card b, GQA.
- Paged and quantized caches. A paged kernel follows a block table to non-contiguous blocks; an INT8 cache halves the bytes and is dequantized in registers. Read more: PagedAttention paper (vLLM); cookbook card a, KV cache.
- Eq
- S′ = S / √d_k + M_c, (M_c)ij = 0 if j ≤ i, −∞ if j > i
- Shape
- [B, h, N, N] → [B, h, N, N]; M_c [N, N] broadcasts over B and h
- FLOPs
- B·h·N² 0.54 GFLOP
- Bytes
- 2·b·B·h·N² as a separate pass 2.00 GiB, 10.49 ms; 0 when fused into the GEMM or FlashAttention
- Kernel
- never a separate pass in practice. Causal kernels also skip whole tiles with j > i, about half of the score and A·V FLOPs.
- Decode
- no mask: the new token is the last row, and that row of M_c is all zeros (§3.2)
- Toy
- primer steps 8–9
Derivation: for q, k with independent zero-mean, unit-variance entries, Var(q·k) = Σj Var(qjkj) = d_k, so the score's std is √d_k (8 at d_k = 64, 11.3 at 128). Softmax of numbers that large is nearly one-hot and its gradient vanishes. Dividing by √d_k brings the std back to 1 for any head size; it acts like a temperature.
Tiny example: d_k = 64, raw scores [8, 0]: softmax = [0.9997, 0.0003]. Scaled to [1, 0]: [0.73, 0.27], and both keys still get gradient.
Try it: softmax saturation as d_k grows
Why the mask: in training, row i predicts token i + 1 from tokens 0…i, so it must not see later tokens. At inference it guarantees that appending a token never changes earlier rows' K, V or outputs: the basis of the KV cache (§3). exp(−∞) = 0, so masked keys get exactly zero weight and each row still sums to 1.
out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # fused; no N x N mask tensor
mask = torch.tril(torch.ones(N, N, dtype=torch.bool)) # manual path: True = may attend
s = s.masked_fill(~mask, float('-inf')) # nn.MultiheadAttention: True = BLOCKED
🎬 3Blue1Brown ch. 6, “Masking” (from 11:08)
GPU kernel deep dive
- Inline scale and mask. The 1/√d_k multiply is applied to the accumulator (or folded into W_Q offline) and the mask is index arithmetic (j > i), so no [N, N] mask tensor and no 2 GiB elementwise pass exist. Read more: Triton tutorial: fused softmax.
- Decode and chunks. One new row needs no mask. A chunk of c new rows against t cached keys (chunked prefill, speculative verification) uses the bottom-right corner of the causal mask: key j is allowed for new row i if j ≤ t + i. Read more: lab 03, chunked prefill against the cache.
- Eq
- Aij = exp(S′ij − mi) / Σk exp(S′ik − mi), mi = maxk S′ik
- Shape
- [B, h, N, N] → [B, h, N, N]; Aij = 0 for j > i
- FLOPs
- ≈ 5·B·h·N² (the estimate in compute_flops()) 2.68 GFLOP
- Bytes
- 2·b·B·h·N² for a one-pass kernel 2.00 GiB, 10.49 ms; a 3-pass softmax reads S three times
- Kernel
- a row reduction. Subtracting mi cancels in the ratio, so the result is unchanged but exp never overflows (FP16 overflows above 65,504, which is exp(11.1)).
- Decode
- [B, h, 1, t]: 256 KiB at t = 4,096, tiny
- Toy
- primer step 10
Online softmax: one pass, then no N × N at all
Safe softmax needs the row maximum before it can exponentiate. Online softmax (Milakov & Gimelshein 2018) keeps a running max m and sum l, and rescales l when a larger max arrives. FlashAttention adds a running, unnormalised output acc, rescaled the same way, so a tile's scores are used and discarded in on-chip SRAM.
m, l, acc = -inf, 0.0, 0.0 # running max, running sum, unnormalised output (one query row)
for S_blk, V_blk in tiles: # S_blk = q · K_blk^T / sqrt(d_k) for one tile of keys
m_new = max(m, S_blk.max())
alpha = exp(m - m_new) # shrink what was accumulated under the old max
p = exp(S_blk - m_new)
l, acc, m = l * alpha + p.sum(), acc * alpha + p @ V_blk, m_new
out = acc / l # == softmax(S) @ V, without storing S
GPU kernel deep dive
- Fused row softmax. One program keeps a row in registers or shared memory, takes its max and sum, and writes the result: S is read once and A written once, instead of three passes. Read more: Triton tutorial: fused softmax.
- Online softmax. A running max and running sum merge the max and sum passes, and let a kernel consume a row tile by tile without seeing all of it first. Read more: Milakov & Gimelshein, online softmax.
- Recompute in backward. FlashAttention saves only the per-row log-sum-exp and recomputes S and A from Q and K during backward: more FLOPs, no N × N tensor, which is why training activations lose the 5·h·N² term (§7). Read more: FlashAttention paper.
- Eq
- O[b, i, n, :] = Σm A[b, i, n, m] · V[b, g(i), m, :]
- Shape
- [B, h, N, N]·[B, n_kv, N, d_k] → [B, h, N, d_k]
- FLOPs
- 2·B·h·N²·d_k = 2·B·N²·d 137.44 GFLOP, 3.23 ms
- Bytes
- b·(B·h·N² + |V| + |O|) 1.06 GiB · AI 120 → 5.57 ms
- Kernel
- batched GEMM. Each output row is a convex combination of value rows: attention only blends; W_O and the FFN create new features.
- Decode
- [B, h, 1, t]·[B, n_kv, t, d_k] → [B, h, 1, d_k]: 33.55 MFLOP over 32 MiB of cached V
- Toy
- primer step 11
Query of “sat” q = [1, 0, 1, 0]; keys kThe = [0, 1, −0.5, 0], kcat = [0.9, 0.1, 0.8, 0.2], ksat = [0.1, 0, 0.2, 1]; values vThe = [0.1, 0.9, −0.2, 0.4], vcat = [0.6, −0.1, 0.8, 0.3], vsat = [0.3, 0.5, 0.1, −0.2] (illustrative numbers).
q·k = [−0.50, 1.70, 0.30] → ÷ √4 = [−0.25, 0.85, 0.15] → exp = [0.78, 2.34, 1.16], sum 4.28 → weights [0.18, 0.55, 0.27] → o = 0.18·vThe + 0.55·vcat + 0.27·vsat = [0.43, 0.24, 0.43, 0.18]. labs/check.py checks this example.
Try it: one attention head in 2-D
o = s.softmax(dim=-1) @ v # [B, h, N, N] @ [B, h, N, d_k] -> [B, h, N, d_k]
🎬 3Blue1Brown ch. 6, “Values” (from 13:10)
GPU kernel deep dive
- P never leaves the chip. Inside FlashAttention the exponentiated tile P is kept in registers and fed straight into the second MMA with the V tile, so A is never materialized. Read more: FlashAttention-2 paper.
- Decode reads V once per step. o = softmax(s)·V_c is a second GEMV over the cache, another t·n_kv·d_k·b bytes per layer: each decode step reads the whole cache, K and V, exactly once. Read more: Flash-Decoding (Dao et al.).
- Eq
- O = softmax(Q·Kᵀ/√d_k + M_c)·V, tile by tile with the online softmax (block 7)
- FLOPs
- the same 4·B·N²·d (+ 6·B·h·N² elementwise) 278.10 GFLOP, 6.54 ms
- Bytes
- ideally b·(|Q| + |K| + |V| + |O|) 128 MiB · AI 2,072; K, V tiles are re-read per query block, Θ(N²d²/M_sram) in total
- Memory
- no N × N buffer; the extra state is m and l per row, h·N·4 B 0.5 MiB each
- Kernel
- Q, K, V tiles live in on-chip SRAM (shared memory, ~100–228 KB per SM). Same result up to rounding: exact attention, not an approximation.
- Decode
- one query row and no N × N matrix: little to gain. Decode is bound by reading the weights and the cache.
What to notice: both sides do the same FLOPs. Unfused attention parks S and A in DRAM and moves them back and forth (red); FlashAttention streams tiles through SRAM and writes only O.
Unfused vs fused: unfused, blocks 5–8 move ≈ 6·b·B·h·N² bytes (four kernels write or read S and A), so time ≈ that ÷ BW, quadratic in N. Fused, only Q, K, V and O cross DRAM and time ≈ 4·B·N²·d ÷ peak. Reference (N = 4,096, §2.6): 32.1 → 6.5 ms per layer, TTFT 2.38 → 1.56 s. The N² term is a prefill problem.
Versions: FlashAttention-2 (2023) is a backend of PyTorch's scaled_dot_product_attention; FlashAttention-3 (2024) targets Hopper with FP8; FlashAttention-4 (2026) targets Blackwell. The tiling and online-softmax idea is the same in all of them.
from torch.nn.attention import sdpa_kernel, SDPBackend # PyTorch >= 2.3
out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # picks cuDNN / Flash / mem-efficient / math
with sdpa_kernel(SDPBackend.FLASH_ATTENTION): # Flash only; raises if inputs do not qualify
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
🎬 FlashAttention (Tri Dao, Stanford MLSys, 59 min); code-along: Flash Attention derived and coded from first principles with Triton (Umar Jamil). Depth: cookbook card d.
GPU kernel deep dive
- The tiling loop. A thread block holds one Q tile in SRAM and loops over K, V tiles: compute the S tile, update the running max and sum, rescale and accumulate O. DRAM traffic is Θ(N²d²/M_sram) instead of Θ(N·d + N²). Read more: FlashAttention paper.
- Better work partitioning (v2). Parallelize over query blocks as well as batch and heads, keep the non-matmul FLOPs (rescaling) to a minimum, and split work across warps so they share less through shared memory. Read more: FlashAttention-2 paper.
- Asynchrony and FP8 (v3). On Hopper, TMA loads and warp specialization overlap data movement, MMAs and softmax. Not available on Orin (Ampere), but the same tiling applies. Read more: FlashAttention-3 paper.
- Decode is a different kernel. With one query row, split the keys instead of the queries (Flash-Decoding, block 5). Read more: Flash-Decoding (Dao et al.).
- Eq
- Y = concat(O₁, …, O_h)·W_O = Σi O_i · W_O[i·d_k : (i+1)·d_k, :]
- Shape
- [B, h, N, d_k] → transpose, reshape → [B, N, h·d_k]·[h·d_k, d] → [B, N, d]
- FLOPs
- 2·B·N·d² 137.44 GFLOP, 3.23 ms
- Bytes
- merge: a copy if .contiguous(), 2·b·B·N·d 64 MiB; GEMM: b·(2·B·N·d + d²) 96 MiB · AI 1,365
- Kernel
- one GEMM. Fused attention kernels write O already in [B, N, h, d_k] order, so the merge is free.
- Decode
- [B, 1, d]·[d, d]: 33.55 MFLOP over 32 MiB of weights, AI ≈ 1
- Toy
- primer step 12; the sum over heads is worked in block 4
Blocks 3–9 together, as in transformer.py:
def forward(self, x, mask=None): # x: [B, N, d], mask: bool, True = may attend B, N, _ = x.shape Q = self.W_q(x).view(B, N, self.n_heads, self.d_k).transpose(1, 2) # blocks 3-4: [B, h, N, d_k] K = self.W_k(x).view(B, N, self.n_heads, self.d_k).transpose(1, 2) V = self.W_v(x).view(B, N, self.n_heads, self.d_k).transpose(1, 2) scores = (Q @ K.transpose(-2, -1)) * self.scale # blocks 5-6: [B, h, N, N] if mask is not None: scores = scores.masked_fill(~mask, float('-inf')) attn = self.dropout(torch.softmax(scores, dim=-1)) # block 7 context = (attn @ V).transpose(1, 2).contiguous().view(B, N, self.d_model) # blocks 8-9 return self.W_o(context) # [B, N, d]
GPU kernel deep dive
- Residual in the epilogue. W_O's epilogue computes D = acc + β·C with C = X, β = 1, and writes X + Y directly: Y never makes a DRAM round trip, 2·b·B·N·d bytes less per layer. Read more: CUTLASS deep dive (block 3), which writes exactly this GEMM.
- Merge without a copy. Fused attention writes O already as [B, N, h, d_k] = [B, N, d], which W_O reads as is; the .contiguous() in transformer.py costs another 2·b·B·N·d bytes per layer. Read more: flash-attention README.
- Decode. A [B, d]·[d, d] GEMV, d²·b bytes of weights per layer: the same split-K and INT4 tricks as block 3. Read more: cookbook card c, quantization.
2.3 Residual, FFN and the output
- Eq
- X ← X + Y (pre-norm: X + F(LN(X)); the paper's post-norm: LN(X + F(X)))
- Shape
- [B, N, d] + [B, N, d] → [B, N, d]
- FLOPs
- B·N·d 16.78 M
- Bytes
- 3·b·B·N·d 96 MiB, 0.49 ms
- Kernel
- elementwise. Fuse it into the previous GEMM's epilogue or with the next norm (fused add + norm, §6). Nothing is overwritten, so the embedding reaches the last layer and gradients have a direct path back.
- Decode
- [B, 1, d], tiny
- Toy
- primer step 13; both norm orders side by side: primer, paper order
x = x + attn(ln1(x)); x = x + ffn(ln2(x)) # pre-norm (GPT-2, Llama, this guide) x = ln1(x + attn(x)); x = ln2(x + ffn(x)) # post-norm (2017 paper, BERT)
🎬 Karpathy, “residual connections” (from 1:26:48)
GPU kernel deep dive
- Pure bandwidth. 1 FLOP per element against 3·b bytes (two reads, one write): AI = 1 / (3b) ≈ 0.17. The add costs exactly its bytes, 3·b·B·N·d ÷ BW. Read more: NVIDIA, GPU performance background.
- Never on its own. Put it in the epilogue of the GEMM before it (block 9, W₂) or merge it with the next norm (block 2). In decode the saving is mostly the launch. Read more: cookbook card h, fusion and CUDA graphs.
- Eq
- F = GELU(X̂₂·W₁ + b₁)·W₂ + b₂; SwiGLU: (silu(X̂₂·W_g) ⊙ X̂₂·W_u)·W_d
- Shape
- [B, N, d]·[d, d_ff] → [B, N, d_ff] → ·[d_ff, d] → [B, N, d]
- FLOPs
- 2 × 2·B·N·d·d_ff = 16·B·N·d² 1.10 TFLOP, 25.9 ms (57.1% of the layer)
- Bytes
- W₁: b·(B·N·d + d·d_ff + B·N·d_ff) 288 MiB; GELU 256 MiB; W₂ 288 MiB
- Kernel
- two GEMMs (AI 1,820). GELU belongs in W₁'s epilogue: that saves the 256 MiB round trip of the [B, N, d_ff] hidden tensor.
- Params
- 2·d·d_ff = 8d² of the block's 12d²
- Decode
- [B, 1, d] → [B, 1, d_ff] → [B, 1, d]: 268.44 MFLOP over 256 MiB of weights, AI ≈ 1
- Toy
- primer step 15 (ReLU, d_ff = 2d)
Why it exists: attention only blends value rows. The FFN is where each token, alone, builds new features; its hidden units act like key–value memories (Geva et al., 2021).
y = F.gelu(x_hat @ W1 + b1) @ W2 + b2 # GPT-2 / transformer.py y = (F.silu(x_hat @ W_gate) * (x_hat @ W_up)) @ W_down # Llama SwiGLU, d_ff ~ 8d/3
🎬 3Blue1Brown ch. 7, “Inside a multilayer perceptron” (from 6:07)
GPU kernel deep dive
- GELU in the W₁ epilogue. Apply the activation to the accumulator before the store: the [B, N, d_ff] hidden tensor is written once instead of written, read and written again, 2·b·B·N·d_ff bytes less per layer. In CUTLASS this is the LinearCombinationGELU epilogue. Read more: CUTLASS deep dive (block 3); Triton tutorial: matrix multiplication.
- SwiGLU as one GEMM. Concatenate W_gate and W_up into one [d, 2·d_ff] weight; the epilogue computes silu(g) ⊙ u and writes one [B, N, d_ff] tensor. Read more: cookbook card h, fusion and CUDA graphs.
- Decode: the FFN is most of the bytes. W₁ and W₂ are 8d² of each block's 12d² weights, so weight-only INT4 here buys most of the decode speed-up. Read more: cookbook card c, quantization.
- Prefill: Tensor Core bound. AI = 1 / (1/(B·N) + 1/d + 1/(4d)) sits far above the ridge; only faster maths helps, e.g. INT8 Tensor Cores at twice the FP16 rate (W8A8). Read more: NVIDIA, Matrix multiplication background.
- Eq
- z = LN_f(X[:, N−1]) · Eᵀ (weight tying); p = softmax(z / T); next = argmax p, or a top-k / top-p sample
- Shape
- [B, d]·[d, V] → [B, V] → [B] (all rows would be [B, N, V])
- FLOPs
- 2·B·d·V 0.41 GFLOP; on all N rows: 2·B·N·d·V 1.69 TFLOP
- Bytes
- all of E: b·V·d 393 MiB, 2.01 ms, a GEMV: memory-bound even inside prefill
- Kernel
- engines run the head on the last position only; transformer.py scores every row, which training needs (§7). The sampled token ends the prefill: its latency is the TTFT, and it is decode's first input.
- Decode
- the same [B, d]·[d, V], every step: 0.41 GFLOP over 393 MiB
- Toy
- primer step 17 (greedy vs sampling)
logits = self.output(self.norm(x[:, -1])) # [B, V]; self.output.weight is token_emb.weight (tied) next_id = torch.multinomial((logits / T).softmax(-1), 1) if T > 0 else logits.argmax(-1, keepdim=True)
🎬 3Blue1Brown ch. 5, “Unembedding” and “Softmax with temperature” (from 20:22)
GPU kernel deep dive
- Last row only. Slicing x[:, −1] before the head turns 2·B·N·d·V FLOPs into 2·B·d·V, N times fewer. The bytes stay: all of E, V·d·b, every step. Read more: cookbook §2, roofline.
- Sampling without a full sort. Top-k and top-p need only the head of the distribution; GPU samplers use partial selection or rejection sampling instead of sorting all 50,257 logits every step. Read more: FlashInfer, sorting-free sampling kernels.
- The whole decode step is many small launches. Counting one kernel per op, a step is ≈ 14·L + 3 launches unfused and ≈ 7·L + 3 fused (451 and 227 at L = 32). At batch 1 the CPU can fall behind the GPU; CUDA Graphs record the step once and replay it with a single launch. Read more: NVIDIA, Getting started with CUDA Graphs; PyTorch, Accelerating PyTorch with CUDA Graphs.
2.4 What prefill writes into the KV cache
Block 3 produces K and V for all N prompt rows of every layer. They are kept, per layer, as
Reference: [1, 32, 4096, 128] each, 64 MiB per layer, 2 GiB (2.15 GB) for all 32 layers. Q is not kept: its rows have produced their outputs (§3.2). With RoPE, K is cached after the rotation.
2.5 FLOPs per layer, derived
Read it aloud: the weight GEMMs cost 2 FLOPs per weight per row, 2·12d²·N, linear in N; the two attention GEMMs cost 4·N²·d, quadratic. The model: L·(24Nd² + 4N²d) + 2·d·V for the last-row LM head. Elementwise ops (norms, softmax, adds) are under 1%.
Shares: the N² part is 4N²d / (24Nd² + 4N²d) = N / (6d + N) of a layer, the FFN 16d / (24d + 4N). The N² part overtakes the rest at N = 6d. Reference (N = d = 4,096): attention's N² part 14%, FFN 57%, 61.57 TFLOP for the whole prompt.
2.6 TTFT: why prefill is compute-bound
Why compute-bound: for a d × d weight, AI = 1 / (1/M + 2/d) = M / (1 + 2M/d) (§2.2): ≈ M while M ≪ d, approaching d/2 as M grows. It passes the ridge R when M > R / (1 − 2R/d), ≈ 231 rows at d = 4,096. In prefill M = B·N, so any prompt longer than a few hundred tokens is compute-bound (AI = 1,365 at N = 4,096).
Reference, N = 4,096: TTFT ≥ 61.57 TFLOP ÷ 42.5 TFLOPS = 1.45 s. Real kernels reach a fraction of peak, so measured TTFT is higher; the per-op estimate below gives 1.56 s with FlashAttention and 2.38 s without.
| N | Prefill FLOPs | Attention share | FLOPs ÷ peak | Weights ÷ BW | GEMM AI | Bound |
|---|---|---|---|---|---|---|
| 128 | 1.66 T | 0.5% | 39 ms | 65 ms | 120 | memory |
| 512 | 6.73 T | 2.0% | 158 ms | 65 ms | 410 | compute |
| 1,024 | 13.74 T | 4.0% | 323 ms | 65 ms | 683 | compute |
| 2,048 | 28.59 T | 7.7% | 673 ms | 65 ms | 1,024 | compute |
| 4,096 | 61.57 T | 14.3% | 1,449 ms | 65 ms | 1,365 | compute |
| 8,192 | 140.74 T | 25.0% | 3,311 ms | 65 ms | 1,638 | compute |
Reference config, B = 1, AGX Orin. Attention share = 4N²d ÷ (24Nd² + 4N²d) = N / (6d + N). Doubling N roughly doubles TTFT until the N² term takes over.
Per-op roofline of one layer (N = 4,096)
| Op | FLOPs | Bytes (unfused) | AI | FLOPs ÷ peak | Bytes ÷ BW | Bound |
|---|---|---|---|---|---|---|
| LN₁, LN₂ (each) | 117 M | 64 MiB | 1.75 | 0.00 ms | 0.33 ms | memory |
| QKV | 412.32 G | 224 MiB | 1,755 | 9.70 ms | 1.15 ms | compute |
| Q·Kᵀ | 137.44 G | 1.06 GiB | 120 | 3.23 ms | 5.57 ms | memory |
| scale + mask | 0.54 G | 2.00 GiB | 0.25 | 0.01 ms | 10.49 ms | memory |
| softmax | 2.68 G | 2.00 GiB | 1.25 | 0.06 ms | 10.49 ms | memory |
| A·V | 137.44 G | 1.06 GiB | 120 | 3.23 ms | 5.57 ms | memory |
| FlashAttention (replaces the 4 rows above) | 278.10 G | 128 MiB | 2,072 | 6.54 ms | 0.66 ms | compute |
| merge copy | 0 | 64 MiB | – | 0 | 0.33 ms | memory |
| W_O | 137.44 G | 96 MiB | 1,365 | 3.23 ms | 0.49 ms | compute |
| residual add (each) | 16.78 M | 96 MiB | 0.17 | 0.00 ms | 0.49 ms | memory |
| FFN W₁, W₂ (each) | 549.76 G | 288 MiB | 1,820 | 12.94 ms | 1.47 ms | compute |
| GELU | – | 256 MiB | – | – | 1.31 ms | memory |
| Layer, unfused attention | 1.92 T + 3.49 G | 74.2 ms | ||||
| Layer, FlashAttention | 1.92 T + 3.49 G | 48.6 ms |
Each op takes max(FLOPs ÷ 42.5 TFLOPS, bytes ÷ 204.8 GB/s); the layer is the sum. × 32 layers plus the embedding and last-row LM head: TTFT ≈ 2.38 s unfused, 1.56 s with FlashAttention, against the pure-FLOPs bound of 1.45 s. The remaining gap is the memory-bound elementwise ops, which fusion (§6) removes.
3 Decode: one token per step against the cache
Each step feeds the newest token of every sequence, x [B, 1, d], through all L layers. Its q, k, v are computed, k and v are appended to the cache, and q attends over all t cached rows. Every weight is read once to produce B rows: decode is memory-bound.
3.1 One decode step, with shapes
| # | Equation | Shape |
|---|---|---|
| 1 | x = E[id] + P[t − 1] | [B, 1] → [B, 1, d] |
| 3 | [q | k | v] = LN₁(x) · W_QKV | [B, 1, d]·[d, (h + 2·n_kv)·d_k] |
| 4 | q → [B, h, 1, d_k]; k, v → [B, n_kv, 1, d_k] | view |
| 4′ | K_c ← cat(K_c, k); V_c ← cat(V_c, v) | [B, n_kv, t − 1, d_k] → [B, n_kv, t, d_k] |
| 5–6 | s = q · K_cᵀ / √d_k (no mask) | [B, h, 1, d_k]·[B, n_kv, d_k, t] → [B, h, 1, t] |
| 7–8 | o = softmax(s) · V_c | [B, h, 1, t]·[B, n_kv, t, d_k] → [B, h, 1, d_k] |
| 9–11 | x ← x + merge(o)·W_O; x ← x + FFN(LN₂(x)) | [B, 1, d] |
| 12 | z = LN_f(x)·Eᵀ; next ~ softmax(z / T) | [B, V] → [B] |
The numbers are §2's blocks; each block's drop-down has a “Decode” line with these shapes and its cost at t = 4,096. Every GEMM now has M = B rows. Toy version with real numbers: primer step 18.
3.2 No mask, no Q cache
- No mask is needed. The new token sits at position t − 1, the last row of the causal mask, and row t − 1 of M_c is all zeros: (M_c)t−1, j = 0 for every j ≤ t − 1. The cache holds only the past and the token itself, so there is nothing to block.
- K and V are cached because they never change. With the causal mask, row j's K and V in every layer depend only on tokens 0…j, and every later query reads them.
- Q is not cached. qj only produces row j's output, which was used once. See primer step 18, “What about Q?”.
3.3 FLOPs, bytes, intensity, TPOT
FLOPs: each matmul weight is used once per token, 2 FLOPs (multiply, add); attention adds q·K_cᵀ and softmax·V_c, 2·t·d_k per head each, so 4·t·d per layer. (Here “params” are the matmul weights, 12·L·d² + V·d; the position table is a lookup.)
Bytes: all weights once per step, shared by the B sequences, plus each sequence's own cache.
Intensity: a weight GEMM with M = B rows has AI = 2B / (b + 4B/d) ≈ B. Attention over the cache has AI = 4·t·h·d_k / (2·t·n_kv·d_k·b) = h / n_kv for FP16: 1 for MHA, whatever B is, because every sequence reads its own cache.
Time: TPOT ≈ bytes ÷ bandwidth, since AI ≪ ridge.
| Op (B = 1, t = 4,096; per layer unless noted) | FLOPs | Weight bytes | KV bytes |
|---|---|---|---|
| QKV | 100.66 M | 96 MiB | – |
| q·K_cᵀ | 33.55 M | – | 32 MiB |
| softmax·V_c | 33.55 M | – | 32 MiB |
| W_O | 33.55 M | 32 MiB | – |
| FFN W₁, W₂ (each) | 134.22 M | 128 MiB | – |
| LM head E (once) | 411.71 M | 393 MiB | – |
| position table P (once; counted whole, as in the primer) | 0 | 16 MiB | – |
| Step: 32 layers + once | 13.30 + 2.15 = 15.44 G | 13.31 GB | 2.15 GB |
Reference (B = 1, t = 4,096): AI ≈ 1 ≪ 208, so the bytes take ≈ 208× longer than the FLOPs and TPOT ≥ (weights + cache) ÷ BW = 15.46 GB ÷ 204.8 GB/s = 75.5 ms, ≈ 13 tok/s, as in primer step 19 (15.4 tok/s without the cache read). What moves it:
| Variant (B = 1, t = 4,096) | Weights | KV cache | Bytes/step | TPOT ≥ | tok/s ≤ |
|---|---|---|---|---|---|
| FP16 weights, MHA (reference) | 13.31 GB | 2.15 GB | 15.46 GB | 75.5 ms | 13.2 |
| INT8 weights | 6.66 GB | 2.15 GB | 8.80 GB | 43.0 ms | 23.3 |
| INT4 weights | 3.33 GB | 2.15 GB | 5.48 GB | 26.7 ms | 37.4 |
| INT4 + GQA (n_kv = 8) | 2.93 GB | 0.54 GB | 3.46 GB | 16.9 ms | 59.1 |
| INT4 + GQA-8 + INT8 KV cache | 2.93 GB | 0.27 GB | 3.19 GB | 15.6 ms | 64.1 |
Weight-only quantization; quantization scales are ignored. GQA also shrinks W_K and W_V to [d, n_kv·d_k] (805 M fewer parameters). Real runtimes reach a fraction of these bounds.
End-to-end latency = TTFT + (N_out − 1)·TPOT. Reference, 4,096-token prompt and 100 output tokens: 1.45 s + 99 × 75.6 ms ≈ 8.94 s, 84% of it decode.
3.4 Batching
B sequences in one step share one read of the weights. FLOPs grow B-fold, weight bytes stay, cache bytes grow B-fold.
| Attention | B | Bytes/step | AI | TPOT ≥ | tok/s, all B | Weights + cache |
|---|---|---|---|---|---|---|
| MHA | 1 | 15.46 GB | 1.0 | 75.5 ms | 13 | 15.5 GB |
| MHA | 8 | 30.49 GB | 4.1 | 148.9 ms | 54 | 30.5 GB |
| MHA | 16 | 47.67 GB | 5.2 | 232.8 ms | 69 | 47.7 GB |
| MHA | 32 | 82.03 GB | 6.0 | 400.6 ms | 80 | 82.0 GB: does not fit |
| GQA-8 | 1 | 12.24 GB | 1.1 | 59.8 ms | 17 | 12.2 GB |
| GQA-8 | 8 | 16.00 GB | 6.9 | 78.1 ms | 102 | 16.0 GB |
| GQA-8 | 32 | 28.88 GB | 15.3 | 141.0 ms | 227 | 28.9 GB |
FP16, every sequence at t = 4,096, AGX Orin (64 GB nominal, shared with the OS). Max batch that fits: 23 (MHA), 97 (GQA-8).
What to notice: batching shares the weight bytes, not the cache bytes, so it raises throughput and also TPOT. As B grows, AI → (FLOPs per token) ÷ (cache bytes per sequence) = (2·params + 4·L·t·d) / (2·L·n_kv·d_k·b·t): 7.2 for MHA, 25.8 for GQA-8, both far below 208. The weight GEMMs alone would reach the ridge at B ≈ 231. Continuous batching (a new request joins the batch as soon as another finishes) keeps B high in a server; on a single-user Jetson, B is usually 1.
3.5 GQA and MQA: fewer K/V heads
n_kv < h K/V heads, each shared by a group of h / n_kv query heads (head i reads K/V head ⌊i·n_kv / h⌋). W_K, W_V shrink to [d, n_kv·d_k]; the cache to [B, n_kv, t, d_k] per layer.
| Variant | n_kv | KV per token | KV at t = 4,096 | Attention AI |
|---|---|---|---|---|
| MHA (reference) | 32 | 512 KiB | 2,048 MiB | 1 |
| GQA (Llama 3 8B style) | 8 | 128 KiB | 512 MiB | 4 |
| MQA | 1 | 16 KiB | 64 MiB | 32 |
k = k.repeat_interleave(h // n_kv, dim=1) # [B, n_kv, t, d_k] -> [B, h, t, d_k]; kernels index instead of copying
🎬 LLaMA explained: KV-Cache, RoPE, RMS Norm, GQA, SwiGLU (Umar Jamil, 71 min). Depth: cookbook card b (GQA, MQA, MLA).
3.6 Cache growth and paged KV
- Growth: every decode step appends 2·L·n_kv·d_k·b bytes per sequence: 512 KiB for the reference config. The cache, not the weights, often sets the maximum context and batch on a Jetson (§5).
- Paged KV (vLLM's PagedAttention): store the cache in fixed-size blocks of a few tokens plus a block table per sequence, instead of one contiguous [t_max] buffer per sequence. Memory is allocated as tokens arrive, nothing is reserved for unused length, and sequences with a common prefix can share blocks. Cookbook card e.
- Speculative decoding in one line: a small draft model proposes k tokens and the large model checks all k in one pass (M = k rows per weight read), keeping the large model's output distribution. Cookbook card g.
3.7 Worked example: “What color is apple?”
What to notice: each row is one forward pass, and each square one cache row per layer. read from the cache, computed in this pass. Prefill writes 5 rows at once; every decode step adds one row and reads all of them.
- 1Prefill: “What color is apple?” is 5 GPT-2 tokens, [2061, 3124, 318, 17180, 30]. ids [1, 5] → logits of the last row only → “Apple”. The cache now holds K, V of shape [1, n_kv, 5, d_k] in every layer.
- 2Decode: feed only “Apple”, x [1, 1, d]; append its k, v (t = 6); its q [1, h, 1, d_k] attends over all 6 rows.
- 3Step 15 reads 20 rows (red) and emits EOS: “Apple is in general red color but sometimes green if they are not ripe.”
| Step | Input | t | Scores q·K_cᵀ | Output |
|---|---|---|---|---|
| prefill | 5 prompt tokens | 5 | [1, h, 5, 5], masked | “Apple” |
| 1 | “Apple” | 6 | [1, h, 1, 6] | “is” |
| 2 | “is” | 7 | [1, h, 1, 7] | “in” |
| 3 | “in” | 8 | [1, h, 1, 8] | “general” |
| … | “…red color but sometimes green…” | |||
| 14 | “ripe” | 19 | [1, h, 1, 19] | “.” |
| 15 | “.” | 20 | [1, h, 1, 20] | EOS |
Savings over the whole answer (per layer, per head): without a cache every pass re-runs all tokens, 200 token-rows through the weight GEMMs and 1,520 causal score pairs; with it, 20 rows and 210 pairs. At step 15 alone: 210 pairs → 20. The FLOPs drop about 10×; the time drops less, because each decode step still reads every weight.
4 Prefill vs decode, side by side
| Prefill (§2) | Decode (§3) | |
|---|---|---|
| Input | ids [B, N] | 1 id per sequence, [B, 1] |
| GEMM rows M | B·N | B |
| Attention | Q [B,h,N,d_k] vs K [B,n_kv,N,d_k], causal mask | q [B,h,1,d_k] vs cache [B,n_kv,t,d_k], no mask |
| KV cache | writes N rows per layer | reads t rows, appends 1 |
| FLOPs | L·(24·N·d² + 4·N²·d) + 2·d·V | 2·params + 4·L·t·d per token |
| Bytes | weights once + activations (+ the N × N scores if unfused) | weights + whole cache, every step |
| AI of weight GEMMs | M / (1 + 2M/d), M = B·N | ≈ B |
| Bound | compute (B·N ≳ 231) | memory bandwidth |
| Metric | TTFT ≈ FLOPs ÷ FLOP/s | TPOT ≈ bytes ÷ bandwidth |
| Reference, B = 1, N = t = 4,096 | 61.57 TFLOP, AI 1,365 → TTFT ≥ 1.45 s | 15.44 GFLOP, 15.46 GB, AI 1.0 → TPOT ≥ 75.5 ms |
| Helps | FlashAttention, fused GEMM epilogues, INT8 compute, chunked prefill, prefix caching | weight-only INT4/INT8, GQA/MQA, KV quantization, batching, paged KV, speculative decoding, CUDA graphs |
| Does not help | weight-only quantization (still compute-bound) | more TFLOPS, FlashAttention's N² savings (no N × N in decode) |
Roofline on AGX Orin
A device that does P FLOP/s and moves BW bytes/s runs an op at min(P, AI × BW). The ridge P / BW separates the two regimes: AGX Orin 42.5 TFLOPS ÷ 204.8 GB/s ≈ 208 FLOP/byte (Orin Nano Super: 17 TFLOPS ÷ 102 GB/s ≈ 167). Decode GEMVs sit at AI ≈ 1 and reach 0.205 TFLOPS, 0.48% of peak; prefill GEMMs at N = 4,096 sit at AI 1,365, on the flat roof. Depth: cookbook §2.
5 Memory: weights, KV cache, activations
| Item | Formula | Lives | Reference (B = 1, N = t = 4,096, FP16) |
|---|---|---|---|
| Weights | b·params | always | 13.31 GB (12.4 GiB); INT8 6.66 GB; INT4 3.33 GB |
| KV cache | 2·L·n_kv·d_k·b per token, × t × B | for the whole request | 512 KiB/token; 2 GiB at t = 4,096 |
| Prefill: X, and LN outputs | B·N·d·b | one layer at a time | 32 MiB each |
| Prefill: Q | K | V | 3·B·N·d·b | one layer | 96 MiB |
| Prefill: scores S (and A), unfused | B·h·N²·b | one layer | 1 GiB each |
| Prefill: FFN hidden | B·N·d_ff·b | one layer | 128 MiB |
| Prefill: logits, all rows vs last row | B·N·V·b vs B·V·b | once | 392.6 MiB vs 98.2 KiB |
| Decode: x, scores | B·d·b, B·h·t·b | one layer | 8 KiB, 256 KiB |
The N² fact, once: unfused, S and A each take b·B·h·N² bytes per layer, 1 GiB each at the reference N = 4,096. Inference frees them before the next layer, so the prefill peak is one layer's live set, X + Q|K|V + S + A (2.12 GiB). With FlashAttention the peak moves into the FFN: X, the LN₂ output and the hidden tensor before and after GELU, b·B·N·(2d + 2·d_ff) (320 MiB). Training keeps every layer's activations (§7).
Read it aloud: one K and one V vector of n_kv·d_k numbers per token per layer, b bytes each, for t tokens and B sequences.
Why it matters: it grows linearly with context and batch, and on an edge device it, not the weights, often sets the maximum of both.
Tiny example: L = 2, t = 3, n_kv = 2, d_k = 4, FP16: 192 bytes. GPT-2 small at t = 1,024: 36 MiB. Llama 3.1 8B (L = 32, n_kv = 8, d_k = 128): 128 KiB per token, 1 GiB at 8,192; with 32 K/V heads it would be 4× more.
kv_bytes = 2 * L * n_kv * d_k * dtype_bytes * t * B k_cache = torch.cat([k_cache, k_new], dim=2) # [B, n_kv, t, d_k] -> [B, n_kv, t + 1, d_k]
Does it fit on a Jetson?
| Reference model at t = 4,096, B = 1 | Weights + cache | AGX Orin 64 GB | Orin Nano Super 8 GB |
|---|---|---|---|
| FP16, MHA | 15.46 GB | 24% | 193%: does not fit |
| INT4 weights, MHA | 5.48 GB | 9% | 68% |
| INT4 weights, GQA-8 | 3.46 GB | 5% | 43% |
Nominal memory, shared by the CPU, the OS and your other processes; the cookbook flags anything above 75% as tight. Plus the activations above (2.12 GiB unfused, 320 MiB fused at N = 4,096). Plan model and context with the cookbook's memory planner.
6 Optimizations, mapped to phase
Each technique cuts FLOPs, bytes or launches, so it helps the phase bound by that resource. Depth, numbers and labs for each: the Memory & inference efficiency cookbook.
| Technique | Cuts | Prefill | Decode | Here | Cookbook |
|---|---|---|---|---|---|
| Fused QKV GEMM | launches, input reads | ✓ | ✓ | block 3 | |
| FlashAttention | N × N bytes and memory | ✓✓ | – | blocks 5–8 | d |
| Fused add + norm, GEMM epilogues (GELU, bias, residual) | elementwise bytes | ✓ | ✓ | below, CUTLASS | h |
| CUDA graphs | CPU launch overhead | – | ✓ | h | |
| Weight-only INT8 / INT4 | weight bytes | – | ✓✓ | below | c |
| INT8 weights and activations (W8A8) | FLOP time and bytes | ✓ | ✓ | below | c |
| GQA / MQA | KV bytes and memory | small | ✓✓ | §3.5 | b |
| KV-cache quantization (INT8) | KV bytes and memory | – | ✓ | §3.3 | a |
| Batching, continuous batching | weight bytes per token | – | ✓ (throughput) | §3.4 | e |
| Paged KV | wasted cache memory | – | ✓ (capacity) | §3.6 | e |
| Prefix caching | repeated prefill | ✓✓ | – | f | |
| Speculative decoding | weight reads per token | – | ✓ | §3.6 | g |
Every elementwise op in the §2.6 table is memory-bound: it reads and writes a whole [B, N, d] (or [B, N, d_ff]) tensor for one FLOP or a few. Fusing it into the GEMM before it (bias, GELU, residual add) or merging it with its neighbour (residual add + the next norm) removes that round trip. Per layer: GELU in W₁'s epilogue saves 2·b·B·N·d_ff bytes, the residual in W_O's epilogue 2·b·B·N·d, add + norm b·B·N·d per pair. The CUTLASS deep dive shows these epilogues in code. In decode the same ops are tiny, but each is still a kernel launch.
model = torch.compile(model) # fuses elementwise chains; TensorRT(-LLM) does it at build time from apex.normalization import FusedRMSNorm # fused norm kernel (the residual add is not fused here)
GPU kernel deep dive
- Why fusion pays. A chain of elementwise ops costs one DRAM round trip per op unfused and one in total fused; the FLOPs do not change. Read more: Horace He, Making deep learning go brrrr; cookbook card h.
- Epilogues. A GEMM kernel holds its output tile in registers before the store; bias, activation, residual add and even a quantize step can run there for free. Read more: CUTLASS deep dive (block 3); Triton tutorial: matrix multiplication.
- Launches in decode. ≈ 14·L + 3 kernels per decode step unfused, ≈ 7·L + 3 fused (block 12); CUDA Graphs replay the rest with one CPU call. Read more: NVIDIA, Getting started with CUDA Graphs.
- Weight-only INT4 / INT8 (the usual LLM recipe on Jetson Orin): weights are stored in 4 or 8 bits and dequantized inside the GEMM; the maths stays FP16. Decode reads 2–4× fewer weight bytes: 13.2 → 37.4 tok/s for the reference model with INT4 (§3.3). Prefill is compute-bound and barely changes.
- W8A8: INT8 weights and activations run on INT8 Tensor Cores, which have twice the FP16 rate, so they help prefill too.
- Orin's precisions: FP16, INT8 and INT4; no FP8 or FP4 (those arrive with Ada/Hopper and Blackwell, e.g. Jetson Thor). See the cookbook's device table.
GPU kernel deep dive
- Dequantize in registers. A weight-only GEMV loads packed 4-bit weights and their group scales, expands them to FP16 in registers and runs FP16 FMAs: the bytes shrink, the maths does not (block 3). Read more: cookbook card c.
- Scales cost bytes too. One FP16 scale per group of g weights adds 16/g bits per weight; finer groups keep accuracy but read more. Read more: cookbook card c, granularity.
- W8A8 on Tensor Cores. INT8 MMAs at twice the FP16 rate raise the compute roof for prefill, but the activations must be quantized on the fly, usually in the previous kernel's epilogue. Read more: NVIDIA, Matrix multiplication background.
Deep dive: TensorRT build with explicit (Q/DQ) quantization
What to notice: the model leaves PyTorch as an ONNX graph whose Q/DQ nodes set each layer's precision; the builder fuses layers, auto-tunes kernels and serializes an engine for one specific GPU.
# Q/DQ nodes come from NVIDIA Model Optimizer before export:
# import modelopt.torch.quantization as mtq; model = mtq.quantize(model, mtq.INT8_DEFAULT_CFG, forward_loop)
import tensorrt as trt
logger = trt.Logger(trt.Logger.WARNING)
builder = trt.Builder(logger)
network = builder.create_network(0)
trt.OnnxParser(network, logger).parse_from_file("model_qdq.onnx")
serialized = builder.build_serialized_network(network, builder.create_builder_config())
engine = trt.Runtime(logger).deserialize_cuda_engine(serialized)
# The implicit INT8 calibrator is deprecated since TensorRT 10.1 and removed in TensorRT 11.
7 Training in one screen
- Same forward pass, full sequence. Training runs §2's prefill on [B, N] token sequences, but with the LM head on every row. The input at position i is the true token i, not a sampled one (teacher forcing).
- N predictions per sequence, in parallel. The causal mask makes row i depend only on tokens 0…i, so one pass gives N independent next-token predictions. No KV cache is needed.
- Loss: cross-entropy at every position, ℒ = −(1 / B·N) Σb,i log pθ(xb,i+1 | xb,≤i), with targets = ids shifted left by one.
- Compute: backward costs about 2× forward (gradients for activations and for weights), so a step costs ≈ 3 × 2·params per token = 6·params·tokens. Reference config: 39.9 GFLOP per token, against 13.3 to generate one. GPT-2 small: 0.75 GFLOP per token; 10⁹ tokens is 7.46 × 10¹⁷ FLOP, 4.9 hours at AGX Orin's peak.
- Memory: mixed-precision Adam keeps 16 bytes per parameter (weights, grads, FP32 master, two moments): 106.5 GB for the reference config, more than an AGX Orin has. Activations of every layer stay for backward: per layer ≈ B·N·d·(34 + 5·h·N/d) bytes (Korthikanti et al. 2022). The 5·h·N/d term is the stored scores, which FlashAttention recomputes instead; activation checkpointing keeps only each layer's input, 2·B·N·d bytes. Reference, all 32 layers: 104 GB, 18 GB without scores, 1 GB with checkpointing.
logits = model(ids[:, :-1]) # [B, N, V]: the head on every row loss = F.cross_entropy(logits.reshape(-1, V), ids[:, 1:].reshape(-1)) loss.backward(); opt.step(); opt.zero_grad()
Build and train one yourself: Build an LLM, training; memory tricks (LoRA, QLoRA, checkpointing, ZeRO): cookbook card j.
8 What changed since 2017
This guide builds the GPT-2-style block because it is the simplest complete version. Current LLMs keep the skeleton and swap parts. You will meet each of these in later modules.
| Component | This guide | Modern LLMs (as of 2026) | Why | Next seen in |
|---|---|---|---|---|
| Norm position | pre-norm: x + F(LN(x)). The 2017 paper: post-norm, LN(x + F(x)) | pre-norm almost everywhere; Gemma 2 also normalizes each sub-layer's output, x + LN(F(LN(x))), a “sandwich” norm | the residual path stays a plain sum, so deep stacks train without warm-up tricks | primer, paper order; ViT |
| Norm type | LayerNorm | RMSNorm: no mean, divide by √mean(x²) | cheaper, same quality | Mamba, VLM language models |
| Positions | learned vectors added to x | RoPE: rotate each pair of q and k dimensions by an angle proportional to the position, so q·k depends only on the offset | relative positions, longer contexts | VLM, Mamba hybrids |
| FFN | GELU MLP | SwiGLU: silu(xW_g) ⊙ (xW_u), then W_d; a learned gate | better quality at equal parameters | VLM, MoE |
| K/V heads | n_kv = h | GQA / MQA: n_kv < h (Llama 3 8B: 32 query heads, 8 K/V heads) | 4× smaller cache for 32 → 8, faster decode (§3.5) | VLM; any edge LLM |
| Source of K/V | same sequence (self-attention) | + cross-attention: Q from one sequence, K/V from another | condition on image, camera or text features | diffusion, BEV, VLA, robot models |
What to notice: Q comes from one sequence (4 text tokens), K and V from another (6 image patches). The score matrix is rectangular, [N_q, N_kv] = [4, 6], with no causal mask. Self-attention is cross-attention of a sequence with itself.
The blocks are the same in all three families; only the mask and the source of K/V change. This guide and transformer.py build the decoder-only kind.
| Family | Who sees whom | Examples | Where you'll meet it |
|---|---|---|---|
| Decoder-only (this guide) | causal: token i sees tokens 0…i | GPT-2/3, Llama, Qwen | here; the language model inside VLMs and VLAs |
| Encoder-only | bidirectional: every token sees every token | BERT, ViT | ViT (Module 2), VLM vision encoders |
| Encoder–decoder (the 2017 paper) | bidirectional encoder + causal decoder + cross-attention | original Transformer, T5, Whisper | cross-attention returns in diffusion, BEV, VLA, robot models |
9 Build it and check yourself
transformer.py is the complete model of this guide (its docstring lists where it differs from the 2017 paper). inference_math.py prints every worked number above; change its configs to size your own model and device.
The full transformer.py listing (about 570 lines)
""" Minimal Transformer Implementation (decoder-only, GPT-style) Run: python transformer.py This is a DECODER-ONLY (GPT-2-style) causal language model built from the blocks of "Attention Is All You Need" (Vaswani et al., 2017). It is NOT the paper's encoder-decoder model. Differences from the 2017 paper: - decoder only: no encoder and no cross-attention - pre-LayerNorm + a final LayerNorm (paper: post-LN, x = LN(x + Sublayer(x))) - GELU in the FFN (paper: ReLU) - learned positional embeddings (paper: sinusoidal; learned PE was an ablation) - no sqrt(d_model) scaling of the token embedding (GPT-2 convention; the paper multiplies by sqrt(d_model) and pairs it with sinusoidal PE) - no biases in the attention projections, GPT-2 init (normal, std 0.02) Shared with the paper: scaled dot-product multi-head attention, the position-wise FFN with d_ff = 4*d, residual connections, and tying the embedding and output (LM-head) weights (paper Sec. 3.4). This implementation prioritizes clarity over efficiency. For production, use F.scaled_dot_product_attention / HuggingFace / TensorRT-LLM. References: - Paper: https://arxiv.org/abs/1706.03762 (Attention Is All You Need) - PyTorch: https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html """ import torch import torch.nn as nn import torch.nn.functional as F class MultiHeadAttention(nn.Module): """ Multi-Head Attention mechanism. Args: d_model: Hidden dimension (embedding size) n_heads: Number of attention heads dropout: Dropout probability Shapes: Input: [B, N, d_model] mask: bool tensor broadcastable to [B, h, N, N]. True = this query MAY attend to this key. Same convention as the bool attn_mask of F.scaled_dot_product_attention, but the OPPOSITE of nn.MultiheadAttention / nn.Transformer, where True (or -inf) means "blocked". A row with no True entry gives NaN. Output: [B, N, d_model] Reference: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html """ def __init__(self, d_model: int, n_heads: int, dropout: float = 0.1): super().__init__() assert d_model % n_heads == 0, "d_model must be divisible by n_heads" self.d_model = d_model self.n_heads = n_heads self.d_k = d_model // n_heads # Dimension per head self.scale = self.d_k ** -0.5 # 1/sqrt(d_k) # Linear projections for Q, K, V # Reference: https://pytorch.org/docs/stable/generated/torch.nn.Linear.html self.W_q = nn.Linear(d_model, d_model, bias=False) self.W_k = nn.Linear(d_model, d_model, bias=False) self.W_v = nn.Linear(d_model, d_model, bias=False) self.W_o = nn.Linear(d_model, d_model, bias=False) self.dropout = nn.Dropout(dropout) self.last_attn = None # attention weights of the last call (for inspection/demos) def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor: B, N, _ = x.shape # Project to Q, K, V # Each: [B, N, d_model] @ [d_model, d_model] -> [B, N, d_model] # GPU: cuBLAS GEMM kernel Q = self.W_q(x) K = self.W_k(x) V = self.W_v(x) # Reshape for multi-head attention # [B, N, d_model] -> [B, N, n_heads, d_k] -> [B, n_heads, N, d_k] Q = Q.view(B, N, self.n_heads, self.d_k).transpose(1, 2) K = K.view(B, N, self.n_heads, self.d_k).transpose(1, 2) V = V.view(B, N, self.n_heads, self.d_k).transpose(1, 2) # Compute attention scores # [B, h, N, d_k] @ [B, h, d_k, N] -> [B, h, N, N] # This is O(N²) memory - the bottleneck! # GPU: cuBLAS batched GEMM (one small GEMM per (batch, head)) scores = torch.matmul(Q, K.transpose(-2, -1)) * self.scale # Apply mask (for causal attention): blocked positions get -inf, # so exp(-inf) = 0 after the softmax. if mask is not None: assert mask.dtype == torch.bool, "mask must be bool, True = may attend" scores = scores.masked_fill(~mask, float('-inf')) # Softmax and dropout # Reference: https://pytorch.org/docs/stable/generated/torch.nn.functional.softmax.html attn_weights = F.softmax(scores, dim=-1) self.last_attn = attn_weights.detach() attn_weights = self.dropout(attn_weights) # Apply attention to values # [B, h, N, N] @ [B, h, N, d_k] -> [B, h, N, d_k] context = torch.matmul(attn_weights, V) # Reshape back # [B, h, N, d_k] -> [B, N, h, d_k] -> [B, N, d_model] context = context.transpose(1, 2).contiguous().view(B, N, self.d_model) # Output projection return self.W_o(context) class FeedForward(nn.Module): """ Position-wise Feed-Forward Network. FFN(x) = Linear2(GELU(Linear1(x))) (the 2017 paper uses ReLU) Holds ~2/3 of each block's parameters (8d² of 12d², ignoring biases). Shapes: Input: [B, N, d_model] Output: [B, N, d_model] Reference: https://pytorch.org/docs/stable/generated/torch.nn.GELU.html """ def __init__(self, d_model: int, d_ff: int = None, dropout: float = 0.1): super().__init__() d_ff = d_ff or 4 * d_model # Default: 4x expansion self.linear1 = nn.Linear(d_model, d_ff) self.linear2 = nn.Linear(d_ff, d_model) self.dropout = nn.Dropout(dropout) self.activation = nn.GELU() def forward(self, x: torch.Tensor) -> torch.Tensor: # [B, N, d] -> [B, N, d_ff] -> [B, N, d] x = self.linear1(x) # GPU: cuBLAS GEMM x = self.activation(x) # GPU: Elementwise kernel x = self.dropout(x) x = self.linear2(x) # GPU: cuBLAS GEMM return x class TransformerBlock(nn.Module): """ Single Transformer block with pre-normalization (GPT-2 style). Structure: x = x + Attention(LayerNorm(x)) x = x + FFN(LayerNorm(x)) (The 2017 paper uses post-norm: x = LN(x + Sublayer(x)).) Reference: https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html """ def __init__(self, d_model: int, n_heads: int, d_ff: int = None, dropout: float = 0.1): super().__init__() self.norm1 = nn.LayerNorm(d_model) self.attn = MultiHeadAttention(d_model, n_heads, dropout) self.norm2 = nn.LayerNorm(d_model) self.ffn = FeedForward(d_model, d_ff, dropout) self.dropout = nn.Dropout(dropout) def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor: # Pre-norm + residual for attention x = x + self.dropout(self.attn(self.norm1(x), mask)) # Pre-norm + residual for FFN x = x + self.dropout(self.ffn(self.norm2(x))) return x class Transformer(nn.Module): """ Complete decoder-only Transformer language model. Args: vocab_size: Size of vocabulary (V) d_model: Hidden dimension (d) n_heads: Number of attention heads (h) n_layers: Number of transformer blocks (L) d_ff: Feed-forward hidden dimension (d_ff, default 4*d) max_seq_len: Maximum sequence length (N_max) dropout: Dropout probability Shapes: Input: [B, N] token ids Output: [B, N, V] logits (row i = scores for the token at position i+1) Reference: https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html """ def __init__( self, vocab_size: int, d_model: int = 512, n_heads: int = 8, n_layers: int = 6, d_ff: int = None, max_seq_len: int = 512, dropout: float = 0.1 ): super().__init__() self.d_model = d_model self.n_layers = n_layers # Token and position embeddings self.token_emb = nn.Embedding(vocab_size, d_model) self.pos_emb = nn.Embedding(max_seq_len, d_model) self.dropout = nn.Dropout(dropout) # Transformer blocks self.layers = nn.ModuleList([ TransformerBlock(d_model, n_heads, d_ff, dropout) for _ in range(n_layers) ]) # Final layer norm self.norm = nn.LayerNorm(d_model) # Output projection to vocabulary (the "LM head") self.output = nn.Linear(d_model, vocab_size, bias=False) # Tie weights with token embeddings (common practice) self.output.weight = self.token_emb.weight # Initialize weights self.apply(self._init_weights) def _init_weights(self, module): if isinstance(module, nn.Linear): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: torch.nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) def forward(self, x: torch.Tensor) -> torch.Tensor: B, N = x.shape assert N <= self.pos_emb.num_embeddings, ( f"sequence length {N} > max_seq_len {self.pos_emb.num_embeddings} " "(learned positional embeddings cannot extrapolate)") # Causal mask: True = may attend. Query i sees keys 0..i (lower triangle). mask = torch.tril(torch.ones(N, N, dtype=torch.bool, device=x.device)) # Embeddings: row lookup in the [V, d] table + a learned position vector. # GPT-2 style: no sqrt(d_model) scaling (see module docstring). positions = torch.arange(N, device=x.device).unsqueeze(0) x = self.token_emb(x) x = x + self.pos_emb(positions) x = self.dropout(x) # Transformer layers for layer in self.layers: x = layer(x, mask) # Output x = self.norm(x) logits = self.output(x) return logits def count_parameters(self) -> int: """Count total trainable parameters (tied weights counted once).""" return sum(p.numel() for p in self.parameters() if p.requires_grad) def print_model_summary(model: Transformer): """Print a summary of the model architecture.""" print("=" * 70) print("TRANSFORMER MODEL SUMMARY") print("=" * 70) d = model.d_model h = model.layers[0].attn.n_heads d_k = model.layers[0].attn.d_k d_ff = model.layers[0].ffn.linear1.out_features L = len(model.layers) V = model.token_emb.num_embeddings N_max = model.pos_emb.num_embeddings print(f"\n{'NOTATION':-^70}") print(f" B = Batch size") print(f" N = Sequence length (max {N_max})") print(f" d = Hidden dimension = {d}") print(f" h = Number of heads = {h}") print(f" d_k = Head dimension = d/h = {d_k}") print(f" d_ff = FFN hidden = {d_ff}") print(f" L = Number of layers = {L}") print(f" V = Vocabulary size = {V}") total_params = model.count_parameters() print(f"\n{'PARAMETERS':-^70}") print(f" Total: {total_params:,} ({total_params / 1e6:.2f}M)") # Parameter breakdown qkv = 3 * d * d out_proj = d * d ffn = 2 * d * d_ff + d_ff + d # weights + biases layer_norm = 4 * d per_layer = qkv + out_proj + ffn + layer_norm tok_emb = V * d # tied with the LM head, so counted once pos_emb = N_max * d final_ln = 2 * d print(f"\n{'PER LAYER BREAKDOWN':-^70}") print(f" QKV projections (W_q, W_k, W_v): 3 × d × d = 3 × {d}² = {qkv:,}") print(f" Output projection (W_o): d × d = {d}² = {out_proj:,}") print(f" FFN (Linear1 + Linear2): 2 × d × d_ff + d_ff + d = {ffn:,}") print(f" LayerNorm (γ, β × 2): 4 × d = {layer_norm:,}") print(f" {'':->50}") print(f" Total per layer: {per_layer:,}") print(f" Total for {L} layers: {per_layer * L:,}") print(f" + token embedding (= LM head): V × d = {tok_emb:,}") print(f" + position embedding: N_max × d = {pos_emb:,}") print(f" + final LayerNorm: 2 × d = {final_ln:,}") breakdown = per_layer * L + tok_emb + pos_emb + final_ln print(f" = {breakdown:,} (matches Total)") assert breakdown == total_params, "parameter breakdown does not add up" print(f"\n{'COMPLEXITY (per layer, batch=1)':-^70}") print(f" QKV projection FLOPs: 6 × N × d² = 6N × {d}²") print(f" Attention (QKᵀ + ×V): 4 × N² × d = 4N² × {d} ← O(N²)!") print(f" Output projection: 2 × N × d² = 2N × {d}²") print(f" FFN: 4 × N × d × d_ff = 4N × {d} × {d_ff}") print(f" Softmax (estimate): 5 × h × N² = 5 × {h} × N²") print(f" (+ once per model: LM head 2 × N × d × V = 2N × {d} × {V})") print(f"\n{'MEMORY (per layer, FP32)':-^70}") print(f" Attention scores: h × N × N × 4B = {h} × N² × 4 bytes ← O(N²)!") print(f" KV cache (infer): 2 × N × d × 4B = 2 × N × {d} × 4 bytes") print(f" Activations: N × d × 4B = N × {d} × 4 bytes") print("\n" + "=" * 70) def compute_flops(B: int, N: int, d: int, h: int, d_ff: int, L: int, V: int = 0) -> dict: """ FLOPs of one forward pass over N tokens (2 FLOPs per multiply-accumulate). Counts the matmuls of the L blocks and the LM head (2*B*N*d*V; pass V=0 to skip it), plus a 5*h*N² softmax estimate. Ignores LayerNorm, GELU, residual adds, the embedding gather, and the ~2x saving a causal kernel can get by skipping masked scores. All keys except 'per_layer' are summed over the L layers; 'per_layer' is ONE layer (softmax included, LM head excluded). """ # Per layer qkv = 6 * B * N * d * d qkt = 2 * B * N * N * d softmax = 5 * B * h * N * N av = 2 * B * N * N * d out_proj = 2 * B * N * d * d ffn = 4 * B * N * d * d_ff per_layer = qkv + qkt + softmax + av + out_proj + ffn lm_head = 2 * B * N * d * V total = L * per_layer + lm_head return { 'qkv_projection': qkv * L, 'qk_transpose': qkt * L, 'softmax': softmax * L, 'attn_v': av * L, 'out_projection': out_proj * L, 'ffn': ffn * L, 'lm_head': lm_head, 'per_layer': per_layer, 'total': total } def compute_memory(B: int, N: int, d: int, h: int, dtype_bytes: int = 4) -> dict: """ Memory of ONE layer, in bytes. attention_scores: the naive [B, h, N, N] score matrix. At inference it is freed before the next layer runs; FlashAttention never stores it. kv_cache: K and V for N tokens with classic multi-head attention (with grouped-query attention, multiply by n_kv_heads / h). """ return { 'attention_scores': B * h * N * N * dtype_bytes, 'kv_cache': 2 * B * N * d * dtype_bytes, 'activations': B * N * d * dtype_bytes, } def format_number(n: float) -> str: """Format large numbers with K/M/G/T/P suffixes (powers of 1000).""" for div, suffix in ((1e15, "P"), (1e12, "T"), (1e9, "G"), (1e6, "M"), (1e3, "K")): if abs(n) >= div: return f"{n/div:.2f}{suffix}" return f"{n:.0f}" def format_bytes(b: float) -> str: """Format bytes with binary units (KiB/MiB/GiB/TiB, powers of 1024).""" for div, suffix in ((2**40, "TiB"), (2**30, "GiB"), (2**20, "MiB"), (2**10, "KiB")): if b >= div: return f"{b/div:.2f} {suffix}" return f"{b:.0f} B" def demo_forward_pass(): """Demonstrate a forward pass with shape annotations.""" print("\n" + "=" * 70) print("DEMO: Forward Pass with Shape Tracking") print("=" * 70) torch.manual_seed(0) # Model config B = 2 # Batch size N = 16 # Sequence length V = 1000 # Vocab size d = 256 # Hidden dimension h = 8 # Number of heads L = 4 # Number of layers d_ff = 4 * d print(f"\nConfiguration:") print(f" B (batch) = {B}") print(f" N (seq len) = {N}") print(f" d (hidden) = {d}") print(f" h (heads) = {h}") print(f" d_k (per head)= {d // h}") print(f" d_ff (FFN) = {d_ff}") print(f" L (layers) = {L}") print(f" V (vocab) = {V}") # Create model model = Transformer( vocab_size=V, d_model=d, n_heads=h, n_layers=L, max_seq_len=512 ) model.eval() # disable dropout for inference (torch.no_grad only disables autograd) # Print summary print_model_summary(model) # Create dummy input x = torch.randint(0, V, (B, N)) print(f"\nInput shape: {list(x.shape)} = [batch, sequence]") # Forward pass with torch.no_grad(): logits = model(x) print(f"Output shape: {list(logits.shape)} = [batch, sequence, vocab]") assert logits.shape == (B, N, V) # Compute FLOPs flops = compute_flops(B, N, d, h, d_ff, L, V) print(f"\n{'FLOPs BREAKDOWN (all layers)':-^70}") print(f" QKV projection: {format_number(flops['qkv_projection']):>10} FLOPs") print(f" QKᵀ matmul: {format_number(flops['qk_transpose']):>10} FLOPs") print(f" Softmax (est.): {format_number(flops['softmax']):>10} FLOPs") print(f" Attention × V: {format_number(flops['attn_v']):>10} FLOPs") print(f" Output proj: {format_number(flops['out_projection']):>10} FLOPs") print(f" FFN: {format_number(flops['ffn']):>10} FLOPs") print(f" LM head: {format_number(flops['lm_head']):>10} FLOPs") print(f" {'':->50}") print(f" Total: {format_number(flops['total']):>10} FLOPs") # Compute memory mem = compute_memory(B, N, d, h) print(f"\n{'MEMORY PER LAYER (FP32)':-^70}") print(f" Attention scores: {format_bytes(mem['attention_scores']):>10} (O(N²) - bottleneck!)") print(f" KV cache: {format_bytes(mem['kv_cache']):>10} (O(N))") print(f" Activations: {format_bytes(mem['activations']):>10} (O(N))") print("\n" + "=" * 70) print("✓ Forward pass complete!") print("=" * 70) def demo_causality(): """Show the causal attention pattern and why it makes a KV cache valid.""" print("\n" + "=" * 70) print("DEMO: Causal mask => past tokens never change => KV cache is valid") print("=" * 70) torch.manual_seed(0) model = Transformer(vocab_size=1000, d_model=64, n_heads=4, n_layers=2, max_seq_len=64) model.eval() x = torch.randint(0, 1000, (1, 8)) with torch.no_grad(): logits = model(x) w = model.layers[0].attn.last_attn[0, 0, :5, :5] # layer 0, head 0, first 5 tokens print("\nAttention weights, layer 0 / head 0 (rows = query i, cols = key j):") for i, row in enumerate(w.tolist()): print(f" q{i}: " + " ".join(f"{v:5.2f}" for v in row)) print(" -> upper triangle is exactly 0 (no peeking ahead); each row sums to 1.") print(" An untrained model spreads weight almost evenly: ~1, 1/2, 1/3, 1/4, 1/5.") with torch.no_grad(): prefix_logits = model(x[:, :5]) same = torch.allclose(logits[:, :5], prefix_logits, atol=1e-5) print(f"\nLogits of tokens 0..4 unchanged when tokens 5..7 are appended? {same}") print(" -> K, V of old tokens never change, so they can be computed once and cached.") def demo_scaling(): """Show how complexity scales with different parameters.""" print("\n" + "=" * 70) print("SCALING ANALYSIS: How complexity grows") print("=" * 70) V = 50257 # GPT-2 / GPT-3 vocabulary configs = [ # name, d, h, L, N (context) ("GPT-2 Small (124M)", 768, 12, 12, 1024), ("GPT-2 Medium (355M)", 1024, 16, 24, 1024), ("GPT-3 6.7B", 4096, 32, 32, 2048), ("GPT-3 175B", 12288, 96, 96, 2048), ] print("\nOne forward pass over the full context, batch 1, LM head included.") print("'Attn scores/layer' = one layer's naive [h, N, N] FP32 score matrix.") print(f"\n{'Model':<20} {'d':>6} {'h':>4} {'L':>4} {'N':>6} {'FLOPs':>10} {'Attn scores/layer':>18}") print("-" * 72) for name, d, h, L, N in configs: d_ff = 4 * d flops = compute_flops(1, N, d, h, d_ff, L, V) mem = compute_memory(1, N, d, h) print(f"{name:<20} {d:>6} {h:>4} {L:>4} {N:>6} {format_number(flops['total']):>10} " f"{format_bytes(mem['attention_scores']):>18}") print("\n" + "=" * 70) # Show N² scaling print("\nSequence length scaling (d=4096, h=32, L=32):") print(f"\n{'N':>8} {'Attention FLOPs (all L)':>24} {'Attn scores / layer (FP32)':>28}") print("-" * 62) for N in [512, 1024, 2048, 4096, 8192, 16384]: flops = compute_flops(1, N, 4096, 32, 16384, 32) mem = compute_memory(1, N, 4096, 32) attn_flops = flops['qk_transpose'] + flops['attn_v'] attn_mem = mem['attention_scores'] # one layer; freed before the next layer at inference print(f"{N:>8} {format_number(attn_flops):>24} {format_bytes(attn_mem):>28}") print("\n⚠️ Note: Attention memory scales O(N²) - this is why FlashAttention exists!") print(" (Training keeps every layer's activations for backward: multiply by L.)") if __name__ == "__main__": demo_forward_pass() demo_causality() demo_scaling()
# one-time setup (transformer.py needs torch >= 2.1)
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python3 transformer.py # shapes, parameter breakdown, FLOPs, causal / KV-cache check
python3 inference_math.py # every table of §2–§7 (standard library only; --json too)
Key takeaways
- The model is 11 equations (§1): embed, then L × [x += attn(LN(x)); x += FFN(LN(x))], then LN_f and the LM head. About 12·L·d² + V·d parameters.
- The head split reshapes Q's output columns; every head's projection reads all d inputs. One [d × d] GEMM equals the paper's h separate [d × d_k] projections.
- Prefill: GEMMs with M = B·N rows, FLOPs L·(24Nd² + 4N²d), compute-bound, TTFT ≈ FLOPs ÷ FLOP/s. The N² scores are a prefill problem; FlashAttention removes their memory and traffic, not their FLOPs.
- Prefill writes K and V, [B, n_kv, N, d_k] per layer. The causal mask keeps them valid; decode needs no mask and no Q cache.
- Decode: GEMVs with M = B, ≈ 2·params + 4·L·t·d FLOPs over b·params + KV bytes, AI ≈ 1, memory-bound, TPOT ≈ bytes ÷ bandwidth: ≈ 13 tok/s for the 7B-class FP16 model on AGX Orin at t = 4,096.
- Decode gets faster by moving fewer bytes (INT4 weights, GQA, KV quantization) or using each byte more (batching, speculative decoding); prefill by doing fewer or faster FLOPs and fusing.
- Memory: weights, KV cache (2·L·n_kv·d_k·b per token) and one layer's activations at inference; every layer's activations plus 16 B/param of optimizer state in training.
Self-check
Try each question before opening the answer.
1. d = 4096 and h = 32. What is d_k, and what is the shape of the scores for B = 2, N = 128?
Answer
d_k = 4096 / 32 = 128. Scores are [B, h, N, N] = [2, 32, 128, 128].
2. In the reference model, how many of a token's 4,096 input numbers does head 3's query read, and how big is the paper's W3Q?
Answer
All 4,096: every column of Q is a dot product with the whole token. W3Q is [4096 × 128], columns 384–511 of W_Q. The 32 heads' matrices side by side are the [4096 × 4096] W_Q, so the parameter count is the same either way.
3. You double the prompt length N. By how much do the QKV FLOPs and the Q·Kᵀ FLOPs grow, and what happens to the unfused score memory?
Answer
QKV is 6·B·N·d², linear: 2×. Q·Kᵀ is 2·B·N²·d, quadratic: 4×. The unfused score tensor B·h·N²·b also grows 4×.
4. Why does a decode step need no causal mask, and why is Q not cached?
Answer
The new token is the last row; every key in the cache is at a position ≤ its own, so its mask row is all zeros. Q is used once, to produce its own row's output; old queries are never read again, while every later query reads all K and V.
5. Llama 2 7B has L = 32, d = 4096 and 32 K/V heads of 128. In FP16, how big is its KV cache per token and at 4,096 tokens? And with 8 K/V heads?
Answer
2 × 32 × 32 × 128 × 2 B = 512 KiB per token, 2 GiB at 4,096 tokens per sequence. With 8 K/V heads: 128 KiB per token, 512 MiB: 4× smaller.
6. The reference model decodes at B = 1, t = 4,096 on an AGX Orin. Is it compute- or memory-bound, what is the bound on tokens/s, and what do INT4 weights give?
Answer
Memory-bound: 15.44 GFLOP over 15.46 GB is AI ≈ 1, far below the ridge of 208. TPOT ≥ 15.46 GB ÷ 204.8 GB/s = 75.5 ms, ≈ 13 tok/s. INT4 weights: 3.33 + 2.15 = 5.48 GB per step, ≈ 37 tok/s; the cache read now matters as much as the weights.
7. Batching B sequences multiplies decode throughput for the weight GEMMs. Why does it not raise the intensity of attention over the cache?
Answer
Each sequence reads its own cache, so cache bytes grow with B just like attention FLOPs. Per sequence, AI = 4·t·h·d_k ÷ (2·t·n_kv·d_k·2 B) = h / n_kv: 1 for MHA, 4 for GQA-8, whatever B is.
8. Bound the TTFT of a 4,096-token prompt for the reference model on an AGX Orin. Is a 128-token prompt bound the same way?
Answer
61.57 TFLOP ÷ 42.5 TFLOPS ≥ 1.45 s, compute-bound (GEMM AI 1,365). A 128-token prompt needs 1.66 TFLOP (39 ms of compute) but still reads all 13.31 GB of weights (65 ms): it is memory-bound, like decode.
9. What does FlashAttention change: the FLOPs, the extra memory, the DRAM traffic, the result? Does it help decode?
Answer
FLOPs: the same. Extra memory: O(N²) → O(N), only the row statistics. DRAM traffic: no N × N round trips. Result: identical up to rounding. Decode has one query row and no N × N matrix, so its gain there is small; decode is bound by the weight and cache reads.
10. Roughly what does training the reference model cost per token, and why can you not fully fine-tune it on an AGX Orin 64GB?
Answer
6·params ≈ 39.9 GFLOP per token. Mixed-precision Adam needs 16 B per parameter, 106.5 GB, before activations: more than 64 GB. LoRA/QLoRA with checkpointing is the edge recipe (cookbook card j).
Hands-on exercises
Self-checking scripts that rebuild this guide's pieces (labs/index.html). Do them in order.
- labs/lab01.html: scaled dot-product attention with a causal mask, the head split and merge, multi-head attention (§2.2).
- labs/lab02.html: a pre-norm block in GPT-2 style and Llama style, with a closed-form parameter count (§1, §2.3).
- labs/lab03.html: a tiny GPT, greedy and top-k generation, and a KV cache that must match full recomputation (§3).
The exercises extend transformer.py. Call model.eval() before comparing outputs, so dropout is off.
1. Make the counters exact (easy)
Check the analytic FLOP count against PyTorch's counter. Then remove the weight-tying line and predict the new parameter count.
from torch.utils.flop_counter import FlopCounterMode
with torch.no_grad(), FlopCounterMode(display=False) as fc:
model(x)
f = compute_flops(B, N, d, h, d_ff, L, V)
assert fc.get_total_flops() == f['total'] - f['softmax'] # the counter only sees matmuls
# untied: count_parameters() grows by exactly V * d
2. Prove the head split is lossless (easy)
For a random MultiHeadAttention, slice W_q.weight into the paper's h per-head matrices, run h separate attentions, concatenate, apply W_o, and compare with the module's output. Then zero the off-diagonal blocks of W_q (the lossy version) and show the outputs differ.
W = mha.W_q.weight.T # nn.Linear stores [out, in] heads = [x @ W[:, i*d_k:(i+1)*d_k] for i in range(h)] # each [B, N, d_k], reads all d inputs assert torch.allclose(torch.cat(heads, -1), mha.W_q(x), atol=1e-6)
3. Implement the KV cache (medium)
Write forward_cached(ids_new, caches, start_pos) that keeps per-layer (K, V) of shape [B, h, t, d_k], offsets the positions by start_pos, and needs a mask only for multi-token chunks. Then a greedy generate(): one prefill, then one token per step.
assert (torch.cat(step_logits, dim=1) - model(ids)).abs().max() < 1e-5 assert generate_with_cache(ids, 20).equal(generate_without_cache(ids, 20)) # cache bytes == 2 * L * B * t * d * 4 (FP32)
4. Grouped-query attention (medium)
Add n_kv_heads: W_k and W_v output n_kv_heads·d_k features; repeat K and V with repeat_interleave(n_heads // n_kv_heads, dim=1) before Q·Kᵀ. Check that n_kv_heads = n_heads reproduces the original and that the cache of exercise 3 shrinks by h / n_kv.
5. Measure prefill and decode on your Jetson (medium)
Build a GPT-2-small-shaped model in FP16 on the GPU. Time one prefill for N = 128 … 1,024 and one cached decode step for t = 128 … 1,024. Compare with inference_math.prefill(GPT2, N) and decode(GPT2, t) for your device, and report the achieved fraction of each roof. Where does prefill turn compute-bound?
torch.cuda.synchronize(); t0 = time.perf_counter() with torch.no_grad(): model(ids) torch.cuda.synchronize(); ms = 1e3 * (time.perf_counter() - t0) # warm up first, average many runs
6. Back to the 2017 paper (harder)
Add options for post-norm (x = LN(x + F(x)), no final LN), ReLU and sinusoidal positions. Check a block against nn.TransformerEncoderLayer(..., norm_first=False) with a causal mask after copying the weights.
Next: labs 01–03 (python labs/check.py 1), then Build an LLM from scratch, where you train the model of §7. Then the next module: Vision Transformer, the same block on image patches with bidirectional attention: no causal mask, no KV cache, prefill only.
10 References
Videos
- 3Blue1Brown, Chapter 5: Transformers, the tech behind LLMs (27 min)
- 3Blue1Brown, Chapter 6: Attention in transformers, step-by-step (26 min)
- 3Blue1Brown, Chapter 7: How might LLMs store facts (the FFN, 23 min)
- Andrej Karpathy, Let's build GPT: from scratch, in code, spelled out (1 h 56 min)
- Tri Dao, FlashAttention (Stanford MLSys, 59 min)
- Umar Jamil, LLaMA explained: KV-Cache, RoPE, RMS Norm, GQA, SwiGLU (71 min)
Papers
- Attention Is All You Need (Vaswani et al., 2017)
- Online normalizer calculation for softmax (Milakov & Gimelshein, 2018)
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (Dao et al., 2022)
- FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning (Dao, 2023)
- FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision (Shah et al., 2024)
- FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling (Zadouri et al., 2026)
- Fast Transformer Decoding: One Write-Head is All You Need (Shazeer, 2019; MQA)
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023)
- Efficient Memory Management for Large Language Model Serving with PagedAttention (Kwon et al., 2023)
- Reducing Activation Recomputation in Large Transformer Models (Korthikanti et al., 2022)
- On Layer Normalization in the Transformer Architecture (Xiong et al., 2020; pre-norm vs post-norm)
- Gemma 2: Improving Open Language Models at a Practical Size (Gemma Team, 2024; pre- and post-norm)
- RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021; RoPE)
- Root Mean Square Layer Normalization (Zhang & Sennrich, 2019)
- GLU Variants Improve Transformer (Shazeer, 2020; SwiGLU)
- Transformer Feed-Forward Layers Are Key-Value Memories (Geva et al., 2021)
- Llama 2: Open Foundation and Fine-Tuned Chat Models (Touvron et al., 2023)
- The Llama 3 Herd of Models (Llama Team, Meta, 2024)
PyTorch and NVIDIA
- torch.nn.functional.scaled_dot_product_attention and sdpa_kernel
- torch.nn.MultiheadAttention, torch.nn.LayerNorm, torch.nn.GELU
- TensorRT documentation; Working with quantized types (Q/DQ)
- NVIDIA Model Optimizer (INT8 / FP8 / INT4 AWQ / FP4), TensorRT-LLM, Apex, CUTLASS
- Jetson Orin modules: specifications; NVIDIA H100