Transformer Attention Mechanism
Attention Mechanism in Transformers
Recap: Transformers and Token Embeddings
The model takes a piece of text and predicts what word comes next.
Input text is broken into tokens (usually words or sub-word pieces; for simplicity, treat as whole words).
Each token is associated with a high-dimensional vector called its embedding (e.g., 12,288 dimensions in GPT-3).
Directions in this embedding space correspond to semantic meaning — for example, a vector direction that shifts from masculine to feminine nouns.
The transformer’s job is to progressively adjust these embeddings so they encode not just the individual word but richer contextual meaning.
Purpose of Attention
Consider the word mole in these phrases:
“American shrew mole”
“one mole of carbon dioxide”
“take a biopsy of the mole”
Even though mole has different meanings, the initial embedding (a table lookup) is identical for every occurrence. The attention mechanism lets surrounding embeddings pass information into the embedding of mole, moving it toward the appropriate direction (e.g., animal, chemistry, skin lesion).
Similarly, the embedding of tower is generic. If preceded by Eiffel, it should move toward directions associated with Paris, France, steel. If preceded by miniature, it should shift away from “large, tall” directions.
Attention allows information from one embedding to influence another, enabling context-dependent refinement of meaning.
Single Head of Attention: Query, Key, Value
Queries and Keys
Each token i produces two vectors from its embedding ei:
Query vector qi: obtained by multiplying ei by a query matrix WQ. Dimension is much smaller than the embedding (e.g., 128). Conceptually, the query asks a question — “Are there adjectives near me?” – about other tokens.
Key vector ki: obtained by multiplying ei by a key matrix WK, also in the same smaller space. Keys effectively answer the queries — “I am an adjective and I am in that position.”
Both WQ and WK are tunable parameters learned from data.
Dot Products and Attention Scores
For every pair of tokens (i,j), compute the dot product qi⋅kj. A large positive value indicates that token j is highly relevant to token i (token j “attends to” token i). A small or negative value indicates irrelevance.
These scores form a grid (size: context length × context length).
Normalization via Softmax
To interpret the scores as weights that sum to 1, apply softmax along each column. This produces the attention pattern:
Q and K are matrices whose rows are query and key vectors.
dk is the dimension of the key/query space (used for numerical stability).
The softmax is applied column-wise (i.e., per token receiving information).
The resulting grid gives for each column (token being updated) a set of weights over all tokens (rows) indicating how much each should influence the update.
Masking (Causal / Masked Attention)
During training, the model simultaneously predicts every possible next token from each prefix of the input. To prevent later tokens from influencing earlier ones (which would “give away” the answer), masking is applied:
Before softmax, set all entries corresponding to future tokens (above the diagonal) to −∞.
After softmax, these entries become zero; columns remain normalized (sum to 1).
This ensures that when updating the embedding of a token, only preceding tokens (including itself) contribute. Masking is always used in GPT-style models, both during training and inference.
The attention pattern size scales as O(context2), making context length a major bottleneck.
Value Matrices and Embedding Updates
Value Vectors
A value matrix WV (also tunable) is applied to each embedding to produce a value vector vi in the same high-dimensional space as the embeddings. The value vector represents what should be added to other embeddings when this token is relevant to them.
Weighted Sum and Update
For each column (token i receiving information):
Multiply each value vector vj by the attention weight from the attention pattern for position i.
Sum all these scaled value vectors to produce a change vector Δei.
Add Δei to the original embedding ei:
The result is a refined embedding that incorporates information from relevant context tokens — e.g., the embedding of creature after absorbing “fluffy” and “blue” moves to a new region encoding a fluffy blue creature.
Value Matrix Factorization
If WV were a full D×D matrix (where D = embedding dimension, e.g., 12,288), it would contain ≈150 million parameters per head — far more than the key/query matrices (≈1.5 million each). To keep parameter counts balanced, the value map is factored into two smaller matrices:
Value down matrix (WVdown): maps from embedding space down to a smaller space (e.g., 128 dimensions).
Value up matrix (WVup): maps from that smaller space back up to the embedding space.
Combined effect: a low-rank transformation with far fewer parameters.
In practice, WVup for all heads is often concatenated into a single large output matrix for the entire multi-headed attention block. Papers typically refer only to the down-projection as the “value matrix.”
Multi‑Headed Attention
A single attention head captures one type of contextual update (e.g., adjectives modifying nouns). To capture many different relationships, a transformer block runs many heads in parallel.
Each head has its own WQ, WK, WVdown, and WVup (or output matrix contribution).
For each token, each head produces a proposed change Δei.
All changes from all heads are summed and added to the original embedding:
GPT-3 uses 96 heads per block.
This allows the model to learn many distinct types of context effects simultaneously — grammatical, semantic, topical, etc.
Parameter Count (GPT-3 Example)
Component | Dimensions | Parameters per Head |
|---|---|---|
WQ | 12,288 × 128 | 1,572,864 |
WK | 12,288 × 128 | 1,572,864 |
WVdown | 12,288 × 128 | 1,572,864 |
WVup | 128 × 12,288 | 1,572,864 |
Total per head | — | ≈ 6.3 million |
Per block (96 heads): 96×6.3M≈600 million.
Total model (96 layers): 96×600M≈57.6 billion attention parameters.
This is about one‑third of GPT-3’s total 175 billion parameters; the rest come from the multi‑layer perceptron (MLP) blocks that follow each attention block.
Cross‑Attention (Brief)
A variation called cross‑attention appears in models that process two distinct data sequences (e.g., translation: source text and target text; or audio and transcription).
The keys are computed from one dataset (e.g., source language tokens).
The queries are computed from the other dataset (e.g., target language tokens being generated).
Masking is typically not applied (no temporal order between the two sequences).
Cross‑attention otherwise follows the same QKV mechanism.
Role of Parallelism and Scale
The attention mechanism is extremely parallelizable — the dot‑product computations for all (query, key) pairs can be performed simultaneously on GPUs. This makes it feasible to scale transformers to massive sizes, and the deep learning community has repeatedly found that scale alone leads to large qualitative improvements in model performance.
While attention gets much of the spotlight, the majority of parameters in a transformer reside in the feed‑forward (MLP) blocks that sit between attention blocks, which will be covered in the next chapter.

Ask anything
We've read this whole study set, so questions about it get the best answers.