Preset Sentence:
Attention Head:
Mask:
Attention Heatmap: Softmax(Q · KT / √dk)
Coreference Head (Pronoun → Referent binding)
Select or hover any cell in the matrix to inspect exact Query-Key dot products and softmax weights.
Mathematical Decomposition dk = 64 · Layer 1
1. Query & Key Dot Product q["it"] · k["animal"]
Score = Q · K = 38.42
High cosine affinity: token "it" aligns strongly with noun antecedent "animal".
2. Variance Normalization (√dk) √64 = 8.0
Scaled Score = 38.42 / 8.0 = 4.8025

Prevents large dot products from pushing softmax into vanishing gradient saturation regions.

3. Softmax Normalization p = 0.762
αij = exp(sij) / ∑k exp(sik)
4. Value Aggregation (Context Vector z) zi = ∑ αij · Vj
z["it"] = 0.762 · V["animal"] + 0.141 · V["tired"] + ...

Token "it" absorbs 76% of its new semantic representation directly from the physical features of "animal".

The Mathematical Engine of Modern Artificial Intelligence

Introduced in 2017 by Vaswani et al. in the landmark paper "Attention Is All You Need", the Transformer eliminated recurrent sequential bottlenecks, enabling parallel training over trillions of tokens. Here is how its mechanisms calculate meaning.

1. The Problem with Recurrence: Why RNNs Failed to Scale

Prior to 2017, the undisputed state-of-the-art for natural language processing was the Recurrent Neural Network (RNN) and its gated variants, the Long Short-Term Memory (LSTM) and Gated Recurrent Unit (GRU). While conceptually elegant, recurrent models suffered from a fatal computational limitation: sequential dependency.

In an RNN, the hidden state at step $t$ ($h_t$) is a strict function of the previous hidden state $h_{t-1}$ and the current input $x_t$:

ht = tanh(Whh · ht-1 + Wxh · xt + b)
Sequential computation constraint: computing token 1,000 requires 999 sequential matrix multiplications.

This recurrence created two insurmountable roadblocks:

  • Zero Parallelization across Time: Modern GPUs contain thousands of tensor cores built for massive simultaneous matrix multiplications. An RNN forces GPUs to idle while waiting for sequential timesteps to complete.
  • Information Compression Bottleneck: The entire historical context of a 500-word paragraph had to be squeezed into a fixed-width vector $h_t$. Long-range dependencies suffered from catastrophic forgetting and vanishing gradients.

2. Self-Attention: The Query, Key, and Value Formulation

Transformers discard recurrence completely. Instead of transmitting a vector like a baton down a relay line, every token in a sequence can look directly at every other token simultaneously. This mechanism is called Self-Attention.

To understand the math, consider how database retrieval functions: you submit a Query, compare it against indexed Keys, and retrieve corresponding Values. In a Transformer, every single token generates all three vectors by multiplying its input embedding $x_i$ by three learned parameter projection matrices:

  • Query ($Q = X \cdot W_Q$): What this token is searching for in the surrounding context.
  • Key ($K = X \cdot W_K$): What features or characteristics this token has to offer to others.
  • Value ($V = X \cdot W_V$): The substantive payload or information transmitted if a match is established.
Attention(Q, K, V) = softmax( (Q · KT) / √dk ) · V
The core equation of the Transformer. Q, K have dimension d_k; V has dimension d_v.

Why Divide by √dk?

For large projection dimensions (e.g., $d_k = 64$ or $128$), the dot product of two independent zero-mean, unit-variance vectors has a mean of 0 and a variance equal to $d_k$. Without dividing by $\sqrt{d_k}$, large dot products yield values in the hundreds, pushing the softmax function into regions where gradients are infinitesimally small ($< 10^{-6}$), completely stalling gradient descent.

3. Multi-Head Attention: Distinct Semantic Perspectives

A single attention distribution can only focus on one relationship at a time. If the word "bank" attends to "river" to clarify its lexical meaning, it might fail to attend to "overflowed" to establish its grammatical role as the subject of the clause.

Multi-Head Attention (MHA) solves this by projecting $Q, K, V$ into $h$ distinct lower-dimensional subspaces (typically 8, 16, or 32 heads). Each head performs scaled dot-product attention in parallel with its own learned projections:

MultiHead(Q, K, V) = Concat(head1, ..., headh) · WO

where headi = Attention(Q · WQ(i), K · WK(i), V · WV(i))

In practice, heads spontaneously specialize during pre-training:

  1. Coreference Heads: Resolving ambiguous pronouns (linking "it" to "the animal" or "the street").
  2. Syntactic Binding Heads: Associating adjectives directly with their downstream head nouns.
  3. Positional Proximity Heads: Attending to immediate predecessor and successor bigrams.
  4. Global Semantic Heads: Broadcasting document-wide topic themes across all tokens.

4. Positional Encodings: Injecting Spatial Awareness

Because Self-Attention is permutation-invariant—calculating dot-products regardless of token order—the sentence "Dog bites man" would produce the exact same attention outputs as "Man bites dog" without positional intervention.

To give the model sequence awareness, positional signals are combined with token embeddings:

  • Sinusoidal Encodings (Original 2017): Fixed sine and cosine waves of varying frequencies added directly to the input embeddings:
    PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
  • Rotary Position Embeddings (RoPE - Modern LLaMA/Mistral): Instead of adding a vector, RoPE rotates the Query and Key vectors in 2D complex coordinate planes by an angle proportional to their absolute position. This ensures the dot product $Q_m \cdot K_n$ depends purely on the relative distance $(m - n)$.

5. The Transformer Block: Residuals, Norms, and Feed-Forward Networks

Attention by itself is merely a dynamic re-weighting mechanism; it does not introduce non-linear reasoning. A complete Transformer layer pairs multi-head attention with a point-wise Feed-Forward Network (FFN) and deep residual streams:

Sub-Layer Operation Mathematical Function Primary Purpose
Residual Stream Skip Connection $x + \text{Sublayer}(x)$ Allows gradients to flow unimpeded directly from output to input layers, preventing vanishing gradients in 100+ layer models.
LayerNorm / RMSNorm Normalization $(x - \mu) / \sigma \cdot \gamma$ Stabilizes activation distributions across layers, accelerating convergence during multi-GPU distributed training.
Feed-Forward (MLP) Non-linear Projection $\text{SwiGLU}(x W_1) \cdot W_2$ Expands dimension $4\times$, applies non-linear activation (GELU/SwiGLU), and projects back; acts as the model's factual memory store.

6. Encoder vs. Decoder: The Architectural Family Tree

Modern large language models split into three distinct architectural archetypes based on their masking and attention topology:

  • Encoder-Only (BERT, RoBERTa): Uses full bidirectional attention where every token attends to past, present, and future tokens simultaneously. Ideal for sentence classification, named entity recognition, and dense embedding retrieval.
  • Decoder-Only (GPT-4, LLaMA, Claude, Mistral): Uses causal masking (an upper-triangular mask of $-\infty$ values before softmax) so token $t$ can only attend to tokens $1 \dots t$. This autoregressive structure is uniquely suited for open-ended text generation.
  • Encoder-Decoder (Original Transformer, T5, Whisper): An encoder processes the full source bidirectionally (e.g. English audio or text), while a decoder generates the target autoregressively (e.g. French translation) using cross-attention over the encoder's outputs.

Frequently Asked Questions

Why did Transformers replace Recurrent Neural Networks (RNNs)? +
RNNs processed sequences sequentially token-by-token, creating an unparallelizable $O(N)$ computational bottleneck. Transformers process all tokens simultaneously using Self-Attention with $O(1)$ sequential operations, allowing massive GPU scaling and eliminating vanishing gradients across long distances.
What is the physical meaning of Query, Key, and Value vectors? +
Queries represent what a token is searching for in the sequence; Keys represent what attributes a token possesses; and Values represent the actual content or information payload transmitted to the recipient token when a Query-Key match occurs.
Why divide by the square root of the key dimension (sqrt(d_k)) in attention? +
When the dimension $d_k$ is large, dot products grow substantially in variance. Unscaled dot products push the softmax activation function into regions with near-zero gradients (saturation), paralyzing gradient backpropagation during training.
What is the difference between Encoder-only, Decoder-only, and Encoder-Decoder architectures? +
Encoder-only (e.g. BERT) uses bidirectional attention to understand full contexts for classification and embeddings. Decoder-only (e.g. GPT, LLaMA) uses causal masking to prevent tokens from looking into the future, making them ideal for autoregressive text generation. Encoder-Decoder (e.g. T5) encodes an input sequence bidirectionally and decodes an output sequence autoregressively with cross-attention.
Enjoy this tool? Build your own with Super