Attention and the context window
easy 7 minSelf-attention lets a position mix information from other eligible positions.
Pack the rules, pack the evidence, leave room for the reply.
A travel case has three compartments. Instructions go in first, source cards go in next, and an empty compartment is reserved for the answer.
Video lesson · Chapter 1 of 4
A parcel with a pronoun
Theory
Read or listen first. About 2 min.
What it is
Self-attention lets a position mix information from other eligible positions. Queries score keys and the normalized scores weight the corresponding values. In a decoder, a causal mask limits each position to its available past. The context window limits which positions can exist in the first place.
Why it exists
A support assistant may lose an important exception either because it fell outside the supplied input or because the model failed to use it. Record the actual input first. Then compare performance at different evidence positions and inspect whether preserving the same facts in less text improves the answer.
How much attention can “it” give an earlier word?
Inside this chapter
Chapter sources- Anatomy of a Transformer
- A transformer block mixes information across positions through attention and transforms each position through a feed-forward network. Residual connections carry information between layers. At generation time, the final hidden representation is projected into vocabulary scores. A decoder uses a causal mask so a position cannot read later tokens.
Picture a stack of identical blocks. Attention is the only place where positions exchange information; the feed-forward layer then processes each position separately. The residual connection adds each block's input back to its output, so information and gradients can pass through dozens of layers without fading. Only the last position's final vector is turned into vocabulary scores when generating the next token.
Example. Trace three positions through a decoder block. At position two, the causal mask allows positions one and two and hides position three.
Another example. In a three-token prompt
The parcel arrived, position two (parcel) can attend toTheand itself. The mask hidesarrived, which matters during training when the whole sentence is present.One decoder block, repeated many times
Attention moves information between positions; the feed-forward network transforms each position on its own. - Self-Attention Mechanism
- Each position produces a query, a key and a value. Query–key scores determine how much each permitted value contributes to the output. Different heads learn different projections. A high attention coefficient describes one internal weighted sum; by itself it cannot establish why an entire model produced its answer.
Each position asks a question (its query) and every eligible position offers a label (its key) and a payload (its value). The dot product of query and key says how relevant that position is; softmax turns the scores into weights; the output is the weighted sum of values. Many heads do this in parallel with different learned projections, so one head might track the subject of a sentence while another tracks punctuation. A single head's weights are a narrow view and should not be read as the model's reasoning.
Example. If two eligible value vectors are (1, 0) and (0, 2), weighting them ¼ and ¾ yields (0.25, 1.5).
A weighted average of value vectors
The weights come from softmax over query-key scores and always sum to one. - Context Window & Memory
- The context window bounds the sequence a model can process. Instructions, tool schemas, conversation, retrieved text and output reservations compete for space. When an old address drops out of a conversation, the model cannot recover it from that conversation unless the application retrieves or resupplies it. Test what survives truncation.
The window is a hard ceiling on the number of positions in one forward pass, and it covers everything: system prompt, tool schemas, history, retrieved passages and the tokens the model will write. When a chat outgrows it, the application must drop or summarise something, and whatever is dropped no longer exists for the model. Test this deliberately: put a key fact early in a long conversation and check whether it survives your truncation policy.
Example. In a 4,096-token window, fixed input uses 1,000 and the response reserves 500. Evidence has 2,596 tokens before extra framing.
Another example. A booking assistant trims the oldest turns once a chat passes the limit. The customer's delivery address from turn one disappears, so the assistant should fetch it from the account record rather than ask the model to remember it.
Budgeting a 4,096-token window
Item Tokens Remaining Window 4,096 4,096 Instructions, tools, conversation 1,000 3,096 Reserved for the reply 500 2,596 Retrieved evidence up to 2,596 0 Template framing tokens come out of the evidence share too, so measure the rendered request. - Where the evidence sits
- Compare identical contexts with the supporting passage near the start, middle and end. Keep question, distractors, and total length fixed. A larger advertised context limit alone tells you little about retrieval of a particular fact at each position.
A model can accept a long input yet use some parts of it less reliably than others. To measure this, hold everything constant and move only the one passage that answers the question. Plot accuracy against position. If the middle is weak, you can reorder evidence so the most relevant passages sit near the start or end, or send less text.
Example. Move the only warranty exception from paragraph two to paragraph forty. An answer change isolates sensitivity to placement from the cost of adding more text.
A placement experiment
Only the position changes, so any accuracy gap is caused by placement, not by length or distractors. - Positional information
- Attention on its own treats its inputs as an unordered set, so the model needs position information. Some models add a learned position vector to each token embedding; many modern decoders use rotary position embeddings, which rotate queries and keys by position-dependent angles so the score depends on the distance between tokens.
Rotary embeddings are popular because the relative offset between two tokens appears directly in their query-key score. A model trained on a certain maximum length can still behave poorly beyond it, which is why extending a context window usually involves adjusting the position scheme and further training, not just raising a config value.
Example.
dog bites manandman bites dogcontain the same three tokens. Without positions, attention would compute the same mixtures for both.Same tokens, different order
Sentence Token set Without positions With positions dog bites man{dog, bites, man} identical mixtures subject is dogman bites dog{dog, bites, man} identical mixtures subject is manPosition information is what lets attention tell these apart.
How it works
Step through the idea, or press Play.
Token positions. “The parcel arrived. It …”
Understand it
Worked example
How much attention can “it” give an earlier word?
- 1
“The parcel arrived. It …”
At the position for It, the model can use earlier permitted positions. The example isolates two candidate keys to make one attention head’s calculation visible.
- 2
log 3 and log 1
After masking, assume the two allowed positions have these scaled scores. Softmax assigns weights 0.75 and 0.25. Later positions receive no causal attention here.
- 3
0.75 × 8 + 0.25 × 4 = 7
For scalar values 8 and 4, the head outputs 7. A real head combines vectors, and subsequent heads and layers can change the representation.
Scaled dot-product attention
Follow the handoffs
One head's calculation at the position for `It`
| Key position | Allowed? | Scaled score | Weight | Value | Contribution |
|---|---|---|---|---|---|
| Candidate A | yes | log 3 | 0.75 | 8 | 6 |
| Candidate B | yes | log 1 = 0 | 0.25 | 4 | 1 |
| Later tokens | no, masked | minus infinity | 0 | n/a | 0 |
| Output | 1.00 | 7 |
Summary
The whole topic in one minute.
Only positions present in the actual input or eligible cached prefix can participate. A larger attention score cannot recover omitted text.
A support assistant may lose an important exception either because it fell outside the supplied input or because the model failed to use it. Record the actual input first. Then compare performance at different evidence positions and inspect whether preserving the same facts in less text improves the answer.