FullStack AI Hub
Studio
AI & LLM Systems · 01. Transformer Architecture
12 min
6 steps
Intermediate

Self-Attention & Q/K/V Mechanics

Explore live Query-Key-Value attention beams, N×N softmax heatmaps, √d_k scaling saturation, and causal masking.

AI & LLM Systems01. Transformer ArchitectureLesson 2 of 4
12 minIntermediate6 steps

Self-Attention & Q/K/V Mechanics

Explore live Query-Key-Value attention beams, N×N softmax heatmaps, √d_k scaling saturation, and causal masking.

PEAK FOCUS
52% → animal
ROW ENTROPY
1.86 bits
MASKING
Causal (GPT)
ACTIVE O(N²)
78 / 144 cells
Scaled Dot-Product Attention · Q/K/V Lab
Query (click token)“it” → 52% “animal”Keys / Values
52%38%Theanimaldidn'tcrossthestreetbecauseitwastootiredTheanimal52didn'tcrossthestreetbecauseit38wastootired
Softmax(Q·Kᵀ / √d_k) Matrix (12×12)
Q \ K
The
anim
didn
't
cros
the
stre
beca
it
was
too
tire
Click any row to lock Query× = masked future (−∞ → 0.00)
In This LessonStep 1 of 6
What You Will Master
  • ✓Explain how Queries (what I seek), Keys (what I advertise), and Values (what I pass along) contextualize words
  • ✓Demonstrate why dividing dot products by √d_k prevents softmax saturation and vanishing gradients
  • ✓Contrast causal triangular masking (GPT decoders) against bidirectional attention (BERT encoders)
  • ✓Recognize the O(N²) attention matrix bottleneck and how FlashAttention tiles SRAM to stay fast

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Query · Keyᵀ Dot ProductComputing pairwise relevance between every token pair in parallelProduces an N × N score matrix whose memory & FLOPs grow quadratically with context length
1 / √d_k ScalingKeeping pre-softmax variance near 1.0 regardless of head dimension d_kWithout scaling, large dot products push softmax into near-one-hot saturation with ~0 gradients
Causal Mask (−∞ Upper Tri)Autoregressive LLMs trained on next-token prediction without leaking future wordsBlocks right-to-left context; each token only sees positions j ≤ i
FlashAttention (IO-Aware)Long-context training & serving (32K–1M tokens) without materializing N×N in HBMComputes exact attention in fused GPU SRAM tiles using online softmax rescaling

Step-by-Step Architectural Breakdown (6 Steps)

Full architectural walkthrough transcript and state transitions for Self-Attention & Q/K/V Mechanics.

STEP 01 · SETUPJump to step →

Queries, Keys & Values: Contextualizing Ambiguous Words

In `"The animal didn't cross the street because it was too tired"`, what does **`"it"`** refer to? Static embeddings can’t tell—`"it"` must dynamically gather evidence from earlier tokens.

Each token projects into three vectors: a **Query ($Q$)** asking *"what context do I need?"*, a **Key ($K$)** advertising *"what information do I hold?"*, and a **Value ($V$)** carrying the payload to blend into the output. Watch the bold cobalt beam linking **`"it"`** straight back to **`"animal"`**!

idea:Click any word on the left column or hover any cell in the heatmap on the right to inspect live Q·Kᵀ dot-product scores in the Math Inspector.

Query/Key/ValueContextual EmbeddingsAttention Beams
STEP 02 · PROBLEMJump to step →

Why Dividing by √d_k Saves Training from Softmax Collapse

If $Q$ and $K$ have unit-variance elements across $d_k = 64$ dimensions, their dot product $Q \cdot K^\top$ has variance $d_k = 64$ (standard deviation $8$). Feeding raw scores like `+18.4` vs `+4.1` directly into `softmax` crushes all other tokens to `0.0000`!

When softmax saturates into a near one-hot spike, its derivative approaches **zero**—starving backpropagation of gradients. Dividing by **`√d_k` (`8`)** restores clean unit variance so attention stays smooth and trainable.

watch:Run the experiment below (or click "÷ √d_k Scaling" on the stage) to witness row entropy collapse as softmax saturates into a rigid spike.

Scaled Dot-ProductSoftmax SaturationVanishing Gradients
STEP 03 · SOLUTIONJump to step →

Causal Masking: Stopping Autoregressive Models from Cheating

During parallel GPT training, the entire prompt is fed in at once so all positions predict their next token simultaneously. Without a mask, token 8 (`"it"`) could peek ahead at token 11 (`"tired"`)—making training trivially cheated and useless at inference time.

Adding an upper-triangular **Causal Mask $M$** sets every future cell ($j > i$) to **`−∞`** *before* softmax. Since $e^{-\infty} = 0$, future tokens receive strictly `0.00%` weight (shown as hatched `×` cells on the heatmap).

good:Encoders like BERT disable the causal mask (Bidirectional) so every word sees full left-and-right context; Decoder LLMs like GPT & Claude always keep it ON.

Causal MaskAutoregressive TrainingBidirectional Encoder
STEP 04 · TECHNIQUEJump to step →

Attention in Code: Variable Binding & Bracket Matching

Self-attention isn’t limited to English prose. In `function clamp(val, min, max) { return Math.min(max,`, attention heads act like a soft differentiable symbol table.

Watch how the final `max,` token shoots an attention beam directly back to the parameter declaration `, max`—while switching to the **Syntax Head** links closing delimiters `) {` back to their opening parenthesis `(`.

idea:Try switching between H1 Coref and H2 Syntax in the stage toolbar while inspecting the code prompt.

Induction HeadsVariable BindingCode Completion
STEP 05 · TRADE-OFFJump to step →

The O(N²) Matrix Wall & FlashAttention Tiling

Look at the $N \times N$ grid on the right: for 12 tokens it holds 144 cells, but for a **128,000-token** prompt a single attention head would need **16.3 billion cells** (32 GB in FP16 for just one head!).

**FlashAttention** solves the memory wall without approximations: instead of writing the giant $N \times N$ matrix to slow GPU HBM, it tiles $Q, K, V$ into fast on-chip **SRAM** and updates exact softmax incrementally—cutting HBM memory from $O(N^2)$ to $O(N)$ and speeding up attention 2–4×.

good:FlashAttention computes the exact same mathematical result as standard attention—it is purely an IO-aware hardware tiling breakthrough.

Quadratic ComplexityFlashAttentionOnline SoftmaxGPU SRAM
STEP 06 · RECAPJump to step →

Recap: One Equation Powers Contextual Intelligence

Every attention head runs one compact equation: $\text{Attn}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V$.

A single head can only focus on one kind of relationship at a time. Next, we stack **parallel Multi-Head streams**, wire them onto a clean **Residual Highway**, and pass the result through a **SwiGLU Feed-Forward Network**.

good:Open the Math & Tensor Shape Inspector below the stage to review the exact shape flow: [1, H, T, d_k] → [1, H, T, T] → [1, T, d_model].

Scaled Dot-Product EquationAttention Summary

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.