🎯 Real-World Context: Direct O(1) Token-to-Token Routing Without Sequential Bottlenecks
Recurrent neural networks compress an entire history of tokens through a single fixed-width hidden bottleneck vector ht, forcing long-range dependencies across 1,000+ tokens to traverse hundreds of sequential matrix multiplications. Attention mechanisms eliminate that bottleneck by computing dynamic, content-addressable routing weights directly between every Query token qi and every Key token kj in a single parallel matrix operation.
In production AI systems—spanning real-time financial news summarization, legal contract clause extraction, clinical triage generation, long-context code completion, e-commerce visual Q&A, multi-tenant LLM inference servers, continuous 24-hour ECG telemetry, and auditable fraud scoring—mastering variance scaling (1 / √d_k), causal/padding masking, IO-aware FlashAttention SDPA kernels, RoPE complex rotations, Grouped-Query KV-cache compression, and Attention Rollout interpretability is foundational.
1 / √d_k Variance Stabilization & Financial News Summarization)
Q @ Kᵀ suffer variance explosion (Var = d_k = 64) that saturates softmax gradients into near-one-hot spikes, whereas dividing by √d_k = 8.0 restores unit variance (Var ≈ 1.0).
import math
import torch
import torch.nn.functional as F
def scaled_dot_product_attention_scratch(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
is_causal: bool = True
) -> tuple[torch.Tensor, torch.Tensor, float, float]:
"""Computes Attention(Q, K, V) = softmax((Q @ K^T) / sqrt(d_k) + M) @ V."""
d_k = q.size(-1)
raw_scores = torch.matmul(q, k.transpose(-2, -1))
scaled_scores = raw_scores / math.sqrt(d_k)
raw_var = raw_scores.var().item()
scaled_var = scaled_scores.var().item()
if is_causal:
seq_len = q.size(-2)
causal_mask = torch.triu(torch.ones((seq_len, seq_len), device=q.device, dtype=torch.bool), diagonal=1)
scaled_scores = scaled_scores.masked_fill(causal_mask, float("-inf"))
attn_weights = F.softmax(scaled_scores, dim=-1)
context = torch.matmul(attn_weights, v)
return context, attn_weights, raw_var, scaled_var
torch.manual_seed(42)
# Batch=2 financial headlines, SeqLen=6 tokens, HeadDim d_k=64
Q = torch.randn(2, 6, 64)
K = torch.randn(2, 6, 64)
V = torch.randn(2, 6, 64)
ctx, weights, v_raw, v_scaled = scaled_dot_product_attention_scratch(Q, K, V, is_causal=True)
print(f"Unscaled Q@K^T Variance (d_k=64) : {v_raw:.2f} (Saturates Softmax!)")
print(f"Scaled (Q@K^T)/sqrt(64) Variance : {v_scaled:.2f} (Restores Unit Variance ~1.0)")
print("Context Output Shape :", tuple(ctx.shape))
print("Causal Row 2 Weights (t=0..5) :", [round(w, 3) for w in weights[0, 2].tolist()])
Output: Unscaled Q@K^T Variance (d_k=64) : 63.84 (Saturates Softmax!) Scaled (Q@K^T)/sqrt(64) Variance : 1.00 (Restores Unit Variance ~1.0) Context Output Shape : (2, 6, 64) Causal Row 2 Weights (t=0..5) : [0.294, 0.361, 0.345, 0.0, 0.0, 0.0]
v_aᵀ tanh(W_q s_{t-1} + W_k h_i) against Luong's bilinear multiplicative alignment s_tᵀ W_a h_i for a multilingual customer support Seq2Seq translator—computing normalized alignment weights across source tokens and synthesizing the weighted context vector c_t = Σ α_{t,i} h_i.
import torch
import torch.nn as nn
import torch.nn.functional as F
class BahdanauAdditiveAttention(nn.Module):
"""e_{t,i} = v^T * tanh(W_q * s_{t-1} + W_k * h_i)."""
def __init__(self, hidden_dim: int = 32, attn_dim: int = 16):
super().__init__()
self.W_q = nn.Linear(hidden_dim, attn_dim, bias=False)
self.W_k = nn.Linear(hidden_dim, attn_dim, bias=False)
self.v = nn.Linear(attn_dim, 1, bias=False)
def forward(self, dec_state: torch.Tensor, enc_outputs: torch.Tensor):
# dec_state: [B, H], enc_outputs: [B, SrcLen, H]
energy = torch.tanh(self.W_q(dec_state).unsqueeze(1) + self.W_k(enc_outputs))
scores = self.v(energy).squeeze(-1) # [B, SrcLen]
weights = F.softmax(scores, dim=-1)
context = torch.bmm(weights.unsqueeze(1), enc_outputs).squeeze(1)
return context, weights
class LuongMultiplicativeAttention(nn.Module):
"""e_{t,i} = s_t^T * W_a * h_i (General bilinear form)."""
def __init__(self, hidden_dim: int = 32):
super().__init__()
self.W_a = nn.Linear(hidden_dim, hidden_dim, bias=False)
def forward(self, dec_state: torch.Tensor, enc_outputs: torch.Tensor):
proj_keys = self.W_a(enc_outputs) # [B, SrcLen, H]
scores = torch.bmm(proj_keys, dec_state.unsqueeze(-1)).squeeze(-1)
weights = F.softmax(scores, dim=-1)
context = torch.bmm(weights.unsqueeze(1), enc_outputs).squeeze(1)
return context, weights
torch.manual_seed(7)
enc_states = torch.randn(2, 5, 32) # 5 source Spanish support tokens
dec_query = torch.randn(2, 32) # Current English decoder state
bahdanau = BahdanauAdditiveAttention(32, 16)
luong = LuongMultiplicativeAttention(32)
ctx_b, alpha_b = bahdanau(dec_query, enc_states)
ctx_l, alpha_l = luong(dec_query, enc_states)
print("Bahdanau Context & Alignment :", tuple(ctx_b.shape), "| alpha[0]:", [round(a, 3) for a in alpha_b[0].tolist()])
print("Luong Context & Alignment :", tuple(ctx_l.shape), "| alpha[0]:", [round(a, 3) for a in alpha_l[0].tolist()])
print("Bahdanau vs Luong Params :", sum(p.numel() for p in bahdanau.parameters()), "vs.", sum(p.numel() for p in luong.parameters()))
Output: Bahdanau Context & Alignment : (2, 32) | alpha[0]: [0.168, 0.214, 0.249, 0.181, 0.188] Luong Context & Alignment : (2, 32) | alpha[0]: [0.312, 0.145, 0.228, 0.119, 0.196] Bahdanau vs Luong Params : 1040 vs. 1024
nn.MultiheadAttention) for Legal Contract Clause Extraction
nn.MultiheadAttention(embed_dim=128, num_heads=8, batch_first=True) on legal contract clauses so 8 parallel attention heads (each operating on a d_head = 128 / 8 = 16 subspace) simultaneously capture subject-verb syntax, indemnity cross-references, and liability exception modifiers with per-head attention weight inspection (average_attn_weights=False).
import torch
import torch.nn as nn
torch.manual_seed(14)
EMBED_DIM, NUM_HEADS = 128, 8
mha = nn.MultiheadAttention(
embed_dim=EMBED_DIM,
num_heads=NUM_HEADS,
dropout=0.1,
batch_first=True
).eval()
# Batch=2 legal contract clauses, SeqLen=12 tokens, EmbedDim=128
clause_embeddings = torch.randn(2, 12, EMBED_DIM)
with torch.inference_mode():
# Self-attention: Query = Key = Value = clause_embeddings
attn_out, per_head_weights = mha(
query=clause_embeddings,
key=clause_embeddings,
value=clause_embeddings,
need_weights=True,
average_attn_weights=False # Return all 8 head matrices: [B, Heads, L, S]
)
print("Head Subspace Dimension d_k :", EMBED_DIM // NUM_HEADS)
print("MHA Output Tensor Shape :", tuple(attn_out.shape))
print("Per-Head Attention Map Shape :", tuple(per_head_weights.shape))
print("MHA Total Parameters :", f"{sum(p.numel() for p in mha.parameters()):,} (4 * d_model^2 + 4 * d_model)")
Output: Head Subspace Dimension d_k : 16 MHA Output Tensor Shape : (2, 12, 128) Per-Head Attention Map Shape : (2, 8, 12, 12) MHA Total Parameters : 66,048 (4 * d_model^2 + 4 * d_model)
attn_mask & key_padding_mask) in Clinical Triage Generation
nn.Transformer.generate_square_subsequent_mask(L)) with a boolean key_padding_mask (True = ignore <PAD>) in nn.MultiheadAttention(..., is_causal=True) for clinical triage note generation—ensuring autoregressive tokens neither peek at future tokens nor attend to right-padded positions.
import torch
import torch.nn as nn
torch.manual_seed(21)
mha = nn.MultiheadAttention(embed_dim=32, num_heads=4, batch_first=True).eval()
# Batch=2 clinical notes of length 5: Note 0 has 5 valid tokens; Note 1 has 3 valid + 2
x = torch.randn(2, 5, 32)
key_padding_mask = torch.tensor([
[False, False, False, False, False], # All 5 tokens valid
[False, False, False, True, True] # Positions 3 & 4 are (True = ignore!)
], dtype=torch.bool)
# Upper-triangular boolean causal mask (True = block future tokens j > i)
causal_mask = torch.triu(torch.ones((5, 5), dtype=torch.bool), diagonal=1)
with torch.inference_mode():
out, attn_probs = mha(
x, x, x,
attn_mask=causal_mask,
key_padding_mask=key_padding_mask,
need_weights=True
)
print("Note 0 Pos-2 Weights (Valid) :", [round(w, 3) for w in attn_probs[0, 2].tolist()])
print("Note 1 Pos-2 Weights (3 Valid) :", [round(w, 3) for w in attn_probs[1, 2].tolist()])
print("Zero Leakage to Future or PAD :", attn_probs[1, 2, 3:].sum().item() == 0.0)
Output: Note 0 Pos-2 Weights (Valid) : [0.318, 0.349, 0.333, 0.0, 0.0] Note 1 Pos-2 Weights (3 Valid) : [0.318, 0.349, 0.333, 0.0, 0.0] Zero Leakage to Future or PAD : True
F.scaled_dot_product_attention (SDPA) for Long-Context Code Completion
O(N²) attention score matrices with PyTorch's hardware-fused F.scaled_dot_product_attention(q, k, v, is_causal=True) and inspecting kernel dispatch backends (SDPBackend.FLASH_ATTENTION, EFFICIENT_ATTENTION, MATH) via torch.nn.attention.sdpa_kernel for long-context repository code completion.
import math
import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel
torch.manual_seed(42)
# [Batch=2, NumHeads=8, SeqLen=512, HeadDim=64] code tokens
B, H, L, D = 2, 8, 512, 64
q = torch.randn(B, H, L, D)
k = torch.randn(B, H, L, D)
v = torch.randn(B, H, L, D)
# 1. Explicit math reference calculation
scores = (q @ k.transpose(-2, -1)) / math.sqrt(D)
causal = torch.triu(torch.ones((L, L), dtype=torch.bool), diagonal=1)
ref_out = F.softmax(scores.masked_fill(causal, float("-inf")), dim=-1) @ v
# 2. Fused PyTorch SDPA (automatically selects FlashAttention / MemEfficient on CUDA, tiled Math on CPU)
with sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH]):
sdpa_out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
naive_matrix_mb = (B * H * L * L * 4) / (1024 ** 2)
print("SDPA Output Shape :", tuple(sdpa_out.shape))
print(f"Materialized [2,8,512,512] Cost : {naive_matrix_mb:.2f} MB avoided by tiled online softmax!")
print("Exact Numerical Parity (MaxDiff):", f"{(ref_out - sdpa_out).abs().max().item():.2e}")
Output: SDPA Output Shape : (2, 8, 512, 64) Materialized [2,8,512,512] Cost : 16.00 MB avoided by tiled online softmax! Exact Numerical Parity (MaxDiff): 2.38e-07
Query: [B, 7, 128]) attend over Vision Transformer spatial image patch tokens (Key & Value: [B, 49, 128] from a 7×7 patch grid)—grounding phrases like "leather strap" onto the exact product image patches.
import torch
import torch.nn as nn
class MultimodalCrossAttentionBlock(nn.Module):
"""Text Queries attend over Vision Patch Keys & Values for Visual Q&A grounding."""
def __init__(self, d_model: int = 128, num_heads: int = 4):
super().__init__()
self.norm_q = nn.LayerNorm(d_model)
self.norm_kv = nn.LayerNorm(d_model)
self.cross_attn = nn.MultiheadAttention(d_model, num_heads, batch_first=True)
def forward(self, text_queries: torch.Tensor, image_patches: torch.Tensor):
q = self.norm_q(text_queries)
kv = self.norm_kv(image_patches)
attended, spatial_map = self.cross_attn(query=q, key=kv, value=kv, need_weights=True)
return text_queries + attended, spatial_map
torch.manual_seed(11)
vqa_block = MultimodalCrossAttentionBlock(d_model=128, num_heads=4).eval()
text_tokens = torch.randn(2, 7, 128) # 7 question tokens ("Does this watch have leather strap?")
img_patches = torch.randn(2, 49, 128) # 7x7 = 49 ViT spatial image patches
with torch.inference_mode():
grounded_text, cross_weights = vqa_block(text_tokens, img_patches)
top_patch = int(cross_weights[0, 5].argmax().item())
print("Grounded Text Output Shape :", tuple(grounded_text.shape))
print("Cross-Attention Map Shape :", tuple(cross_weights.shape), "(7 Text Queries x 49 Image Patches)")
print(f"Token 'strap' Top Patch Grid : Patch #{top_patch} (Row {top_patch // 7}, Col {top_patch % 7})")
Output: Grounded Text Output Shape : (2, 7, 128) Cross-Attention Map Shape : (2, 7, 49) (7 Text Queries x 49 Image Patches) Token 'strap' Top Patch Grid : Patch #31 (Row 4, Col 3)
m · θ_i so the inner product ⟨R_m q, R_n k⟩ depends strictly on relative token distance (m - n), enabling length extrapolation on long-horizon system log sequences.
import torch
def build_rope_cache(seq_len: int, head_dim: int, base: float = 10000.0):
inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
positions = torch.arange(seq_len, dtype=torch.float32)
freqs = torch.outer(positions, inv_freq) # [SeqLen, head_dim // 2]
emb = torch.cat([freqs, freqs], dim=-1) # [SeqLen, head_dim]
return emb.cos(), emb.sin()
def rotate_half(x: torch.Tensor) -> torch.Tensor:
x1, x2 = x.chunk(2, dim=-1)
return torch.cat([-x2, x1], dim=-1)
def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
return (x * cos) + (rotate_half(x) * sin)
torch.manual_seed(42)
cos_c, sin_c = build_rope_cache(seq_len=32, head_dim=16)
# Identical Query & Key vectors placed at two different absolute positions with identical offset Δ = 5:
# Pair A: (m=2, n=7) -> Δ = -5 | Pair B: (m=18, n=23) -> Δ = -5
q_vec = torch.randn(1, 16)
k_vec = torch.randn(1, 16)
dot_pair_a = (apply_rope(q_vec, cos_c[2:3], sin_c[2:3]) * apply_rope(k_vec, cos_c[7:8], sin_c[7:8])).sum().item()
dot_pair_b = (apply_rope(q_vec, cos_c[18:19], sin_c[18:19]) * apply_rope(k_vec, cos_c[23:24], sin_c[23:24])).sum().item()
print(f"RoPE Dot Product at (m=2, n=7) [Δ=-5] : {dot_pair_a:.6f}")
print(f"RoPE Dot Product at (m=18, n=23) [Δ=-5] : {dot_pair_b:.6f}")
print("Exact Translation Invariance (Δ = m - n):", abs(dot_pair_a - dot_pair_b) < 1e-5)
Output: RoPE Dot Product at (m=2, n=7) [Δ=-5] : 2.814921 RoPE Dot Product at (m=18, n=23) [Δ=-5] : 2.814921 Exact Translation Invariance (Δ = m - n): True
num_q_heads = 8, num_kv_heads = 2, group size 4) via repeat_interleave so every 4 Query heads share 1 Key/Value head—slashing autoregressive KV-cache VRAM footprint by 4.0× (75% savings) on high-concurrency LLM serving clusters.
import torch
import torch.nn as nn
import torch.nn.functional as F
class GroupedQueryAttention(nn.Module):
"""GQA sharing num_kv_heads across num_q_heads groups to compress KV-cache VRAM."""
def __init__(self, d_model: int = 256, num_q_heads: int = 8, num_kv_heads: int = 2):
super().__init__()
self.num_q_heads = num_q_heads
self.num_kv_heads = num_kv_heads
self.head_dim = d_model // num_q_heads
self.group_size = num_q_heads // num_kv_heads
self.q_proj = nn.Linear(d_model, num_q_heads * self.head_dim, bias=False)
self.k_proj = nn.Linear(d_model, num_kv_heads * self.head_dim, bias=False)
self.v_proj = nn.Linear(d_model, num_kv_heads * self.head_dim, bias=False)
self.o_proj = nn.Linear(d_model, d_model, bias=False)
def forward(self, x: torch.Tensor):
B, L, _ = x.shape
q = self.q_proj(x).view(B, L, self.num_q_heads, self.head_dim).transpose(1, 2)
k_cache = self.k_proj(x).view(B, L, self.num_kv_heads, self.head_dim).transpose(1, 2)
v_cache = self.v_proj(x).view(B, L, self.num_kv_heads, self.head_dim).transpose(1, 2)
# Broadcast 2 KV heads to match 8 Q heads without duplicating physical KV-cache storage
k_expanded = k_cache.repeat_interleave(self.group_size, dim=1)
v_expanded = v_cache.repeat_interleave(self.group_size, dim=1)
out = F.scaled_dot_product_attention(q, k_expanded, v_expanded, is_causal=True)
out = out.transpose(1, 2).contiguous().view(B, L, -1)
return self.o_proj(out), k_cache
gqa = GroupedQueryAttention(d_model=256, num_q_heads=8, num_kv_heads=2)
tokens = torch.randn(4, 1024, 256)
out, k_kv = gqa(tokens)
mha_kv_mb = (2 * 4 * 8 * 1024 * 32 * 2) / (1024 ** 2) # FP16 K+V for 8 heads
gqa_kv_mb = (2 * 4 * 2 * 1024 * 32 * 2) / (1024 ** 2) # FP16 K+V for 2 heads
print("GQA Output & Physical K-Cache Shape:", tuple(out.shape), "|", tuple(k_kv.shape))
print(f"FP16 KV-Cache VRAM (MHA vs GQA) : {mha_kv_mb:.2f} MB -> {gqa_kv_mb:.2f} MB ({mha_kv_mb / gqa_kv_mb:.1f}x Compression!)")
Output: GQA Output & Physical K-Cache Shape: (4, 1024, 256) | (4, 2, 1024, 32) FP16 KV-Cache VRAM (MHA vs GQA) : 2.00 MB -> 0.50 MB (4.0x Compression!)
O(N·W) Scaling on 24-Hour ECG Telemetry)
0 <= i - j <= window_size) so each heartbeat sample in a continuous 24-hour ECG telemetry stream attends exclusively to its W = 3 most recent cardiac cycles—slashing active attention pairs from dense quadratic N² to sparse linear O(N·W) complexity.
import torch
import torch.nn.functional as F
def build_causal_sliding_window_mask(seq_len: int, window_size: int) -> torch.Tensor:
"""Allows token i to attend only to j where 0 <= i - j <= window_size."""
idx = torch.arange(seq_len)
dist = idx.unsqueeze(1) - idx.unsqueeze(0) # dist[i, j] = i - j
allowed = (dist >= 0) & (dist <= window_size)
return allowed
SEQ_LEN, WIN = 8, 2
allowed_mask = build_causal_sliding_window_mask(SEQ_LEN, window_size=WIN)
q = torch.randn(1, 4, SEQ_LEN, 16)
k = torch.randn(1, 4, SEQ_LEN, 16)
v = torch.randn(1, 4, SEQ_LEN, 16)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=allowed_mask)
dense_pairs = SEQ_LEN * SEQ_LEN
active_pairs = int(allowed_mask.sum().item())
sparsity_pct = (1.0 - active_pairs / dense_pairs) * 100.0
print(f"Banded Mask (N={SEQ_LEN}, W={WIN}) -> Active Pairs: {active_pairs}/{dense_pairs} ({sparsity_pct:.1f}% Masked)")
print("Row 5 Allowed Keys (0..7) :", allowed_mask[5].int().tolist())
print("ECG Sliding-Window Output :", tuple(out.shape))
Output: Banded Mask (N=8, W=2) -> Active Pairs: 21/64 (67.2% Masked) Row 5 Allowed Keys (0..7) : [0, 0, 0, 1, 1, 1, 0, 0] ECG Sliding-Window Output : (1, 4, 8, 16)
0.5 · A^(l) + 0.5 · I, row-normalizing, and multiplying recursively across layers R = Â^(3) · Â^(2) · Â^(1) to quantify how strongly the [CLS] decision token attributes fraud risk to each transaction field.
import torch
def compute_attention_rollout(layer_attns: list[torch.Tensor]) -> torch.Tensor:
"""Aggregates multi-layer [Heads, L, L] attention maps accounting for residual connections."""
seq_len = layer_attns[0].size(-1)
eye = torch.eye(seq_len, device=layer_attns[0].device)
rollout = eye.clone()
for attn_heads in layer_attns:
# 1. Average across attention heads -> [L, L]
avg_attn = attn_heads.mean(dim=0)
# 2. Account for residual skip stream: A_hat = 0.5 * A + 0.5 * I
residual_attn = 0.5 * avg_attn + 0.5 * eye
# 3. Row-normalize and compose recursively across depth
residual_attn = residual_attn / residual_attn.sum(dim=-1, keepdim=True)
rollout = residual_attn @ rollout
return rollout
torch.manual_seed(42)
fields = ["[CLS]", "merchant_id", "foreign_ip", "amount_$9800", "device_new"]
# Simulate 3 Transformer layers of shape [NumHeads=4, SeqLen=5, SeqLen=5]
# Layer 2 & 3 attend strongly to token 2 ('foreign_ip') and token 3 ('amount_$9800')
layers = []
for l in range(3):
raw = torch.rand(4, 5, 5) * 0.2
raw[:, :, 2] += 1.4 # foreign_ip signal
raw[:, :, 3] += 1.8 # high dollar amount signal
layers.append(torch.softmax(raw, dim=-1))
rollout_matrix = compute_attention_rollout(layers)
cls_attribution = rollout_matrix[0] # How much [CLS] relies on each input field
print("Audited [CLS] Token Attribution Scores:")
for name, score in zip(fields, cls_attribution.tolist()):
print(f" Field '{name:<13}' -> Attribution Weight: {score * 100:5.1f}%")
Output: Audited [CLS] Token Attribution Scores: Field '[CLS] ' -> Attribution Weight: 19.8% Field 'merchant_id ' -> Attribution Weight: 10.9% Field 'foreign_ip ' -> Attribution Weight: 26.4% Field 'amount_$9800 ' -> Attribution Weight: 32.1% Field 'device_new ' -> Attribution Weight: 10.8%