Pidoku

Tracing One Request Through a Model

Module 11 Lesson 11.a 1h 15m Difficulty 2/5

Prerequisites 10.i, 2.f, 4.e


Before you start: words you need#

WordPlain meaning
Forward passOne run of the model from input tokens to output scores. Inference is a loop of forward passes (2.b).
OperatorOne named step in the model, such as a matrix multiply, a normalisation or a softmax.
KernelThe actual GPU program that carries out one operator (or several fused together).
PrefillThe first forward pass, which reads the whole prompt at once.
DecodeEvery later forward pass, each producing one new token per request.
KV cacheThe keys and values of earlier tokens, kept in GPU memory so they are not recomputed (12.e).
Memory boundLimited by how fast bytes arrive from memory, not by how fast the chip can do arithmetic (2.e).
BF16A 2-byte number format; most open models ship their weights in it (10.k).

1. What is it?#

A step-by-step account of what one request costs inside the model: every operator, in order, with the real shapes, the arithmetic it does and the bytes it moves.

The example is Qwen3-8B, a current open dense model, in BF16 on one H100. All sizes come from its config.json on Hugging Face:

num_hidden_layers     36        hidden_size          4096
num_attention_heads   32        num_key_value_heads  8
head_dim              128       intermediate_size    12288
vocab_size            151936    tie_word_embeddings  false

That works out to 8.2 billion parameters, or 16.4 GB of weights in BF16.

The parts of a request that happen outside the model (HTTP, the scheduler, streaming text back) have their own lessons: the request map in 12.a and 16.c, tokenisation in 12.b, sampling in 12.o, streaming in 12.p. This lesson stays inside the forward pass.

Facts checked on 12 November 2026.


2. Why does it matter?#

Most performance problems are found by knowing where in this sequence time goes. A profiler timeline (22.h) is a list of a few hundred kernels per step. If you know the trace, you can read it: “that 200 MB kernel is the gate-and-up projection; that tiny one is the norm”. If you don’t, it is noise.

The trace also shows the two facts the rest of the material builds on:

  • Decode reads every weight for every token. That makes it memory bound.
  • Prefill reads the weights once for the whole prompt. For long prompts that makes it compute bound.

3. Simple analogy#

A parcel’s journey. “Delivery takes three days” tells you nothing about a delay. Knowing the legs does: collection, sorting hub, line haul, local depot, doorstep. Then a delay has a location, and each location has its own fix.

The legs of a forward pass are the operators. The fix for a slow norm (fusion, 11.h) is different from the fix for a slow matrix multiply (batching or quantization, 11.c).


4. Tiny example: count the work#

This program walks one layer of Qwen3-8B, operator by operator, and adds up the arithmetic (FLOPs) and the bytes read and written. Then it puts the totals against the H100’s two limits: 989 TFLOP/s of BF16 tensor-core compute and 3.35 TB/s of memory bandwidth.

Go
// trace.go — count the work in one forward pass of Qwen3-8B, operator by operator.
// Numbers come from the model's config.json; the GPU is an H100 SXM.
package main

import "fmt"

const (
	layers  = 36
	d       = 4096   // hidden_size
	heads   = 32     // num_attention_heads
	kvHeads = 8      // num_key_value_heads
	headDim = 128    // head_dim
	ffn     = 12288  // intermediate_size
	vocab   = 151936 // vocab_size
	bytesW  = 2.0    // BF16

	peakFLOPs = 989e12 // dense BF16 tensor-core peak
	bandwidth = 3.35e12
)

type op struct {
	name         string
	flops, bytes float64
}

// oneLayer lists the work for S new tokens attending over ctx earlier tokens.
func oneLayer(S, ctx float64) []op {
	qkvOut := float64((heads + 2*kvHeads) * headDim) // 6144
	kvPerTok := float64(2*kvHeads*headDim) * bytesW  // K and V, one layer
	gemm := func(name string, k, n float64) op {
		return op{name, 2 * S * k * n, k*n*bytesW + S*(k+n)*bytesW}
	}
	// Each new token attends to ctx earlier tokens plus the new ones up to itself.
	pairs := S*ctx + S*(S+1)/2
	return []op{
		{"rmsnorm", 4 * S * d, 2 * S * d * bytesW},
		gemm("qkv_proj", d, qkvOut),
		{"q/k norm + rope", 10 * S * qkvOut, 2 * S * qkvOut * bytesW},
		{"kv cache write", 0, S * kvPerTok},
		{"attention", 4 * float64(heads*headDim) * pairs, (ctx + S) * kvPerTok},
		gemm("o_proj", d, d),
		{"residual add", S * d, 3 * S * d * bytesW},
		{"rmsnorm", 4 * S * d, 2 * S * d * bytesW},
		gemm("gate_up_proj", d, 2*ffn),
		{"silu * up", 3 * S * ffn, 3 * S * ffn * bytesW},
		gemm("down_proj", ffn, d),
		{"residual add", S * d, 3 * S * d * bytesW},
	}
}

func pass(label string, S, ctx float64, show bool) {
	var F, B float64
	if show {
		fmt.Printf("%s: one layer\n", label)
	}
	for _, o := range oneLayer(S, ctx) {
		if show {
			fmt.Printf("  %-16s %9.3f GFLOP %9.2f MB\n", o.name, o.flops/1e9, o.bytes/1e6)
		}
		F += o.flops
		B += o.bytes
	}
	F, B = F*layers, B*layers
	// Final norm and LM head, for the LAST position only.
	F += 2 * d * vocab
	B += d * vocab * bytesW
	tc, tm := F/peakFLOPs, B/bandwidth
	bound := "memory"
	if tc > tm {
		bound = "compute"
	}
	fmt.Printf("%-24s %8.1f GFLOP %6.2f GB  compute %6.2f ms  memory %5.2f ms  -> %s bound\n",
		label, F/1e9, B/1e9, tc*1e3, tm*1e3, bound)
}

func main() {
	pass("decode, 1 token, ctx 500", 1, 500, true)
	fmt.Println()
	pass("prefill 7 tokens", 7, 0, false)
	pass("prefill 300 tokens", 300, 0, false)
	pass("prefill 2,000 tokens", 2000, 0, false)
	pass("decode, 1 token, ctx 32k", 1, 32000, false)
}

Output:

decode, 1 token, ctx 500: one layer
  rmsnorm              0.000 GFLOP      0.02 MB
  qkv_proj             0.050 GFLOP     50.35 MB
  q/k norm + rope      0.000 GFLOP      0.02 MB
  kv cache write       0.000 GFLOP      0.00 MB
  attention            0.008 GFLOP      2.05 MB
  o_proj               0.034 GFLOP     33.57 MB
  residual add         0.000 GFLOP      0.02 MB
  rmsnorm              0.000 GFLOP      0.02 MB
  gate_up_proj         0.201 GFLOP    201.38 MB
  silu * up            0.000 GFLOP      0.07 MB
  down_proj            0.101 GFLOP    100.70 MB
  residual add         0.000 GFLOP      0.02 MB
decode, 1 token, ctx 500     15.4 GFLOP  15.22 GB  compute   0.02 ms  memory  4.54 ms  -> memory bound

prefill 7 tokens             98.5 GFLOP  15.22 GB  compute   0.10 ms  memory  4.54 ms  -> memory bound
prefill 300 tokens         4196.8 GFLOP  18.54 GB  compute   4.24 ms  memory  5.54 ms  -> memory bound
prefill 2,000 tokens      28974.6 GFLOP  37.84 GB  compute  29.30 ms  memory 11.30 ms  -> compute bound
decode, 1 token, ctx 32k     34.0 GFLOP  19.87 GB  compute   0.03 ms  memory  5.93 ms  -> memory bound

Read the per-layer table first. Four matrix multiplies carry almost all the bytes: 386 MB of weights per layer, 13.9 GB across 36 layers, plus 1.2 GB for the LM head. Everything else is kilobytes. Then the summary: a decode step does 15 GFLOP of work but has to move 15 GB, so the compute units are busy for 0.02 ms of a 4.5 ms step. That is “memory bound” in one line.

The numbers are a model, not a measurement. Real kernels reach perhaps 80–90% of peak bandwidth and 60–80% of peak FLOPs, so real times are somewhat longer. The shape of the answer is what transfers.


5. Technical explanation: the trace, step by step#

Step 0: before the GPU#

The server parses the request, applies the chat template, tokenises the text (12.b) and puts the request in the scheduler’s queue. The scheduler decides when it runs and reserves KV cache space for it (12.j, 12.l). Under load, waiting in this queue is usually the largest part of time to first token; the forward pass itself is milliseconds.

Step 1: prefill, the first forward pass#

The prompt’s token ids (a few bytes each) are copied to the GPU. Then:

1.  Embedding lookup: one row of the (151936, 4096) table per token     x: (S, 4096)

2.  For each of 36 layers:
      a. RMSNorm(x)                                             11.e
      b. qkv_proj: one GEMM, (S, 4096) @ (4096, 6144)           11.c
             split into q (S, 32, 128), k (S, 8, 128), v (S, 8, 128)
      c. Qwen3 normalises each q and k head (QK-norm), then applies RoPE
      d. k and v written into the KV cache: 4 KB per token per layer
      e. attention over the prompt, causal mask                 11.f
      f. o_proj: (S, 4096) @ (4096, 4096)
      g. residual add: x = x + attention output
      h. RMSNorm
      i. gate_up_proj: (S, 4096) @ (4096, 24576), one GEMM for two matrices
      j. SiLU(gate) * up                                        10.e
      k. down_proj: (S, 12288) @ (12288, 4096)
      l. residual add

3.  Final RMSNorm, then the LM head for the LAST position only:
        (1, 4096) @ (4096, 151936) → 151,936 logits

Two details in step 3 matter. The LM head is a 1.2 GB matrix, the single largest operator in the model. And it is applied only to the last prompt position, because only that position’s output is needed to choose the next token. Running it on all S positions would multiply that cost by S for nothing.

Step 2: sampling#

Temperature, top-p and the random draw (12.o) all run on the GPU and produce one token id. Copying 151,936 logits back to the CPU for every token would add a round trip per step, so engines keep it on the GPU.

Step 3: the decode loop#

For every new token, the same layer stack runs again with S = 1:

  • Every projection becomes a vector times a matrix (a GEMV, 11.c). Each weight is read once and used once.
  • Attention reads the request’s whole KV cache so far. It grows by 144 KiB per token (2 × 36 layers × 8 heads × 128 × 2 bytes; the formula is 12.f).
  • The new token’s K and V are appended.

At batch 1 each step reads about 15.2 GB, which is about 4.5 ms per token, or roughly 220 tokens per second at best, on any H100, whatever the prompt.

Step 4: after the last token#

When the model emits an end-of-sequence token or reaches max_tokens, the engine frees the request’s KV cache blocks back to the pool (12.l). Forgetting to do this when a client disconnects mid-stream is a classic capacity leak.

The shape of the costs#

flowchart LR
  T["token ids"] --> E["embedding<br/>lookup"]
  E --> L["36 x layer<br/>norm, QKV GEMM, attention,<br/>O GEMM, norm, MLP GEMMs"]
  L --> H["final norm +<br/>LM head (1.2 GB)"]
  H --> S["sample<br/>on GPU"]
  S -->|"next token"| E
  KV[("KV cache<br/>+144 KiB per token")] <--> L
  W[("weights<br/>16.4 GB, read every step")] --> L
  W --> H
  class E,L,H,S compute
  class KV,W memory
  class T neutral

6. Under the hood: what a profiler shows#

An Nsight Systems timeline (22.h) of one decode step of this model shows roughly 10–15 kernels per layer, so a few hundred per step. The biggest bars are the four GEMMs in each layer and the LM head at the end; the norms, RoPE and adds are slivers.

CPU  |--python--|--launch x ~400--|            |--python--|
GPU            |█|▌|█|▌|██|▌|█|▌|...|▌|████|
                ▲                        ▲
                first layer's GEMMs      LM head (the largest single kernel)

Each launch costs the CPU a few microseconds (5.d). A few hundred launches is about a millisecond of CPU time per token, against a 4.5 ms step. At small batch the GPU can sit idle waiting for the CPU. Capturing the step as a CUDA graph (5.f) and replaying it with one launch removes the gaps; engines do this by default for decode (13.k).


7. Performance implications#

The trace tells you which step each optimization touches:

OptimizationStep it changesLesson
Batching many requests3: turns GEMVs back into GEMMs11.c, 12.j
Quantized weights1b, 1f, 1i, 1k: fewer bytes per weight13.b
Fusing norms and activations1a, 1h, 1j: fewer passes over memory11.h
FlashAttention1e: score matrix never stored11.f, 13.l
Paged KV cache1d, 4: no fragmentation, instant free12.l
Prefix caching1: skip prefill for a shared prefix12.m
Chunked prefill1: split long prompts so decode is not blocked12.k
CUDA graphs3: one launch per step13.k
Speculative decoding3: several tokens per weight read12.n

The crossover between memory bound and compute bound for prefill sits around a few hundred prompt tokens on an H100 (the program puts it between 300 and 2,000). Below it, prefill costs about the same as one decode step. Above it, prefill time grows in step with prompt length.


8. Production implications#

  • Measure each phase separately. Queue wait, prefill time, per-token decode time and detokenise/stream time are different metrics with different fixes (22.j). When time to first token regresses, you then know which phase moved.
  • Batch size 1 decode is the floor, not the typical case. At batch 64 the same 15 GB of weights serves 64 tokens per step; each user still sees roughly the per-step time, but total throughput is about 64 times higher (12.c).
  • Long contexts move the bytes from weights to KV. At 32,000 tokens of context the KV cache adds 4.7 GB to every step of this one request, and at batch 32 it would dwarf the weights (12.f).

9. Common mistakes#

  1. Computing logits for every prompt position. Only the last one is needed for generation. Doing all S of them multiplies the LM head’s cost by S.
  2. Copying logits to the CPU to sample. A host round trip per token, for no benefit.
  3. Thinking “8B parameters” means “8 GFLOP per token”. It is about 2 FLOPs per parameter per token (multiply and add), so 15–16 GFLOP, and at batch 1 the FLOPs are not the limit anyway.
  4. Forgetting the LM head. With a 150,000-token vocabulary it is 8% of this model’s weights.
  5. Not freeing the KV cache on client disconnect. The blocks stay reserved and capacity leaks away.
  6. Trusting a back-of-envelope like section 4 to the microsecond. It predicts the shape and the order of magnitude; measure for the real number.

10. Hands-on exercise#

  1. Run trace.go. Change the model to Qwen3-32B (64 layers, hidden 5120, 64 query heads, 8 KV heads, head_dim 128, intermediate 25600, the same vocabulary) and find its decode step time at batch 1.
  2. Add a batch size B to pass: weights are read once per step, but every per-token term is multiplied by B. At what batch does decode become compute bound on an H100?
  3. Find the prompt length where prefill changes from memory bound to compute bound, to the nearest 10 tokens.
  4. With a real model on a GPU, record one decode step with nsys profile (22.h). Count the kernels and match the four largest to steps 1b, 1f, 1i and 1k.
  5. Generate text in a non-Latin script and detokenise each token on its own. Watch the broken characters, then read 12.p for how incremental detokenisation fixes it.

11. Interview questions#

  1. Walk me through every operator in one decode step of a dense transformer, with sizes.
  2. Why is the LM head applied only to the last prompt position during prefill?
  3. Roughly how many FLOPs and how many bytes does one decode token of an 8B BF16 model cost, and which one limits speed?
  4. At what prompt length does prefill become compute bound on an H100, and why?
  5. Where in the trace do prefix caching, quantization and CUDA graphs each apply?
  6. Why should sampling run on the GPU?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in