1. Home
  2. Explore
  3. Computer Science
  4. Transformer Attention Mechanism

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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 iii produces two vectors from its embedding eie_iei​:

  • Query vector qiq_iqi​: obtained by multiplying eie_iei​ by a query matrix WQW_QWQ​. 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 kik_iki​: obtained by multiplying eie_iei​ by a key matrix WKW_KWK​, also in the same smaller space. Keys effectively answer the queries — “I am an adjective and I am in that position.”

Both WQW_QWQ​ and WKW_KWK​ are tunable parameters learned from data.

Dot Products and Attention Scores

For every pair of tokens (i,j)(i,j)(i,j), compute the dot product qi⋅kjq_i \cdot k_jqi​⋅kj​. A large positive value indicates that token jjj is highly relevant to token iii (token jjj “attends to” token iii). A small or negative value indicates irrelevance.

These scores form a grid (size: context length ×\times× 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:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)VAttention(Q,K,V)=softmax(dk​​QKT​)V
  • QQQ and KKK are matrices whose rows are query and key vectors.

  • dkd_kdk​ 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 −∞-\infty−∞.

  • 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)O(\text{context}^2)O(context2), making context length a major bottleneck.


Value Matrices and Embedding Updates

Value Vectors

A value matrix WVW_VWV​ (also tunable) is applied to each embedding to produce a value vector viv_ivi​ 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 iii receiving information):

  • Multiply each value vector vjv_jvj​ by the attention weight from the attention pattern for position iii.

  • Sum all these scaled value vectors to produce a change vector Δei\Delta e_iΔei​.

  • Add Δei\Delta e_iΔei​ to the original embedding eie_iei​:

ei′=ei+∑jattention_weighti,j vje_i' = e_i + \sum_j \text{attention\_weight}_{i,j} \, v_jei′​=ei​+∑j​attention_weighti,j​vj​

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 WVW_VWV​ were a full D×DD \times DD×D matrix (where DDD = embedding dimension, e.g., 12,288), it would contain ≈150\approx 150≈150 million parameters per head — far more than the key/query matrices (≈1.5\approx 1.5≈1.5 million each). To keep parameter counts balanced, the value map is factored into two smaller matrices:

  1. Value down matrix (WVdownW_{V_\text{down}}WVdown​​): maps from embedding space down to a smaller space (e.g., 128 dimensions).

  2. Value up matrix (WVupW_{V_\text{up}}WVup​​): maps from that smaller space back up to the embedding space.

Combined effect: a low-rank transformation with far fewer parameters.

In practice, WVupW_{V_\text{up}}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 WQW_QWQ​, WKW_KWK​, WVdownW_{V_\text{down}}WVdown​​, and WVupW_{V_\text{up}}WVup​​ (or output matrix contribution).

  • For each token, each head produces a proposed change Δei\Delta e_iΔei​.

  • All changes from all heads are summed and added to the original embedding:

ei′=ei+∑head hΔei(h)e_i' = e_i + \sum_{\text{head } h} \Delta e_i^{(h)}ei′​=ei​+∑head h​Δei(h)​
  • 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

WQW_QWQ​

12,288 × 128

1,572,864

WKW_KWK​

12,288 × 128

1,572,864

WVdownW_{V_\text{down}}WVdown​​

12,288 × 128

1,572,864

WVupW_{V_\text{up}}WVup​​

128 × 12,288

1,572,864

Total per head

—

≈ 6.3 million

  • Per block (96 heads): 96×6.3M≈60096 \times 6.3\text{M} \approx 60096×6.3M≈600 million.

  • Total model (96 layers): 96×600M≈57.696 \times 600\text{M} \approx 57.696×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 QKVQKVQKV 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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent