Angad Sandhu
Search
Browse
On this page

6.6.1 Attention Mechanisms

6.6.1 Attention Mechanisms


Key Concepts

6.6.1.1 The Attention Mechanism

Attention allows models to focus on relevant parts of the input when producing each part of the output.

Motivation: The Bottleneck Problem

In vanilla seq2seq models:

Encoder: x_1, x_2, ..., x_n --> [context vector c]
Decoder: c --> y_1, y_2, ..., y_m

Problem: All information compressed into fixed-size vector c
- Long sequences lose information
- Decoder can't focus on relevant parts

Core Idea

Instead of one context vector, compute a weighted combination of all encoder states:

For each decoder step t:
1. Compute relevance scores between decoder state and ALL encoder states
2. Convert scores to weights (softmax)
3. Weighted sum of encoder states = context for this step

     Encoder states: h_1, h_2, h_3, h_4
                      |    |    |    |
     Attention:      0.1  0.6  0.2  0.1  (weights sum to 1)
                      |    |    |    |
                      +----+----+----+
                           |
                      context_t (weighted sum)
                           |
                      Decoder step t

General Attention Formula

# Score function: how relevant is encoder state h_j to decoder state s_t?
e_{t,j} = score(s_t, h_j)

# Attention weights (softmax over all encoder positions)
alpha_{t,j} = exp(e_{t,j}) / sum_k(exp(e_{t,k}))

# Context vector (weighted sum of encoder states)
c_t = sum_j(alpha_{t,j} * h_j)

# Use context in decoder
s_t = f(s_{t-1}, y_{t-1}, c_t)

Score Functions

Different ways to compute attention scores:

NameFormulaNotes
Dot products^T @ hSimple, fast
Scaled dot product(s^T @ h) / sqrt(d)Prevents large values
General (Luong)s^T @ W @ hLearnable transformation
Additive (Bahdanau)v^T @ tanh(W_s @ s + W_h @ h)More expressive
Concatv^T @ tanh(W @ [s; h])Concatenate then transform

6.6.1.2 Self-Attention

Self-attention computes attention between positions within the SAME sequence.

Key Difference from Cross-Attention

Cross-attention (seq2seq):
- Query: decoder state
- Keys/Values: encoder states
- Attends from one sequence to another

Self-attention:
- Query, Key, Value: ALL from same sequence
- Each position attends to all positions (including itself)

Query, Key, Value Framework

Inspired by information retrieval:

  • Query (Q): What am I looking for?
  • Key (K): What do I contain?
  • Value (V): What information do I provide?
For input sequence X = [x_1, x_2, ..., x_n]:

Q = X @ W_Q  (queries)
K = X @ W_K  (keys)
V = X @ W_V  (values)

Attention(Q, K, V) = softmax(Q @ K^T / sqrt(d_k)) @ V

Scaled Dot-Product Attention

                Q    K^T
                |     |
                +--@--+
                   |
              / sqrt(d_k)
                   |
               softmax
                   |
                   @ V
                   |
                output

Attention(Q, K, V) = softmax(Q @ K^T / sqrt(d_k)) @ V

Why scale by sqrt(d_k)?

  • Dot products grow with dimension
  • Large values push softmax into saturated regions
  • Gradients become very small
  • Scaling keeps values in good range

Self-Attention Computation Example

Input: "The cat sat"
       [x_1, x_2, x_3]

Step 1: Project to Q, K, V
Q = [q_1, q_2, q_3]
K = [k_1, k_2, k_3]
V = [v_1, v_2, v_3]

Step 2: Compute attention scores (Q @ K^T)
        k_1   k_2   k_3
q_1 [  0.8   0.1   0.1  ]  "The" attends mostly to itself
q_2 [  0.3   0.5   0.2  ]  "cat" attends to "The" and itself
q_3 [  0.1   0.6   0.3  ]  "sat" attends mostly to "cat"

Step 3: Weighted sum of values
output_1 = 0.8*v_1 + 0.1*v_2 + 0.1*v_3
output_2 = 0.3*v_1 + 0.5*v_2 + 0.2*v_3
output_3 = 0.1*v_1 + 0.6*v_2 + 0.3*v_3

6.6.1.3 Multi-Head Attention

Instead of single attention, use multiple attention "heads" in parallel.

Motivation

  • Single attention can only focus on one type of relationship
  • Multiple heads can capture different patterns:
    • Head 1: syntactic relationships
    • Head 2: semantic relationships
    • Head 3: positional patterns
    • etc.

Architecture

Input X
   |
   +---> Head 1: Attention(X @ W_Q1, X @ W_K1, X @ W_V1)
   |
   +---> Head 2: Attention(X @ W_Q2, X @ W_K2, X @ W_V2)
   |
   +---> ...
   |
   +---> Head h: Attention(X @ W_Qh, X @ W_Kh, X @ W_Vh)
   |
   +---> Concatenate all heads
   |
   +---> Linear projection (W_O)
   |
Output

Equations

# For each head i:
head_i = Attention(Q @ W_Qi, K @ W_Ki, V @ W_Vi)

# Concatenate and project:
MultiHead(Q, K, V) = Concat(head_1, ..., head_h) @ W_O

# Dimensions:
# W_Qi, W_Ki: d_model x d_k
# W_Vi: d_model x d_v
# W_O: (h * d_v) x d_model
# Typically: d_k = d_v = d_model / h

Example Dimensions

d_model = 512 (model dimension)
h = 8 (number of heads)
d_k = d_v = 512 / 8 = 64 (per-head dimension)

Each head operates on 64-dimensional projections
Concatenated: 8 * 64 = 512
Final projection: 512 -> 512

6.6.1.4 Positional Encoding

Self-attention is permutation invariant - it doesn't know position! We must inject position information.

The Problem

Self-attention sees:
"dog bites man" and "man bites dog" as identical!

Attention only looks at content, not position.

Sinusoidal Positional Encoding (Original Transformer)

PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))

Where:
- pos = position in sequence (0, 1, 2, ...)
- i = dimension index
- d_model = embedding dimension

Why sinusoids?

  • Unique encoding for each position
  • Can extrapolate to longer sequences than seen in training
  • Relative positions can be computed as linear functions
  • PE(pos+k) can be represented as linear transform of PE(pos)

Learned Positional Embeddings

# Alternative: learn position embeddings
position_embeddings = nn.Embedding(max_seq_len, d_model)

# Add to input
x = token_embeddings + position_embeddings

Comparison:

AspectSinusoidalLearned
ExtrapolationBetterLimited to max_seq_len
PerformanceSimilarSimilar
ParametersNonemax_seq_len * d_model
Used inOriginal TransformerBERT, GPT

Other Position Encodings

  • Relative positional encoding: Encode relative distances, not absolute positions
  • Rotary Position Embedding (RoPE): Used in modern LLMs (LLaMA, etc.)
  • ALiBi: Attention with Linear Biases

6.6.1.5 Attention Complexity

Time and Space Complexity

Self-attention for sequence length n:

Q @ K^T: (n x d) @ (d x n) = n x n matrix
Softmax: O(n^2)
@ V: (n x n) @ (n x d) = n x d

Time: O(n^2 * d)
Space: O(n^2) for attention matrix

The Quadratic Problem

Sequence length    Attention matrix size
    512                 262,144
   1024               1,048,576
   4096              16,777,216
  16384             268,435,456

Memory and compute grow quadratically!

Efficient Attention Variants

MethodComplexityApproach
Sparse attentionO(n * sqrt(n))Attend to subset of positions
Linear attentionO(n)Kernel approximation
Flash AttentionO(n^2) time, O(n) memoryMemory-efficient implementation
Sliding windowO(n * w)Local attention window

Questions & Answers

Q1: What is Attention in machine learning models?

Answer:

Attention is a mechanism that allows models to dynamically focus on relevant parts of the input when producing each part of the output.

Core concept:

Instead of fixed context: Compute weighted combination of inputs
Weights: Learned based on relevance to current task/position

General formulation:

1. Compute relevance scores: e_j = score(query, key_j)
2. Normalize to weights: alpha_j = softmax(e_j)
3. Weighted sum: context = sum(alpha_j * value_j)

Key benefits:

  1. Dynamic focus: Different outputs attend to different inputs
  2. Handles variable length: No fixed-size bottleneck
  3. Interpretability: Attention weights show what model focuses on
  4. Long-range dependencies: Direct connections regardless of distance

Types of attention:

TypeQueryKeys/ValuesUse case
Cross-attentionDecoderEncoderSeq2seq, translation
Self-attentionSame sequenceSame sequenceTransformers
Causal self-attentionPosition iPositions <= iLanguage modeling

Example (translation):

Source: "Je suis etudiant"
Target: "I am a student"

When generating "student":
- High attention on "etudiant" (relevant)
- Low attention on "Je", "suis" (less relevant)

Q2: How does self-attention differ from RNN-based attention?

Answer:

RNN-based attention (Bahdanau/Luong):

Encoder: RNN processes sequence sequentially
         h_1 -> h_2 -> h_3 -> h_4

Decoder: At each step, attend over encoder states
         Query: decoder hidden state s_t
         Keys/Values: encoder hidden states h_1...h_n
         
Cross-attention between two different sequences

Self-attention (Transformer):

Single sequence attends to itself
Query, Key, Value: ALL from same sequence
Each position attends to ALL positions simultaneously

No recurrence - fully parallel

Key differences:

AspectRNN + AttentionSelf-Attention
RecurrenceYes (sequential)No (parallel)
Attention typeCross (decoder->encoder)Self (within sequence)
ParallelizationLimitedFully parallel
Long-range depsThrough RNN statesDirect connections
ComputationO(n) sequential stepsO(n^2) parallel
Position infoImplicit in RNNRequires positional encoding

Architectural comparison:

RNN + Attention:
x_1 -> [RNN] -> h_1 ----+
                        |
x_2 -> [RNN] -> h_2 ----+---> Attention ---> Decoder
                        |
x_3 -> [RNN] -> h_3 ----+

Self-Attention:
x_1 ----+----+----+
        |    |    |
x_2 ----+----+----+---> All-to-all attention ---> output
        |    |    |
x_3 ----+----+----+

Advantages of self-attention:

  1. Parallelization: All positions computed simultaneously
  2. Constant path length: Any two positions connected in O(1) layers
  3. No vanishing gradients: Direct gradient flow between any positions
  4. Flexibility: Can model any dependency pattern

Advantages of RNN + attention:

  1. Inductive bias: Sequential processing natural for sequences
  2. Memory efficient: O(1) memory per step vs O(n^2)
  3. Implicit position: No need for positional encoding

Modern trend: Self-attention (Transformers) dominates due to parallelization and performance, despite quadratic complexity.

Browse the library