Series in the AI archive · Part 2 · Training
In the April RAG runs , Zoom spent more time retrieving evidence than the flat lexical baseline. At the serving layer there are several ways that time could accumulate. A larger prompt costs more to process, a longer answer takes more decoding steps, and a retrieve-more loop can add both calls to the model and calls to the index. To improve the system, start with the clock you want to move.
One request has two model workloads Link to heading
During prefill, the server processes the input tokens and builds their KV cache. The causal mask still applies, but positions in the known input can be processed together within a layer. Prefill provides the logits for the first output token. During decode, the server feeds each chosen token back to predict the next one. Cached keys and values avoid recomputing earlier projections. A new query in dense attention still consults the earlier positions. Prefill often makes heavy use of parallel arithmetic, while decode at small batch sizes can spend much of its time moving weights and cache data. The balance changes with hardware, context length, and batch size. FlashAttention · PagedAttention · Inference systems post
Record when the request starts and when tokens arrive. Let $t_0$ be the start time, and let $t_i$ be the time the client receives output token $i$. For a response of $N>1$ tokens, the first-token delay plus all subsequent gaps is the total model-response time observed at the client. If the transport sends chunks, measure token timestamps at the server or state that the client metric is chunk-based.
With 101 output tokens, a 0.6-second time to first token, and a mean interval of 20 milliseconds thereafter, the stream finishes in 2.6 seconds. Cutting those intervals to 10 milliseconds brings it to 1.6 seconds. Cutting first-token delay to 0.3 seconds alone brings it to 2.3 seconds. On a request with just a few output tokens, the first-token delay can dominate. Measure aggregate output tokens per second separately. A configuration that serves more tokens per second under load can still lengthen an individual request’s wait.
FlashAttention · Make the score matrix disappear from GPU main memory Link to heading
Consider one head reading 16,384 tokens. If an implementation materializes a square array of scores at two bytes per entry, that single array takes 512 MiB. A separate attention-weight array of the same size would take another 512 MiB. Yet each query only needs a weighted average of value vectors. Why write out the weights if they can be consumed before leaving the chip? FlashAttention, 2022
Worked example of the running softmax
Splitting the score matrix into tiles creates a problem. The softmax denominator for a query depends on all its visible keys. A tile cannot know its final share by looking only at itself. Online softmax carries a running maximum $m$, a denominator $\ell$, and an unnormalized weighted value vector $u$. If a new tile has scores $s_j$ and values $v_j$, set $m’$ to the maximum over the old maximum and the new scores. The previous contributions were expressed relative to $m$. Multiply them by $e^{m-m’}$ to express them relative to $m’$ before adding the new contributions. Online softmax · FlashAttention, Algorithm 1
Here is a scalar example with two keys per tile. The exponentiated scores are $(1,3)$ in the first tile and $(4,8)$ in the second. Their values are $(2,6)$ and $(10,14)$.
| After reading | Scale used | Denominator $\ell$ | Weighted value sum $u$ |
|---|---|---|---|
| First tile | Divide by 3 | $4/3$ | $20/3$ |
| Both tiles | Divide by 8 | $16/8=2$ | $172/8=21.5$ |
When the maximum rises from $\log 3$ to $\log 8$, multiply the first row’s state by $3/8$ before adding the second tile. The final result is $21.5/2=10.75$, the same result as summing the full row in exact arithmetic. Floating-point kernels can differ slightly through rounding and accumulation order.
The milestone was moving fewer bytes. Tiling and fusion avoid writing the full score or probability matrix to GPU main memory. Kernels may still write partial outputs or row statistics, depending on how they schedule the tiles. Dense attention still computes the interactions allowed by the mask and has quadratic arithmetic in the sequence length. Sparse attention changes which interactions are computed, and PagedAttention changes the layout of the persistent inference cache. All three address different bottlenecks. FlashAttention · FlashAttention-2 · PagedAttention · Part 1
Follow the bottleneck before choosing an optimization Link to heading
| Technique | What it changes | What I would measure |
|---|---|---|
| FlashAttention | Tiles exact attention so intermediate data moves less between levels of GPU memory. | Time and peak memory for prefill across input lengths. Dao et al. |
| Paged KV cache and continuous batching | Cache blocks reduce allocation waste. Scheduling can admit new requests as others finish rather than waiting for a whole batch. | Tail latency and served tokens per second at fixed offered load. Kwon et al. |
| Weight quantization | Stores weights at lower precision, which can reduce weight memory and bandwidth. | Accuracy on the intended tasks, weight footprint, and speed with the actual kernel. GPTQ |
| Speculative decoding | A draft proposes a block of tokens and the target verifies the block. The acceptance and correction procedure can preserve the target distribution. | Accepted draft tokens per target step and end-to-end speed at fixed sampling settings. Leviathan et al. |
Take the one-sequence example from Part 1 . At 128 KiB per cached token, an 8,192-token prefix has a 1 GiB KV payload. Sixteen such sequences need 16 GiB of payload if they share no prefix and all remain resident. That calculation excludes model weights, activations, and allocator overhead. Paged allocation can avoid reserving the full maximum for every sequence in advance. The bytes associated with live tokens still matter, and longer requests can consume capacity that would otherwise serve more users. PagedAttention
Faster generation and more reasoning buy different things Link to heading
Speculative decoding can make a given target distribution cheaper to sample. Test-time search can change the answer by asking the model for another candidate or using a verifier to choose among candidates. Snell and colleagues found that allocating inference-time compute based on problem difficulty helped in their math experiments. The result gives a reason to compare budget policies on the intended workload. A repository task with a weak checker can still reward the wrong patch, even when the system has time to produce dozens of candidates. Speculative decoding · Snell et al., ICLR 2025 · OpenAI’s coding benchmark audit
What I would measure next Link to heading
For the research agent, I would time queueing and prefill where the server exposes them, then record decode, retrieval, and reranking separately. I would compare a fixed one-pass evidence budget against an adaptive budget that can request a second pass. Keep the same model and question set. Plot citation support against total latency and report median and tail latency alongside the call count. If the gains come mostly from a few hard questions, a routing policy can spend the second call on those questions while giving the rest a faster path. The question then becomes how to detect missing evidence before answering.
Part 4 follows that decision out of the model server and into the harness.