Building every major attention mechanism from scratch in PyTorch
Introduction
Scaled dot-product attention — softmax(Q @ K.T / sqrt(d_k)) @ V — shipped in 2017 and every LLM since runs on variants of it. The equation stayed the same; the bottlenecks changed. KV cache explodes with long contexts, quadratic cost kills throughput, training becomes unstable at 8B+ scale.
Six efficiency variants solve these bottlenecks: GQA , MLA , SWA , NSA , Gated Attention , and Hybrid Attention . Each modifies the four foundation mechanisms — Self-Attention, MHA, Causal, and Cross-Attention — covered in the previous post .
Same running example throughout: "The CEO announced record earnings on Friday" — 7 tokens, d_model = 64 .
Quick Recap: The Four Foundations
Full deep-dive with implementations in the previous post . Here's what you need to follow the variants:
Self-Attention — softmax(Q @ K.T / sqrt(d_k)) @ V . Project each token into Q, K, V, compute pairwise relevance, weighted sum of values.…