research30 min studyLesson 769 in Engineering

Long-sequence cost and capacity models

Budget named KV, prefill attention work, and decode IO components while separating mathematical bounds from measured service behavior.

On this page

What you’ll understand

  • Calculate a declared KV layout using KV heads and stored element bytes.
  • Distinguish prefill pair work, decode traffic, and other model costs.
  • Use usable pool capacity and measured scheduling effects without promising hardware throughput.

Long inputs stress several resources at once: retained KV storage, prefill computation, decode memory traffic, communication, and request queueing. One token limit does not summarize those constraints. This lesson uses explicit teaching layouts together with Transformers 4.53.2 cache documentation and vLLM 0.10.1 scheduling guidance. The numerical examples describe hypothetical budgets and bandwidths, not measurements or specifications of an actual accelerator.

Name the memory that the token count consumes

For a conventional uniform KV layout, count layers, concurrent sequences, retained tokens per sequence, KV heads, head dimension, and bytes per stored element. Grouped-query attention has fewer KV heads than query heads, so substituting the query-head count can overestimate this component. Quantized caches can add scales, metadata, alignment, and residual storage. Prefix sharing and model-specific layouts change accounting further. State whether a reported capacity is total device memory or the usable KV pool after weights, workspace, reserve, and other allocations.

Generation can grow the retained history beyond the prompt, so plan output tokens and simultaneous requests as well as prefill size. An allocator’s reserved capacity differs from currently live useful KV bytes. Sharding can reduce per-device storage for some layouts but requires checking actual KV partition or replication behavior; dividing by device count is not universally valid. A lower KV representation size can also introduce quality differences. Validate exact workload behavior and the serving configuration rather than turning a byte calculation into a guarantee that every model fits.

MKV=2LBNHKVdhbM_{\mathrm{KV}}=2LBNH_{\mathrm{KV}}d_hb
For B equal-length sequences with N retained tokens each, uniform L layers, H_KV KV heads, head dimension d_h, and b bytes per element, this gives bytes for keys plus values. It excludes metadata, padding, sharing, architecture variants, other allocations, and nonuniform sequence lengths.↔ Scroll wide equations horizontally.

Prefill work and decode IO scale differently

Dense causal prefill compares each query position with its permitted prefix. Counting the QK product and value accumulation with multiply and add as two operations gives a useful ideal attention-work expression. It excludes projections, feed-forward layers, softmax, normalization, and extra kernel work. IO-aware implementations can avoid materializing the entire attention matrix and improve memory traffic, while still computing the relevant pair interactions. Sparse or sliding masks change the pair set and must use their own formula rather than inherit a full-attention estimate.

For a single full-attention decode step, retained KV may need to be read through the memory hierarchy. A stated one-read traffic model gives a movement lower bound, but real kernels can reuse or reload values, and weights or other work can dominate. Effective bandwidth is not necessarily the device’s advertised peak. Time to first token, inter-token latency, and complete request latency describe different boundaries. Include workload arrival and concurrency when measuring them; a single-request lower bound cannot establish a loaded service percentile.

Fattn≈2LBHQdhN(N+1),TKV read≥BKV trafficβeffectiveF_{\mathrm{attn}}\approx2LBH_Qd_hN(N+1),\qquad T_{\mathrm{KV\ read}}\geq\frac{B_{\mathrm{KV\ traffic}}}{\beta_{\mathrm{effective}}}
The first counts ideal causal QK and AV multiply-add work over N(N+1)/2 pairs per query head, ignoring all other operations. The second divides bytes traversing the named memory bottleneck by bytes per second to give seconds. Traffic is not automatically equal to allocated KV size; that equality needs a declared one-read assumption.↔ Scroll wide equations horizontally.

Measure scheduling and quality alongside the bounds

vLLM 0.10.1 documents chunked prefill and batching controls that trade time to first token, inter-token latency, and throughput. Those are versioned scheduler behaviors, not a theorem that one setting is optimal for every GPU and model. A long prefill can contend with existing decodes; cache pressure can trigger recomputation under a supported policy. Record preemption, cache reuse, input and output lengths, and concurrency when explaining a latency result. Also test whether a memory-saving representation changes the evidence-dependent output.

The Roofline lab illustrates only a hypothetical resource ceiling. Reset, set operational intensity to 8 and bandwidth to 80, predict the ceiling, then Step: 640 GFLOP/s. Compare a fresh Reset with both intensity at 2 and bandwidth at 80 before Step: 160 GFLOP/s. Its compute ceiling is fixed at 1000. It contains no KV layout, token sequence, attention kernel, allocator, or scheduler, so it cannot predict a real long-context service’s latency or capacity.

KV capacity and an explicitly assumed read bound

Use a hypothetical uniform model with 32 layers, eight KV heads, head dimension 128, and two-byte KV elements. Count one sequence at 32,768 and 65,536 retained tokens. Assume a usable KV-only pool of 24 GiB, then separately assume one decode reads the entire 32k KV once through a one-TiB/s bottleneck.

  1. Storage per token is 2 × 32 × 8 × 128 × 2 = 131,072 bytes, or 128 KiB. At 32,768 tokens the component is 4 GiB.

  2. At 65,536 tokens it is 8 GiB. The declared 24-GiB usable KV-only pool can hold three such equal sequences before any additional excluded overhead; it is not a total-device-memory claim.

  3. Under the separate one-read assumption, four GiB at one TiB/s gives 4/1,024 seconds, approximately 3.906 ms. Other traffic, computation, and scheduling can add time, so this is not an observed decode latency.

The result

Named memory and IO assumptions make the arithmetic reviewable without converting it into a hardware or service guarantee.

Explore the model

Interactive lab

Interactive lab · roofline

A synthetic ceiling separate from KV accounting

Reset, set I = 8 and B = 80, predict the ceiling, then Step: 640 GFLOP/s. Compare a fresh Reset with both I = 2 and B = 80 before Step: 160 GFLOP/s. The fixed 1000-GFLOP/s model does not allocate KV, execute prefill/decode, or schedule long requests.

A synthetic ceiling separate from KV accountingSynthetic roofline ceiling min(1000, B·I), in GFLOP/s, with B in decimal GB/s and I in FLOP/byte. Playback traces the roof without changing the selected kernel. This upper-bound model is not a measured throughput prediction, hardware comparison or price model. Current readings: Attainable ceiling: 640 GFLOP/s; Ridge intensity: 12.5 FLOP/byte; Ceiling regime: Memory-bound ceiling. All parameters are adjustable with the labeled controls below.Hypothetical roofline upper bound: 640 GFLOP per second at operational intensity 8 FLOP per byte and bandwidth 80 gigabytes per second.0.1110641101001000Operational intensity · FLOP/byte · log scaleCeiling · GFLOP/s · log scalePeak: 1000
Attainable ceiling / kernelBandwidth roof / traceCompute ceiling
Attainable ceiling
640 GFLOP/s
Ridge intensity
12.5 FLOP/byte
Ceiling regime
Memory-bound ceiling
t = 0 s

Synthetic roofline ceiling min(1000, B·I), in GFLOP/s, with B in decimal GB/s and I in FLOP/byte. Playback traces the roof without changing the selected kernel. This upper-bound model is not a measured throughput prediction, hardware comparison or price model. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forResource bounds help explain limits, while actual long-sequence capacity and quality require implementation measurements.

Check your understanding

A calculation says one sequence needs four GiB of KV state. What remains necessary before claiming actual device capacity or decode latency?

Try it yourself

Use 16 layers, four KV heads, head dimension 128, two-byte elements, and 32,768 retained tokens for one hypothetical sequence. Compute KV bytes in GiB. Under a separate one-read assumption at 0.5 TiB/s, calculate the movement lower bound.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Find bytes per token first, and use binary GiB and TiB consistently.

Compare with the solution

Bytes per token are 2 × 16 × 4 × 128 × 2 = 32,768. Multiplying by 32,768 yields 1,073,741,824 bytes, or one GiB. One GiB at 0.5 TiB/s is 1/512 seconds, approximately 1.953 ms. This excludes all other traffic and computation and does not establish a real decode time or account for metadata and other device storage.

Take it with you

  • KV accounting needs actual retained slots, KV heads, representation bytes, and a named pool boundary.
  • Prefill pair work, decode traffic, and service latency are different quantities.
  • Versioned scheduling measurements and quality checks are needed beyond mathematical resource bounds.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.