Skip to content
E
Educatum

Explain the mechanics of self-attention and how it allows models to weigh the importance of different parts of the input data relative to each other.

Curated by Educatum AI teamLast updated:
Transformer Models
Direct Answer

Self-attention computes contextual token representations by projecting inputs into Query (Q), Key (K), and Value (V) vectors and taking a softmax-weighted sum over values using scaled dot products QK^T / sqrt(d_k). Dividing by sqrt(d_k) keeps dot-product variance near 1 so softmax does not saturate with vanishing gradients at large head dimensions. While enabling O(1) parallel path length across any distance, full self-attention scales at O(n^2 d) compute and O(n^2) memory.

Study Card: Mechanics of Self-Attention

Direct Answer

Self-attention computes dynamic, input-dependent pairwise interactions across all tokens in a sequence X∈Rn×dX \in \mathbb{R}^{n \times d}. Each token representation is projected via three learned weight matrices WQ,WK∈Rd×dkW_Q, W_K \in \mathbb{R}^{d \times d_k} and WV∈Rd×dvW_V \in \mathbb{R}^{d \times d_v} into Queries (Q=XWQQ = X W_Q), Keys (K=XWKK = X W_K), and Values (V=XWVV = X W_V), then combined via scaled dot-product attention (Vaswani et al., 2017):

Attention(Q,K,V)=softmax ⁣(QKTdk+M)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^T}{\sqrt{d_k}} + M\right) V

Three architectural principles govern self-attention:

  1. Why divide by dk\sqrt{d_k}? If components of qq and kk are independent with zero mean and unit variance, their dot product ∑i=1dkqiki\sum_{i=1}^{d_k} q_i k_i has mean 00 and variance dkd_k (standard deviation dk\sqrt{d_k}). For large dkd_k, unscaled dot products grow large in magnitude, pushing softmax into extreme saturation regions where gradients nearly vanish. Scaling by 1dk\frac{1}{\sqrt{d_k}} restores unit variance.
  2. Complexity & Path Length: Unlike RNNs (O(n)O(n) sequential steps), self-attention connects any two tokens in O(1)O(1) path length with full parallelism across sequence positions, at a cost of O(n2d)O(n^2 d) compute and O(n2)O(n^2) attention-matrix memory (mitigated in hardware via FlashAttention tiling).
  3. Masking (MM): Encoders (BERT) allow bidirectional attention (M=0M = 0), whereas autoregressive decoders (GPT/LLaMA) add −∞-\infty above the main diagonal so token tt cannot attend to future tokens >t> t.

Key Terms

  • Query (QQ), Key (KK), Value (VV): Linear projections representing what information a token seeks (QQ), what attributes a token advertises (KK), and what content it contributes (VV).
  • Scaled Dot-Product Attention: Pairwise compatibility scoring QKTdk\frac{QK^T}{\sqrt{d_k}} followed by row-wise softmax normalization.
  • Causal Mask: Upper-triangular −∞-\infty mask preventing autoregressive decoders from peeking at future tokens during parallel training.
  • Quadratic Complexity (O(n2)O(n^2)): Memory and compute bottleneck on long sequences motivating FlashAttention, sparse/sliding-window attention, and KV caching.

Example

Consider "The animal didn't cross the street because it was too tired":

  • When updating the representation for "it", the query vector for "it" computes high dot products against the key vector for "animal" (and "tired"), producing a high attention weight on "animal" and near-zero weights on function words like "the".
  • Taking the weighted sum of value vectors injects semantic attributes of "animal" directly into "it" in a single layer—even across arbitrary token distance.

Code Implementation

import torch
import torch.nn as nn


def scaled_dot_product_attention(q, k, v, mask=None):
    """
    Args:
        q: (batch_size, seq_len, d_k)
        k: (batch_size, seq_len, d_k)
        v: (batch_size, seq_len, d_v)
        mask: Optional boolean/0-1 mask (1 = keep, 0 = mask out) broadcastable to (B, L, L)
    """
    d_k = q.size(-1)
    scores = torch.matmul(q, k.transpose(-2, -1)) / (d_k ** 0.5)
    if mask is not None:
        # Use -inf (safe across fp16/bf16/fp32 unlike -1e9 which overflows fp16)
        scores = scores.masked_fill(mask == 0, float("-inf"))
    attn_weights = torch.softmax(scores, dim=-1)
    output = torch.matmul(attn_weights, v)
    return output, attn_weights


class SelfAttention(nn.Module):
    def __init__(self, d_model, d_k=None, d_v=None):
        super().__init__()
        d_k = d_k or d_model
        d_v = d_v or d_model
        self.W_q = nn.Linear(d_model, d_k, bias=False)
        self.W_k = nn.Linear(d_model, d_k, bias=False)
        self.W_v = nn.Linear(d_model, d_v, bias=False)

    def forward(self, x, causal=False):
        q, k, v = self.W_q(x), self.W_k(x), self.W_v(x)
        mask = None
        if causal:
            seq_len = x.size(1)
            mask = torch.tril(torch.ones(seq_len, seq_len, device=x.device)).unsqueeze(0)
        return scaled_dot_product_attention(q, k, v, mask=mask)


torch.manual_seed(0)
x = torch.randn(2, 4, 64)  # (batch_size=2, seq_len=4, d_model=64)
self_attn = SelfAttention(d_model=64, d_k=64, d_v=128)
output, weights = self_attn(x, causal=True)

print("Output shape:", output.shape)             # (2, 4, 128)
print("Attention weights shape:", weights.shape) # (2, 4, 4)
print("Causal weights (batch 0):\n", weights[0].detach().round(decimals=3))
  • Multi-Head Attention: Runs hh independent Q/K/V projections in parallel subspaces, preventing a single softmax map from averaging distinct relations.
  • FlashAttention: Fuses tiling, online softmax, and recomputation in GPU SRAM to eliminate O(n2)O(n^2) HBM materialization without changing exact math.
  • KV Caching: Stores past KK and VV tensors during autoregressive decoding so each generated token computes only O(nd)O(n d) attention rather than recomputing the full prefix.
  • Positional Encoding & RoPE: Essential companion since pure self-attention is permutation-equivariant.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.