Transformer Architecture

The formal follow-up to the step-by-step primer: one decoder-only model, walked through prefill and then decode, with the shape, FLOPs and bytes of every operation.

Decoder-only (GPT-style), pre-norm, building on "Attention Is All You Need" (Vaswani et al., 2017)
Worked numbers on Jetson AGX Orin; also TensorRT, DRIVE

0 Start here

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 answersPrimer steps
1What exactly is computed, with which shapes and how many weights?19
2Prefill: what does each op cost when the whole prompt goes in at once? What lands in the KV cache?2–17
3Decode: why does every new token cost a full read of the weights and the cache?18
4Which phase is compute-bound, which is memory-bound, and what helps each?
5, 6What fills DRAM, and which optimization cuts what?
7, 8What changes for training, and since 2017?16
9Code, 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

  1. 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).
  2. The Illustrated GPT-2 (Jay Alammar). A decoder-only model picture by picture, including processing one new token at a time.
  3. Transformer Explainer (Georgia Tech, interactive). GPT-2 in the browser: inspect every step of a forward pass.
  4. Let's build GPT: from scratch, in code, spelled out (Andrej Karpathy, 1 h 56 min). The best companion to §9 and the labs.
  5. 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

SymbolMeaningReferenceGPT-2 smallPrimer toy
Bbatch: sequences processed together111
Nprompt length: rows in one prefill pass4,0961,0243
tcached length: K/V rows one decode step attends to4,096–4
dtoken vector size in the residual stream (d_model; also "model width", "hidden size"); every weight matrix is sized by it4,0967684
hquery heads32122
n_kvK/V heads: distinct key/value heads, each shared by h / n_kv query heads (= h for MHA; fewer for GQA/MQA, §3.5)32122
d_khead size, d / h (also d_v)128642
d_ffFFN hidden width16,384 = 4d3,0728
Llayers (blocks)32121
Vvocabulary size50,25750,2578
bbytes per element2 (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.

#EquationShape
1X = E[ids] + P[0:N][B, N] → [B, N, d]
for ℓ = 1 … L (weights of layer ℓ)
2X̂ = LN₁(X)[B, N, d]
3[Q | K | V] = X̂ · W_QKV[B, N, d]·[d, (h + 2·n_kv)·d_k]
4Q → [B, h, N, d_k]; K, V → [B, n_kv, N, d_k]view + transpose, no arithmetic
5S = Q·Kᵀ / √d_k + M_c[B, h, N, N]
6A = softmax(S) (row-wise)[B, h, N, N]
7O = A · V[B, h, N, d_k]
8X ← X + merge(O) · W_O[B, N, h·d_k]·[h·d_k, d] → [B, N, d]
9X ← X + GELU(LN₂(X)·W₁ + b₁)·W₂ + b₂[B, N, d] → [B, N, d_ff] → [B, N, d]
after the stack
10z = LN_f(X[:, N−1]) · Eᵀ[B, d]·[d, V] → [B, V]
11next ~ 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

TensorShapeCountReference
E (embedding = LM head, tied)[V, d]V·d205,852,672
P (learned positions)[N_max, d]N_max·d8,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]4d16,384
Block12d²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.

FormatBitsSign / exp / mantissaLargestRelative stepTensor Cores
FP32321 / 8 / 233.4·10³⁸2⁻²³all (TF32 on Ampere+)
FP16161 / 5 / 1065,5042⁻¹⁰Volta+, Orin
BF16161 / 8 / 73.4·10³⁸2⁻⁷Ampere+, Orin
FP8 E4M381 / 4 / 34482⁻³Ada, Hopper, Blackwell
FP8 E5M281 / 5 / 257,3442⁻²Ada, Hopper, Blackwell
FP4 E2M141 / 2 / 162⁻¹Blackwell (with a scale per 16 or 32 values)
INT88q ∈ −128 … 127127·ss / x (uniform step s)Turing+, Orin
INT44q ∈ −8 … 77·ss / xusually weight-only: dequantized to FP16 in the kernel

Each tick is one storable value (negatives mirror these); a value between ticks rounds to the nearest one. Green rows: floats. Orange rows: integers × s. On the log axis the float ticks are evenly spaced (constant relative error); integer ticks crowd at large values and thin out near 0, which is why one outlier in a group (large s) rounds that group's small values to 0.

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

× L residual stream x : [B, N, d] Embedding LN Attention + LN FFN + LN + LM head 1 2 3 inside Attention QKV split heads Q·Kᵀ ÷√d_k, mask softmax A·V merge, W_O K, V → KV cache FlashAttention

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

Multi-head attention in one line
MHA(X̂) = concat(head₁, …, head_h) · W_O, head_i = softmax(X̂WiQ (X̂WiK)ᵀ / √d_k + M_c) · X̂WiV

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.

Every matmul below, in one formula
C [M × P] = A [M × K] · B [K × P]
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:

LevelWhat it ownsData lives inReuse
Gridone CTA (thread block) per BM × BN tile of C: ⌈M/BM⌉·⌈P/BN⌉ CTAsDRAM, L2CTAs that run together share A row panels and B column panels in L2
CTA main loopfor k₀ = 0, BK, 2·BK, … < K: copy A[BM × BK] and B[BK × BN], accumulateshared memory, an S-stage ring filled by cp.asynceach copied element is used BN (or BM) times: tile AI = 2·BM·BN / (b·(BM + BN))
Warpa WM × WN part of the CTA tileregisters (fragments loaded with ldmatrix)each fragment feeds WN/8 (or WM/16) MMAs
Instructionmma.sync m16n8k16: [16 × 16]·[16 × 8] FP16 → FP32Tensor Cores(WM/16)·(WN/8)·(BK/16) MMAs per warp per K step
EpilogueD = f(α·acc + β·C), stored onceregisters → DRAMbias, GELU, residual add at no extra DRAM traffic

Reference config, B = 1, N = 4,096, FP16, AGX Orin (16 SMs, 164 KiB shared memory per SM). Panel 2 draws 8 of the K/BK slices.

CTAs = ⌈M/BM⌉·⌈P/BN⌉
-
CTAs per SM ≈ CTAs / 16
-
K steps = K / BK
-
smem = S·(BM + BN)·BK·b
-
warps = (BM/WM)·(BN/WN)
-
MMAs per warp per K step
-
tile AI = 2·BM·BN / (b·(BM + BN))
-
tile rows used = min(M, BM) / BM
-

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.

  1. 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.
  2. Code stacks them side by side: W_Q = [W1Q | W2Q | … | WhQ], one [d × d] matrix.
  3. 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.
  4. 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].
  5. Same parameters: h·d·d_k = d². The only difference is one large GEMM instead of h small ones, which keeps the GPU busy.
  6. 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.
✓ code = paper x̂ −1.59 0.65 1.03 −0.09 · W0Q W1Q Q 1.31 0.51 −0.54 −0.72 head 0 head 1
✗ slicing x first (not used) x̂ −1.59 0.65 1.03 −0.09 · block-diagonal W 0000 0000 Q′ 0.90 0.35 0.07 −0.08 head 0 head 1

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
Why 1/√d_k

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

What to notice: the 8 keys' scaled scores are fixed; without the 1/√d_k factor they are √d_k times larger. The largest weight climbs from 0.49 (d_k = 4) to 0.96 (64) to 1.00 (512) unscaled, and stays 0.29 scaled.

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
Worked: one query, 4 keys in 2 tiles. Scores [1, 3 | 2, 5], values [10, 20 | 30, 40].
aftermα = e^(m_old − m)placcacc / l
start−∞––00–

What to notice: when tile 2 raises the max from 3 to 5, everything accumulated so far is scaled by α = e⁻² instead of being recomputed, like renormalising a block-floating-point mantissa. The answer is exact.

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
Worked example: one head, 3 tokens, d_k = 4

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
20°
1.5
keyq·kscoreexpweight

What to notice: the dot product measures alignment; the query's length r acts as an inverse temperature (r = 0 gives a plain average); the output (green) never leaves the dashed triangle of the values. A dashed query arrow means r > 1.6.

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.
Unfused attention on-chip SRAM DRAM N × N scores FlashAttention on-chip SRAM tile DRAM Q, K, V, O

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

K_cache[ℓ], V_cache[ℓ] : [B, n_kv, N, d_k] → bytes = 2·L·B·N·n_kv·d_k·b

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

Sum of blocks 3, 5, 8, 9, 11 (B = 1, d_ff = 4d, n_kv = h)
6Nd² (QKV) + 2N²d (Q·Kᵀ) + 2N²d (A·V) + 2Nd² (W_O) + 16Nd² (FFN) = 24·N·d² + 4·N²·d

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.

QKV
-
6·B·N·d²
Q·Kᵀ + A·V
-
4·B·N²·d
W_O
-
2·B·N·d²
FFN
-
4·B·N·d·d_ff
Per layer
-
matmuls only
Prefill total
-
L × layer + 2·B·d·V
TTFT ≥ (AGX Orin)
-
total ÷ 42.5 TFLOPS
Scores, one layer
-
B·h·N²·2 B (unfused)
QKV 6BNd²
-
Q·Kᵀ 2BN²d
-
softmax 5BhN²
-
A·V 2BN²d
-
W_O 2BNd²
-
FFN 4BNd·d_ff
-

2.6 TTFT: why prefill is compute-bound

TTFT ≈ prefill FLOPs ÷ achievable FLOP/s (when B·N rows ≫ ridge)

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.

NPrefill FLOPsAttention shareFLOPs ÷ peakWeights ÷ BWGEMM AIBound
1281.66 T0.5%39 ms65 ms120memory
5126.73 T2.0%158 ms65 ms410compute
1,02413.74 T4.0%323 ms65 ms683compute
2,04828.59 T7.7%673 ms65 ms1,024compute
4,09661.57 T14.3%1,449 ms65 ms1,365compute
8,192140.74 T25.0%3,311 ms65 ms1,638compute

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)

OpFLOPsBytes (unfused)AIFLOPs ÷ peakBytes ÷ BWBound
LN₁, LN₂ (each)117 M64 MiB1.750.00 ms0.33 msmemory
QKV412.32 G224 MiB1,7559.70 ms1.15 mscompute
Q·Kᵀ137.44 G1.06 GiB1203.23 ms5.57 msmemory
scale + mask0.54 G2.00 GiB0.250.01 ms10.49 msmemory
softmax2.68 G2.00 GiB1.250.06 ms10.49 msmemory
A·V137.44 G1.06 GiB1203.23 ms5.57 msmemory
FlashAttention (replaces the 4 rows above)278.10 G128 MiB2,0726.54 ms0.66 mscompute
merge copy064 MiB–00.33 msmemory
W_O137.44 G96 MiB1,3653.23 ms0.49 mscompute
residual add (each)16.78 M96 MiB0.170.00 ms0.49 msmemory
FFN W₁, W₂ (each)549.76 G288 MiB1,82012.94 ms1.47 mscompute
GELU–256 MiB––1.31 msmemory
Layer, unfused attention1.92 T + 3.49 G74.2 ms
Layer, FlashAttention1.92 T + 3.49 G48.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

#EquationShape
1x = 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]
4q → [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–6s = q · K_cᵀ / √d_k (no mask)[B, h, 1, d_k]·[B, n_kv, d_k, t] → [B, h, 1, t]
7–8o = softmax(s) · V_c[B, h, 1, t]·[B, n_kv, t, d_k] → [B, h, 1, d_k]
9–11x ← x + merge(o)·W_O; x ← x + FFN(LN₂(x))[B, 1, d]
12z = 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/token ≈ 2·params + 4·L·t·d   ·   bytes/step ≈ b·params + B·2·L·n_kv·d_k·t·b

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)FLOPsWeight bytesKV bytes
QKV100.66 M96 MiB–
q·K_cᵀ33.55 M–32 MiB
softmax·V_c33.55 M–32 MiB
W_O33.55 M32 MiB–
FFN W₁, W₂ (each)134.22 M128 MiB–
LM head E (once)411.71 M393 MiB–
position table P (once; counted whole, as in the primer)016 MiB–
Step: 32 layers + once13.30 + 2.15 = 15.44 G13.31 GB2.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)WeightsKV cacheBytes/stepTPOT ≥tok/s ≤
FP16 weights, MHA (reference)13.31 GB2.15 GB15.46 GB75.5 ms13.2
INT8 weights6.66 GB2.15 GB8.80 GB43.0 ms23.3
INT4 weights3.33 GB2.15 GB5.48 GB26.7 ms37.4
INT4 + GQA (n_kv = 8)2.93 GB0.54 GB3.46 GB16.9 ms59.1
INT4 + GQA-8 + INT8 KV cache2.93 GB0.27 GB3.19 GB15.6 ms64.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.

AttentionBBytes/stepAITPOT ≥tok/s, all BWeights + cache
MHA115.46 GB1.075.5 ms1315.5 GB
MHA830.49 GB4.1148.9 ms5430.5 GB
MHA1647.67 GB5.2232.8 ms6947.7 GB
MHA3282.03 GB6.0400.6 ms8082.0 GB: does not fit
GQA-8112.24 GB1.159.8 ms1712.2 GB
GQA-8816.00 GB6.978.1 ms10216.0 GB
GQA-83228.88 GB15.3141.0 ms22728.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.

Variantn_kvKV per tokenKV at t = 4,096Attention AI
MHA (reference)32512 KiB2,048 MiB1
GQA (Llama 3 8B style)8128 KiB512 MiB4
MQA116 KiB64 MiB32
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?”

prefill “Apple” step 1 “is” step 2 “in” step 3 “general” step 15 EOS 1 2 3

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.”
StepInputtScores q·K_cᵀOutput
prefill5 prompt tokens5[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)
Inputids [B, N]1 id per sequence, [B, 1]
GEMM rows MB·NB
AttentionQ [B,h,N,d_k] vs K [B,n_kv,N,d_k], causal maskq [B,h,1,d_k] vs cache [B,n_kv,t,d_k], no mask
KV cachewrites N rows per layerreads t rows, appends 1
FLOPsL·(24·N·d² + 4·N²·d) + 2·d·V2·params + 4·L·t·d per token
Bytesweights once + activations (+ the N × N scores if unfused)weights + whole cache, every step
AI of weight GEMMsM / (1 + 2M/d), M = B·N≈ B
Boundcompute (B·N ≳ 231)memory bandwidth
MetricTTFT ≈ FLOPs ÷ FLOP/sTPOT ≈ bytes ÷ bandwidth
Reference, B = 1, N = t = 4,09661.57 TFLOP, AI 1,365 → TTFT ≥ 1.45 s15.44 GFLOP, 15.46 GB, AI 1.0 → TPOT ≥ 75.5 ms
HelpsFlashAttention, fused GEMM epilogues, INT8 compute, chunked prefill, prefix cachingweight-only INT4/INT8, GQA/MQA, KV quantization, batching, paged KV, speculative decoding, CUDA graphs
Does not helpweight-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.

Where does one d × d GEMM with M rows land?
1
Arithmetic intensity
-
Attainable
-
Decode ceiling, weights only
-

What to notice: moving M from 1 to 4,096 slides the dot from the sloped memory roof onto the flat compute roof. INT4 weights move the dot right at the same M: fewer bytes per FLOP, which is why weight-only quantization speeds up decode although the maths still runs in FP16. The ceiling ignores the cache read; with 2.15 GB of cache at t = 4,096 the reference model drops from 15.4 to 13.2 tok/s (§3.3).

5 Memory: weights, KV cache, activations

ItemFormulaLivesReference (B = 1, N = t = 4,096, FP16)
Weightsb·paramsalways13.31 GB (12.4 GiB); INT8 6.66 GB; INT4 3.33 GB
KV cache2·L·n_kv·d_k·b per token, × t × Bfor the whole request512 KiB/token; 2 GiB at t = 4,096
Prefill: X, and LN outputsB·N·d·bone layer at a time32 MiB each
Prefill: Q | K | V3·B·N·d·bone layer96 MiB
Prefill: scores S (and A), unfusedB·h·N²·bone layer1 GiB each
Prefill: FFN hiddenB·N·d_ff·bone layer128 MiB
Prefill: logits, all rows vs last rowB·N·V·b vs B·V·bonce392.6 MiB vs 98.2 KiB
Decode: x, scoresB·d·b, B·h·t·bone layer8 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).

Maths card: KV-cache size
KV bytes = 2 · L · n_kv · d_k · b · t · B

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 = 1Weights + cacheAGX Orin 64 GBOrin Nano Super 8 GB
FP16, MHA15.46 GB24%193%: does not fit
INT4 weights, MHA5.48 GB9%68%
INT4 weights, GQA-83.46 GB5%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.

TechniqueCutsPrefillDecodeHereCookbook
Fused QKV GEMMlaunches, input reads✓✓block 3
FlashAttentionN × N bytes and memory✓✓–blocks 5–8d
Fused add + norm, GEMM epilogues (GELU, bias, residual)elementwise bytes✓✓below, CUTLASSh
CUDA graphsCPU launch overhead–✓h
Weight-only INT8 / INT4weight bytes–✓✓belowc
INT8 weights and activations (W8A8)FLOP time and bytes✓✓belowc
GQA / MQAKV bytes and memorysmall✓✓§3.5b
KV-cache quantization (INT8)KV bytes and memory–✓§3.3a
Batching, continuous batchingweight bytes per token–✓ (throughput)§3.4e
Paged KVwasted cache memory–✓ (capacity)§3.6e
Prefix cachingrepeated prefill✓✓–f
Speculative decodingweight reads per token–✓§3.6g

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
  • 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
PyTorch ONNX TRT parser Optimize Auto-tune Engine

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.

ComponentThis guideModern LLMs (as of 2026)WhyNext seen in
Norm positionpre-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” normthe residual path stays a plain sum, so deep stacks train without warm-up tricksprimer, paper order; ViT
Norm typeLayerNormRMSNorm: no mean, divide by √mean(x²)cheaper, same qualityMamba, VLM language models
Positionslearned vectors added to xRoPE: rotate each pair of q and k dimensions by an angle proportional to the position, so q·k depends only on the offsetrelative positions, longer contextsVLM, Mamba hybrids
FFNGELU MLPSwiGLU: silu(xW_g) ⊙ (xW_u), then W_d; a learned gatebetter quality at equal parametersVLM, MoE
K/V headsn_kv = hGQA / 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/Vsame sequence (self-attention)+ cross-attention: Q from one sequence, K/V from anothercondition on image, camera or text featuresdiffusion, BEV, VLA, robot models
text tokens → Q image patches → K, V scores [4, 6] no causal mask

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.

Which transformer is this?

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.

FamilyWho sees whomExamplesWhere you'll meet it
Decoder-only (this guide)causal: token i sees tokens 0…iGPT-2/3, Llama, Qwenhere; the language model inside VLMs and VLAs
Encoder-onlybidirectional: every token sees every tokenBERT, ViTViT (Module 2), VLM vision encoders
Encoder–decoder (the 2017 paper)bidirectional encoder + causal decoder + cross-attentionoriginal Transformer, T5, Whispercross-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)
Python — transformer.py Copy code
"""
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()
Run the code
# 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

Build it yourself: the labs

Self-checking scripts that rebuild this guide's pieces (labs/index.html). Do them in order.

  1. labs/lab01.html: scaled dot-product attention with a causal mask, the head split and merge, multi-head attention (§2.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).
  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.

10 References

Videos

Papers

PyTorch and NVIDIA