Speaker Notes

Attention in transformers, step-by-step | Deep Learning Chapter 6

A step-by-step visual breakdown of the transformer attention mechanism, explaining how queries, keys, and values dynamically update token embeddings based on context.

3Blue1Brown · 26:09 · YouTube ↗

Animated explainer · solo speaker  Intermediate · conceptual linear algebra and matrix operations

Highlights

4 clips · 6 min of 26 min
    • Initial token embeddings are context-free lookup tables where words like 'mole' share the same vector.
    • Attention allows surrounding embeddings to pass information into a token to shift its vector toward a context-specific meaning.
    • Nouns generate query vectors asking what adjectives precede them, while adjectives generate key vectors answering those queries.
    • Dot products between keys and queries compute a relevance score determining how much one word attends to another.
    • Training processes sequences by predicting tokens simultaneously across all positions.
    • Future tokens are masked with negative infinity before softmax to prevent them from leaking answers to earlier positions.
    • A full attention block uses dozens of parallel attention heads, such as 96 heads in GPT-3.
    • Each head produces a proposed change to token embeddings, which are summed together to capture multiple types of context simultaneously.

Questions this video answers

9 · every answer cites the moment it was said
01 Why do initial token embeddings fail to capture word context? 2 sources · 2:18

Initial token embeddings act like a static lookup table that assigns the exact same vector to a word regardless of its surrounding text. Attention steps in afterward to allow surrounding embeddings to pass relevant context into that specific vector.

02 How do query and key matrices work together to find relevant context? 3 sources · 6:42

Query matrices map noun embeddings to query vectors looking for preceding adjectives, while key matrices map adjective embeddings to matching key vectors. Computing dot products between these keys and queries produces a relevance score grid determining how much one word attends to another.

03 What turns raw dot product scores into an attention pattern? 2 sources · 9:17

The raw dot products can range from negative infinity to infinity, so a softmax function is applied column by column. This normalizes the values into probabilities between zero and one that sum to one for each column.

04 Why is sequence masking necessary during training? 2 sources · 11:42

Masking prevents later tokens from improperly influencing earlier ones by setting their future scores to negative infinity before softmax. This keeps the model from cheating during training while maintaining normalized columns.

05 How are value matrices used to update token embeddings? 2 sources · 13:44

Value matrices multiply token embeddings to produce value vectors, which are then scaled by the attention weights and summed together. Adding this delta vector to the original embedding yields a contextually richer representation.

06 How do models maintain efficiency in value map parameter counts? 2 sources · 16:52

Instead of using a massive square matrix that adds hundreds of millions of parameters, the value map is factored into a low-rank transformation using two smaller matrices. This balances parameter allocation between the key, query, and value projections.

07 What is the purpose of multi-headed attention? 2 sources · 20:47

Multi-headed attention runs many distinct sets of key, query, and value maps in parallel to capture multiple types of context simultaneously. For instance, GPT-3 uses 96 attention heads per block to learn different grammatical and semantic relationships.

08 How do real-world implementations handle value matrices across multiple heads? 1 source · 22:45

In practice, the value up matrices from each individual head are stapled together into a single giant output matrix for the entire block. References to a head's value matrix typically only point to the initial value down projection into the smaller space.

09 Why is the attention mechanism so heavily favored in modern deep learning hardware? 1 source · 24:54

Attention is extremely parallelizable, allowing massive numbers of computations to execute quickly on GPUs. This high parallelizability lets models leverage massive scale for qualitative performance improvements.

Section-by-section summary

6 parts

Transformers and token embeddings

Transformers process text by splitting it into tokens and mapping each to a high-dimensional vector space called an embedding. Directions in this space represent semantic features, and the network progressively updates these vectors to capture rich context.

The need for context resolution

Context-free embeddings cannot distinguish between homonyms like a mole animal versus a medical mole. Attention mechanisms solve this by letting surrounding words update an embedding to point toward a specific directional meaning.

Mechanics of queries and keys

An attention head multiplies embeddings by query and key matrices to map them into a smaller dimensional space. Dot products between these keys and queries generate relevance scores, normalized via softmax into an attention pattern.

Scaling factors and sequence masking

Attention scores are scaled by the square root of the key-query dimension for numerical stability. During training, causal masking sets future token scores to negative infinity to preserve autoregressive integrity.

Value matrices and parameter efficiency

Value matrices determine what information gets added to target embeddings based on attention weights. Factoring the value map into down and up projections significantly reduces the parameter count while maintaining expressiveness.

Multi-headed attention and hardware scaling

Running numerous attention heads in parallel allows models to learn diverse contextual relationships simultaneously. This parallelizable architecture makes transformers uniquely suited to scale efficiently on modern GPU hardware.

0:00 / 26:09
k play/pause · f fullscreen · m mute
n next · p previous clip · t highlights/full
< > slower/faster · / search what was said
  • Token embedding26× · first 0:47

    A high-dimensional vector associated with each token that encodes its initial semantic meaning and position.

  • Query matrix11× · first 6:32

    A tunable parameter matrix that maps token embeddings into a smaller space to represent what a token is looking for.

  • Key matrix5× · first 7:47

    A tunable parameter matrix that maps token embeddings into a smaller space to answer queries from other tokens.

  • Attention pattern5× · first 10:10

    A normalized grid of scores determining how relevant each word is to updating every other word.

  • Softmax3× · first 9:49

    A mathematical function used to normalize columns of dot product scores into probabilities that sum to one.

  • Masking2× · first 12:19

    The process of setting future sequence scores to negative infinity before softmax to prevent later tokens from influencing earlier ones.

  • Value matrix6× · first 13:44

    A matrix used to generate value vectors that determine the exact content added to update token embeddings.

  • Multi-headed attention5× · first 13:35

    Running multiple attention operations in parallel with distinct key, query, and value maps to learn various context types.