Module 3 · Lesson 5 of 5

Prefill, decode and evidence

Use what changes between phases—row reuse and KV reads—to form workload-specific hypotheses.

Prefill and decode change matrix shapes

For one projection, flatten the tokens processed in this step into rrows rows. Prefill may contribute many supplied token rows. Ordinary decode usually contributes one row per active sequence, because its next token is not known yet (see the dependencies concept below). More rows can reuse the same weights across more useful work.

Active sequences are the separate requests processed together in this step (the batch). A prefill chunk is the group of supplied tokens processed per sequence in this step. Equal-length prefill chunks give rows = active sequences × chunk tokens; ordinary decode contributes one row per active sequence. The chunk control applies only to prefill. These are projection rows, not the number of cached positions read by attention.

Change phase, batch and chunk length

One 4096×4096 projection with two-byte elements: one decode sequence gives r=1, while prefill with one 512-token chunk gives r=512. Batch 512 ordinary decode also gives r=512 for this projection, although its attention and scheduling costs differ. Neither phase name determines its bottleneck.

Whole-model decode: bytes per step, and what they cost

One decode step produces one new token for each active sequence, and it must pass through every layer. To do that the GPU reads all the model’s weights from HBM once, plus each sequence’s own KV cache. Small-batch decode therefore streams a very large number of weight bytes for very little arithmetic. Reading bytes cannot go faster than the memory bandwidth, so:

step time ≥ (weight bytes + KV bytes) / BW

Worked example (invented model and device, not a measurement). A 7-billion-parameter model stored at 2 bytes per parameter has 7×10⁹ × 2 = 14 GB of weights. On a device with 3 TB/s of bandwidth (the same scale as the H100’s, lesson 3.2), 14 GB ÷ 3 TB/s ≈ 4.67 ms, so even before attention that is at most about 214 steps per second for one sequence. Add the KV cache of one sequence with 4,096 positions (32 layers, 8 KV heads, width 128, 2 bytes: 0.54 GB, from the next concept’s formula) and the bound is 4.85 ms, about 206 tokens per second. This is a floor from byte counts alone; real steps are slower.

Now batch: the 14 GB is read once however many sequences are active, so more sequences make more tokens per step for nearly the same weight cost. The KV bytes do not share: every sequence has its own cache. Change the batch below and watch the weights’ share of the bytes fall.

Bytes per decode step

Invented 7B model, 3 TB/s device. One sequence at 4,096 positions: 14 GB weights + 0.54 GB KV ≈ 4.85 ms per step, about 206 tokens/s. 32 sequences: 14 GB + 17.18 GB ≈ 10.39 ms per step, about 3,079 tokens/s across the batch. The step takes 2.1× longer but makes 32 tokens instead of 1, so about 15× more tokens per second.

The shape argument, not a universal rule

Ragged batches (sequences with different processed lengths) sum the actual token rows. The projection uses the same optimistic one-read traffic model and dense FLOP convention as 3.4.

Attention has a different shape. For a full causal prefill with T positions and no earlier cache, each query position sees its prefix. Allowed query–key pairs per head total T(T + 1)/2. For three positions in “The sky is”, that is 1 + 2 + 3 = 6 pairs. One decode query over three visible positions has only 3 pairs per head. QK plus weighted-V work is about 4D FLOPs per query–key pair per head (2D for the query–key dot product, 2D for the weighted value sum), excluding normalization. Some implementations execute masked work too; the pair count alone does not establish actual instruction count.

For a prefill chunk, count its query rows against both earlier cached positions and its own causal prefix. Longer context can change attention cost even when the projection row count is fixed. This explorer models projection reuse only; the next concept isolates decode KV reads.

A long prefill projection often has enough rows to reuse weights efficiently. Short prefill, poor shapes, quantization, cache residency, large decode batches, speculative decoding, fused kernels and hardware choice can change the balance.

Predict: Batch decode until this projection has 512 rows. Still necessarily bandwidth-bound?

Parallelism must respect dependencies

In “The sky is”, prefill has three supplied token rows, so one layer can project all three at once. Within one layer, many projections and output elements can run in parallel. The next layer still needs the previous layer’s outputs. During ordinary autoregressive decode, the next input token is unknown until the current step selects it, so a sequence adds only one new row per step. Running more sequences at once is how a server gets more rows.

Known inputs → projection gridMany independent dot products across rows and columns.
Attention and remaining layer workDependencies within the layer still apply. Causal masking prevents future-token information flow.
Next layer → logits → selectionOnly after selection can the new token become the next input.

These are data dependencies, not a GPU scheduling trace. A transformer head is not an SM, a token is not a thread, and one layer is not necessarily one kernel.

Cached does not mean free to read

KV caching avoids recomputing earlier representations. Dense decode attention still reads keys and values for the context. Longer context and more sequences increase that read demand. Grouped-query attention (GQA) lets several query heads share one key/value head (HKV smaller than Hq), which shrinks the stored and read KV payload, while each query head still needs its own scores and outputs.

The key result. Per layer, decode attention does 4NTHqD FLOPs and reads 2NTHKVDB bytes. Divide them and N, T and D cancel:

KV-read intensity = 2Hq / (HKV B) FLOP/byte. Example: 2·32 / (8·2) = 4.

It does not depend on the batch size or the context length. So batching amortizes the weight reads (one read serves every sequence) but not the KV reads (each sequence reads its own cache): KV traffic grows with every sequence while intensity stays at about 4 FLOP/byte, far below any real ridge, so decode attention remains bandwidth-bound. Only fewer KV heads or smaller stored elements raise it.

Real ridges are higher than this lab’s hypothetical 100 FLOP/byte. NVIDIA lists about 1,000 dense BF16 TFLOP/s for the H100 SXM5 (preliminary table; the product page gives 1,979 with sparsity) against 3.35 TB/s of HBM3, a ridge of roughly 300 FLOP/byte (derived: 1,000 ÷ 3.35). A 4096×4096 projection then needs on the order of 350 rows to cross it, not 512 (derived), and 4 FLOP/byte stays far below it.

Visible positions are the context positions this query can attend to, including the current consumed position in this model. Read payload counts K/V bytes consumed this step; append counts the new K/V row written to the cache. They are separate quantities.

The explorer assumes perfect reuse of each KV head’s data across its query heads. “KV-read-only intensity” is QK plus weighted-V work divided by just that KV read payload, not the intensity of the whole attention operation. Capacity measures stored bytes; traffic measures bytes read or written during a step.

Count one layer’s decode attention

For one sequence, 4096 cached positions, 32 query heads, 8 KV heads and width 128: raw K+V reads = 2×4096×8×128×2 = 16,777,216 bytes (16 MiB). QK plus weighted-V work ≈ 4×4096×32×128 = 67,108,864 FLOPs; optimistic KV-read-only intensity = 4 FLOP/byte.

Accounting contract

For N sequences of T visible positions, Hq query heads, HKV KV heads and width D, count 4NTHqD FLOPs for QK and weighted V. This excludes softmax, scaling and other attention operations. Read payload = 2NTHKVDB bytes at the selected storage precision. Count current K/V append separately: 2NHKVDB.

From understanding to an original question

Choose a narrow mechanism, predict a change, then gather evidence that could reject it. “Make inference faster” is too broad; “does the KV-head layout cause redundant memory reads for this shape?” can become an experiment.

A CPU/Mac-friendly investigation

  1. Pick one projection shape and one decode-attention configuration from the explorers. Write all dimensions and units.
  2. Predict separately what happens when you double batch, double context, or reduce KV heads. Say which operation should change and why.
  3. Use the tiny scalar product from 3.3 as a correctness reference. Check that your alternative returns the same output before discussing speed.
  4. Record assumptions and expected outcomes. Mark hardware results “not measured” until a real device run exists.
When GPU access becomes available

Record GPU model, precision, kernel/library versions, exact shapes, batch, context, warmup and cache policy. Synchronize device work or use device timing events; asynchronous host dispatch time is not kernel time. Repeat runs and report variation. Compare outputs with a stated tolerance, then inspect achieved throughput, DRAM bytes/bandwidth and launch overhead with a profiler. Do not infer traffic solely from tensor size.

Example hypothesis: increasing projection rows improves weight reuse until compute or another limit takes over. A failed prediction is useful evidence: look for repeated loads, poor tiling, cache effects or insufficient parallelism. No paid hardware or cloud account is needed to finish these lessons.

Predict: A simulator predicts 2× faster execution. Is an optimization verified?

Model boundaries

Labs. The 7-billion-parameter model, the 3 TB/s device and the 100 TFLOP/s, 1 TB/s roofline device are invented; the rows, bytes and FLOP counts follow from them. Projection traffic uses the optimistic read-once model from 3.4. Decode steps count byte reads only: no compute, attention kernel, launch or scheduling time, so a step bound is a floor and not a measured token latency.

KV explorer. It counts one layer, assumes perfect reuse of each KV head’s data across its query heads, and excludes queries, outputs, softmax, scores, metadata and scale factors. Some kernels use the current position’s new K/V directly. Actual DRAM traffic depends on the kernel, cache residency, layout and reuse, so the idealized payload need not equal physical reads. Multiply payloads across layers only when configurations match.

Hardware figures. The H100 ridge is derived from NVIDIA’s preliminary dense BF16 figure and its HBM3 bandwidth; the product page’s higher number includes sparsity. Full-request latency also includes attention, normalization, sampling, launch overhead, scheduling and communication.

Ready for the next subsystem: explain one projection’s shape, trace operands through memory, derive a bound, name a counterexample, and propose a falsifiable experiment. Return to the collection when ready; PagedAttention and scheduling remain later study.

Module 3 overview · Revisit KV memory

Continue to Module 4: efficient attention and memory →