Skip to content

Block 03 / 07

Attention and transformers

Attention is the data structure of context; its cost scales with window length.

A TransformerThe architecture built on self-attention (block 03). Every token attends to every other token in the window, computed in parallel rather than stepped through sequentially like an RNN. builds context by attention: each token looks at the others, mixes what it needs, and the next token is conditioned on that window. GPT, Claude, Gemini are this idea at different scale, with serving tricks around it. Naive attention is pairwise work over the window. Prefill, KV cache, and time-to-first-token follow from that data structure.

The same accounting used for indexes applies: state the complexity. Concatenating a repository into the prompt is then a resource allocation.

Figure

AttentionCostTheanimaldidn’tcrossthestreetbecauseitwastootiredlow weighttiredanimal, highest weighthigh51232K tokenslatency budgetknee
Eleven tokens, one pronoun to resolve. The word “it” sends a query to every token in the window, and the arc weights are the answer: a thick amber arc to “animal,” a moderate one to “tired,” the rest thin and muted. That is self-attention doing coreference for free, a side effect of computing which tokens matter for this one. On the right, the same mechanism priced by window length. Every token compares against every other token, so cost rises with the square of the length, gently at 512 tokens and steeply by 32K, until it crosses whatever latency or memory budget the system was given. That crossing point is the knee the lab in this block asks you to find.

Algorithms

The core operation has stayed the same since 2017: scaled dot-product, multiple heads, softmaxThe function that turns a vector of logits into a probability distribution: exponentiate each score and divide by the sum, so the outputs are positive and add to 1. over pairwise scores. What earned real estate around it is the response to a single fact, that naive attention costs quadratic work over the window. Three families answer that cost, each accepting a different tradeoff to keep it under control.

Reference

In practice

Attention is pairwise work over a window. Long context, translation, and code completion are that data structure at different scales.

Laboratory

Measure attention cost as sequence length grows

Implement scaled dot-product attention in numpy or PyTorch. Time and memory it at 512, 2K, 8K, 32K tokens (synthetic is fine). Add a sliding-window or prefix-cache variant. Plot wall time and peak memory against n. Mark the knee where lengthening the window exceeds a stated latency or memory bound.