PART 1 · VISUAL CONCEPTS · 02 / 05

Self-Attention & Causal Masking

How does a word like “it” figure out what it refers to—without peeking at future words?

scores = (Q · Kᵀ) / √d_k Causal Mask (j > i → -∞) Multi-Head Parallelism
Interactive Lab 01 · Scaled Dot-Product Attention

Click Any Query Token, Switch Heads & Toggle Causal Masking

Notice how “it” shifts between “animal” and “street” when Causal Mask is OFF vs. ON.

Query: "it" (i=7)
Attention Arcs (Click Any Token = Query Q_i)
Top Key: animal
N×N Attention Matrix (Rows=Q, Cols=K)
10 × 10
Cell (Q="it", K="animal") ALLOWED (j ≤ i)
Raw Q·Kᵀ 24.80
÷ √d_k 3.10
Mask Pass
Softmax % 42.1%
Interactive Lab 02 · Value Blending & Quadratic Cost

How Context Morphs the Vector & Why Long Prompts Cost O(n²)

Contextual Output Vector (Σ α_j · V_j)
For Q = "it"
Static Embedding V["it"] Before Attention
Contextual Output Σ α·V Live Blend
Why Long Context Gets Expensive: O(n²)
n = 512 tokens
n = 8 n = 8,192
Pairs (n²) 262.1K
FP16 / Head 512 KB
32 Heads Total 16.0 MB
FlashAttention tiles this in SRAM, while C4 (KV-Cache) & S1 (PagedAttention) stop decode from recomputing it every token.
Mental Model · 20 Lines of Pure Python

Scaled Dot-Product Attention Without Frameworks

self_attention.py

      

Why divide by √d_k?

Large dot products push softmax into 0.999 / 0.001 saturation where gradients vanish—toggle Scaling OFF above to watch weights collapse into spikes.

Why -∞ before Softmax?

Because e^(-∞) = 0 cleanly removes future tokens while keeping all past attention weights normalized to sum to exactly 1.0.

Why Multi-Head Attention?

A single head averages everything; parallel heads let one subspace track pronouns, another track local syntax, and another track global semantics simultaneously.