Engineering notes
Attention Is All You Need: From Intuition to Implementation
A step-by-step explanation of tokens, queries, keys, values, masking, and the Transformer—with a small attention implementation you can inspect.
Updated
When I first encountered the Transformer, the diagram looked more complicated than the idea behind it. The useful starting question was simple: when a model processes one token, how can it decide which other tokens are relevant?
Attention gives it a learned way to combine information from different positions. The Transformer builds a sequence model around that operation, together with positional information, feed-forward layers, and connections that make a deep network trainable.
This guide moves from that intuition to a small implementation. You do not need to memorize the full architecture before understanding what happens inside one attention head.
Reading goal: explain what Q, K, and V do, trace the shape of an attention calculation, and understand why a decoder needs a causal mask.
1. The problem the paper addressed
Earlier sequence models often used recurrent networks. A recurrent layer carries state from one position to the next, which creates a dependency along the sequence. Attention already existed in sequence-to-sequence systems; the 2017 paper did not introduce the first attention mechanism.
Attention Is All You Need, by Vaswani and colleagues, introduced the Transformer architecture for sequence transduction without recurrence or convolution in its core sequence-processing blocks. The original model had an encoder and a decoder and was evaluated on tasks including machine translation.
The distinction matters: the original translation architecture and a modern decoder-only language model share important building blocks, but they are not identical systems.
Why parallelism changed training
During Transformer training, many positions can be processed together through matrix operations. A causal mask can prevent access to future targets while still allowing parallel computation over the supplied sequence.
Autoregressive generation is different. To produce a new response, a model typically generates a token, appends it, and uses that result to generate the next token. Parallel training does not mean that an entire unknown response is generated in one step.
2. Build a small vocabulary first
| Term | Meaning in this guide |
|---|---|
| Token | A unit produced by a tokenizer; often a word fragment, punctuation mark, or other symbol |
| Embedding | A learned vector associated with a token |
| Hidden state | A token’s representation after processing by a layer |
| Head | One attention calculation using its own projections |
| Logits | Unnormalized scores before a softmax |
| Context window | The sequence capacity supported by a particular model and configuration |
A token is not necessarily a whole word. Also, a vector’s individual coordinates do not generally correspond to simple labels such as “animal” or “past tense.” Those labels can be useful teaching analogies, but learned representations are distributed.
3. Start with token representations
Suppose a sequence contains n tokens and each representation has d_model features. We can arrange those representations in a matrix:
The model also needs information about position. The original Transformer used sinusoidal positional encodings added to the embeddings. Other architectures use different positional methods.
The result is a representation of token content together with positional information. Attention can then use learned projections to decide how information should move between positions.
4. Queries, keys, and values
For one attention head, the model projects the input into three matrices:
A useful interpretation is:
- A query describes what information a position is looking for.
- A key provides something that can be compared with that query.
- A value contains information that can contribute to the output.
These are learned numerical projections. They are not literal search questions or database keys. Training adjusts the projection weights so that the operation becomes useful for the objective.
Compare, normalize, combine
For every query, compute a dot product with the available keys. Scale those scores by the square root of the key dimension, apply any mask, then use softmax to form weights.
Each output row is a weighted combination of value vectors. The scaling helps control the magnitude of the dot products as the dimension grows.
A numerical example
Assume one query produces two scaled scores: 2 and 1. Softmax turns them into approximately 0.731 and 0.269.
These numbers are a worked example, not attention weights measured from a trained model. Their purpose is to show how a position receives a mixture of information rather than selecting exactly one other token.
5. Implement one attention calculation
The following Python example uses only the standard library. It is intentionally small and operates on lists so that the calculation stays visible. Real training uses optimized tensor operations and automatic differentiation.
Read the assertions before changing the example. They capture two useful invariants: forbidden positions receive zero weight, and each valid attention row sums to one.
This function does not implement learned projections, batching, padding masks, dropout, or gradients. It demonstrates the attention operation after Q, K, and V have already been constructed.
6. Why causal masking matters
In next-token training, the model must not use a token that appears after the position it is predicting from. Otherwise, training would expose information that is unavailable during generation.
A common tensor implementation assigns forbidden score entries negative infinity before softmax. Their resulting probability is zero. Be careful with padding: a row with no allowed keys needs explicit handling, since a softmax over only negative infinities can produce invalid values.
An encoder’s self-attention can use the full available input sequence. Decoder self-attention applies a causal constraint. In an encoder–decoder model, cross-attention uses decoder queries and encoder keys and values.
7. Put attention inside a Transformer block
Attention moves information between positions. A feed-forward network then transforms the representation at each position. Residual connections provide paths around sublayers, while normalization helps manage the scale of intermediate activations.
Multi-head attention performs several attention calculations with separate projections, concatenates their results, and applies an output projection. Heads can learn different useful patterns, but it is too simplistic to label every head permanently as “grammar,” “meaning,” or “pronoun resolution.”
| Architecture | Typical information flow | Common task shape |
|---|---|---|
| Encoder-only | Input positions can use the supplied context | Representation and classification |
| Decoder-only | Positions attend under a causal constraint | Next-token generation |
| Encoder–decoder | A decoder also attends to encoded input | Input-to-output sequence tasks |
Layer placement, normalization, activation functions, and positional methods vary across implementations. Learning the original block is a starting point, not a description of every model called a Transformer.
8. Understand training and inference separately
During next-token training, known token sequences supply the targets. The model predicts distributions over the vocabulary, and the training loss compares those predictions with the expected tokens. Optimization changes the model parameters.
During ordinary inference, those parameters stay fixed. The application selects tokens from the output distribution using a decoding strategy. Temperature and sampling affect selection; they do not teach the model new facts by updating its weights.
A key–value cache reuses previously computed keys and values during autoregressive decoding. This saves repeated work, while the stored cache consumes memory as the sequence grows. Retrieval, prompt history, and weight updates are separate mechanisms and should not all be described as “memory.”
9. What later improvements change
Several later techniques address different limitations. They are useful to distinguish because they do not solve the same problem.
Rotary positional embeddings
RoFormer describes rotary positional embeddings, commonly called RoPE. The method applies position-dependent rotations to representations used in attention, allowing relative position to affect their interaction. It is a positional method; it does not make arbitrary context lengths reliable by itself.
FlashAttention
FlashAttention reorganizes exact attention computation to reduce costly memory traffic. It is an implementation improvement, not a replacement of attention with a different semantic operation. It does not change standard dense attention’s quadratic pairwise computation into linear computation.
Grouped-query attention
Grouped-query attention, or GQA, lets groups of query heads share key and value heads. This reduces key–value storage relative to a corresponding multi-head setup and offers a useful inference tradeoff. The quality and speed of a complete model still depend on its architecture, training, and hardware.
10. Common misunderstandings
- “Attention is an explanation.” Attention weights show one internal operation. They do not automatically establish why a model produced a particular answer.
- “More context guarantees better answers.” A larger supported window provides capacity. Relevant retrieval, clear instructions, and evaluation still matter.
- “Every modern language model uses the original architecture.” Models change blocks and may use other sequence-processing designs.
- “A tutorial’s speedup applies to my machine.” Performance claims require a defined workload, implementation, hardware, and measurement method.
What I would learn next
First, run the small function and inspect how its weights change when you alter a query or key. Next, implement the same operation with a tensor library and compare its output on identical inputs. Then add learned projections, multiple heads, and a padding mask.
That sequence makes each abstraction earn its place. The large model becomes easier to understand once you can trace how a single position collects information from the rest of a sequence.