NeuroGenesys.
Transformers & Language ModelsAcademy • Frontier • Lesson 2 of 4

Attention from first principles

8 min read • By Will Schulz • NeuroGenesys AI Academy

Attention is how a transformer lets each token look up information from other tokens: a soft, differentiable lookup table built fresh for every input. This lesson derives the mechanism, explains its quadratic cost and its memory footprint at inference, and surveys how 2025–2026 models changed it to reach million-token contexts.

The problem attention solved

Early neural translation systems compressed an entire source sentence into one fixed-length vector before decoding. Bahdanau, Cho and Bengio saw that this vector was a bottleneck, and that it hurt most on long sentences. Their fix let the decoder, at every output step, compute a weighted average over all encoder states. The weights came from a learned score of how relevant each source position was.[1] Vaswani et al. then made that operation the whole architecture, with no recurrence and no convolution, in "Attention Is All You Need".[2]

Scaled dot-product attention

Each token's vector xix_i is projected three ways: a query qi=WQxiq_i = W_Q x_i (what am I looking for?), a key kj=WKxjk_j = W_K x_j (what do I contain?) and a value vj=WVxjv_j = W_V x_j (what do I hand over if selected?). Stack them into matrices Q,K,VQ, K, V. Then:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V.\mathrm{Attention}(Q,K,V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V .

Row ii of the softmax is a probability distribution over positions jj, and the output for token ii is the average of the values under that distribution. The match score is a dot product, so keys pointing in the query's direction get the most weight.

Why divide by dk\sqrt{d_k}? If the components of qq and kk are independent with mean 0 and variance 1, then q⋅k=∑m=1dkqmkmq\cdot k=\sum_{m=1}^{d_k} q_m k_m is a sum of dkd_k terms each with variance 1, so its variance is dkd_k. Without scaling, logits for dk=128d_k=128 would have a standard deviation of about 11. The softmax would then saturate to nearly one-hot, and its gradients would vanish. Dividing by dk\sqrt{d_k} brings the variance back to 1.[2]

Worked example. Let dk=2d_k=2, query q=(1,0)q=(1,0), keys k1=(1,0)k_1=(1,0), k2=(0,1)k_2=(0,1), k3=(−1,0)k_3=(-1,0) and scalar values v=(10,20,30)v=(10,20,30). The scaled scores are q⋅kj/2=(0.707, 0, −0.707)q\cdot k_j/\sqrt2 = (0.707,\,0,\,-0.707). Exponentiating gives (2.028, 1, 0.493)(2.028,\,1,\,0.493), which sum to 3.5213.521, so the weights are (0.576, 0.284, 0.140)(0.576,\,0.284,\,0.140). The output is

0.576⋅10+0.284⋅20+0.140⋅30≈15.6.0.576\cdot10 + 0.284\cdot20 + 0.140\cdot30 \approx 15.6 .

The value whose key matches best dominates, but every position contributes. That softness is what makes the lookup differentiable.

Heads and masks

Multi-head attention runs hh of these in parallel, each with its own smaller projections (dk=dmodel/hd_k = d_{\text{model}}/h). It concatenates the results and projects them back, so different heads can track different relations: syntax, coreference, copying.[2] For language modelling, a causal mask sets the score to −∞-\infty wherever j>ij>i, so no token can attend to the future. That is what makes next-token training parallel.

Position has to be added

Attention as written is permutation-equivariant: shuffle the tokens and the outputs shuffle the same way. Word order has to be injected. Most current models use rotary position embeddings (RoPE). RoPE rotates each pair of query and key coordinates by an angle proportional to the token's position, so the dot product between positions mm and nn depends only on the offset m−nm-n.[3] Llama 3 uses RoPE with base frequency θ=500,000\theta = 500{,}000, a setting chosen to support long contexts.[4]

Check your understanding

Why does rotating both qmq_m and knk_n by position-dependent angles make their dot product depend only on m−nm-n?

Show answer +

A rotation RϕR_\phi is orthogonal, so (Rmωq)⋅(Rnωk)=q⊤Rmω⊤Rnωk=q⊤R(n−m)ωk(R_{m\omega}q)\cdot(R_{n\omega}k) = q^\top R_{m\omega}^\top R_{n\omega}k = q^\top R_{(n-m)\omega}k. The absolute angles cancel and only the relative angle survives.

What attention costs

For a sequence of length nn, the score matrix QK⊤QK^\top has n2n^2 entries per head per layer. At n=128,000n=128{,}000 that is about 1.6×10101.6\times10^{10} scores. Compute grows as O(n2d)O(n^2 d). A naive implementation also writes the n×nn\times n matrix to GPU memory, and on modern accelerators that traffic, not the arithmetic, is the bottleneck. FlashAttention computes exact attention in tiles that stay in on-chip SRAM, using an online softmax, so the full matrix never reaches high-bandwidth memory. The original paper proved the IO savings and reported large wall-clock speedups.[5] FlashAttention-3 reached up to 740 TFLOP/s in FP16 on an H100, about 75% of peak.[6] These kernels change constants and memory traffic. They do not change the O(n2)O(n^2) arithmetic.

The KV cache, and sharing heads

During generation, each new token needs the keys and values of every earlier token. Recomputing them would be wasteful, so they are stored in a KV cache. Its size per token is

bytes/token=2×L×hkv×dhead×b,\text{bytes/token} = 2 \times L \times h_{kv} \times d_{\text{head}} \times b ,

where the factor 2 counts K and V, LL is the number of layers, hkvh_{kv} the number of key/value heads and bb the bytes per number.

Worked example: Llama 3 70B. It has 80 layers, 64 query heads, 8 key/value heads and dhead=8192/64=128d_{\text{head}} = 8192/64 = 128.[4] In 16-bit precision:

2×80×8×128×2=327,680 bytes≈0.33 MB per token.2\times 80\times 8\times128\times 2 = 327{,}680 \text{ bytes} \approx 0.33\text{ MB per token}.

A single 128k-token context therefore needs about 43 GB of cache. If every one of the 64 heads kept its own K and V, as in the original design, it would need 8× that, about 343 GB.

The saving comes from grouped-query attention (GQA). Shazeer first proposed multi-query attention, in which all heads share one K/V head, because incremental decoding was limited by the memory bandwidth spent reloading keys and values.[7] GQA generalizes this: groups of query heads share a K/V head. Its authors reported quality close to full multi-head attention at speed close to multi-query.[8] DeepSeek-V2 went further with multi-head latent attention (MLA), which caches a compressed latent vector and reconstructs K and V from it. It reported a 93.3% smaller KV cache than DeepSeek 67B.[9] Inference economics explains why bytes in this cache translate directly into cost.

Check your understanding

A model has 32 layers, 8 KV heads and head dimension 128, and stores its cache in FP8 (1 byte). How much KV cache does a batch of 16 sequences of 32,768 tokens need?

Show answer +

Per token: 2×32×8×128×1=65,5362\times32\times8\times128\times1 = 65{,}536 bytes. Total tokens: 16×32,768=524,28816\times32{,}768 = 524{,}288. Cache =65,536×524,288≈3.4×1010= 65{,}536\times524{,}288 \approx 3.4\times10^{10} bytes, about 34 GB.

How attention changed in 2025–2026

As of November 2026, long-context frontier models rarely run plain dense attention in every layer. Four trends stand out.

  • Sparse attention. DeepSeek-V3.2 added DeepSeek Sparse Attention: a small, cheap "lightning indexer" scores earlier tokens, and each query attends only to a selected subset. The report says this reduces long-context cost while preserving quality.[10] DeepSeek-V4-Pro (2026) combines two compressed attention variants. Its model card reports that at one million tokens it needs 27% of the per-token inference FLOPs and 10% of the KV cache of V3.2.[11]
  • Linear-attention hybrids. These replace most attention layers with recurrent layers that keep a fixed-size state. Kimi Linear interleaves three "Kimi Delta Attention" layers per full-attention (MLA) layer. It reports up to 75% less KV cache and up to 6.3× faster decoding at 1M context than full MLA.[12] Qwen3-Next uses a similar 3:1 mix of Gated DeltaNet and gated attention.[13]
  • Gating the output. Qwen researchers showed that a sigmoid gate after the attention output improves training stability and long-context extrapolation. It also largely removes the "attention sink", in which heads park weight on the first token. The share of attention on the first token fell from 46.7% to 4.8% in their models.[14] The paper won a NeurIPS 2025 best paper award.[15]
  • Advertised vs usable context. The RULER benchmark found that most models claiming 32k-token or longer windows degraded well before their nominal limit on tasks harder than simple retrieval.[16] A context window is a capacity, not a guarantee of use.

Key takeaways

  • Attention is a softmax-weighted average of values, with weights from query–key dot products scaled by dk\sqrt{d_k} to keep logits at unit variance.
  • It has no built-in notion of order. RoPE supplies relative position through rotations.
  • Cost is quadratic in sequence length. FlashAttention makes it IO-efficient but does not change the asymptotics.
  • At inference the KV cache dominates memory. GQA, MQA and MLA shrink it by sharing or compressing keys and values.
  • Frontier designs as of 2026 mix full attention with sparse, compressed or linear-recurrent layers to make million-token contexts affordable.

Sources

  1. D. Bahdanau, K. Cho and Y. Bengio (2014). "Neural Machine Translation by Jointly Learning to Align and Translate." ICLR 2015. arXiv:1409.0473. https://arxiv.org/abs/1409.0473 ↩

  2. A. Vaswani, N. Shazeer, N. Parmar et al. (2017). "Attention Is All You Need." NeurIPS 2017. arXiv:1706.03762. https://arxiv.org/abs/1706.03762 ↩ ↩2 ↩3

  3. J. Su, Y. Lu, S. Pan, A. Murtadha, B. Wen and Y. Liu (2021). "RoFormer: Enhanced Transformer with Rotary Position Embedding." arXiv:2104.09864. https://arxiv.org/abs/2104.09864 ↩

  4. Llama Team, AI @ Meta (2024). "The Llama 3 Herd of Models." arXiv:2407.21783. https://arxiv.org/abs/2407.21783 ↩ ↩2

  5. T. Dao, D. Y. Fu, S. Ermon, A. Rudra and C. Ré (2022). "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness." arXiv:2205.14135. https://arxiv.org/abs/2205.14135 ↩

  6. J. Shah, G. Bikshandi, Y. Zhang, V. Thakkar, P. Ramani and T. Dao (2024). "FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision." arXiv:2407.08608. https://arxiv.org/abs/2407.08608 ↩

  7. N. Shazeer (2019). "Fast Transformer Decoding: One Write-Head is All You Need." arXiv:1911.02150. https://arxiv.org/abs/1911.02150 ↩

  8. J. Ainslie, J. Lee-Thorp, M. de Jong, Y. Zemlyanskiy, F. Lebrón and S. Sanghai (2023). "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints." arXiv:2305.13245. https://arxiv.org/abs/2305.13245 ↩

  9. DeepSeek-AI (2024). "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model." arXiv:2405.04434. https://arxiv.org/abs/2405.04434 ↩

  10. DeepSeek-AI (2025). "DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models." arXiv:2512.02556. https://arxiv.org/abs/2512.02556 ↩

  11. DeepSeek-AI (2026). "DeepSeek-V4-Pro" model card. Hugging Face. https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro ↩

  12. Kimi Team (2025). "Kimi Linear: An Expressive, Efficient Attention Architecture." arXiv:2510.26692. https://arxiv.org/abs/2510.26692 ↩

  13. Qwen Team (2025). "Qwen3-Next-80B-A3B-Thinking" model card. Hugging Face. https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Thinking ↩

  14. Z. Qiu et al. (2025). "Gated Attention for Large Language Models: Non-linearity, Sparsity, and Attention-Sink-Free." arXiv:2505.06708. https://arxiv.org/abs/2505.06708 ↩

  15. NeurIPS (2025). "Announcing the NeurIPS 2025 Best Paper Awards." https://blog.neurips.cc/?p=1443 ↩

  16. C.-P. Hsieh et al. (2024). "RULER: What's the Real Context Size of Your Long-Context Language Models?" COLM 2024. arXiv:2404.06654. https://arxiv.org/abs/2404.06654 ↩

Leadership

A word from the founder — on why the brain is the blueprint, and why the next decade of intelligence will be built here.

"The brain is the universe's only proof that general intelligence is possible. We treat it as the blueprint."

From cortical interfaces to photonic silicon, every program at NeuroGenesys exists to answer one question: how does intelligence arise — and how do we build it safely.

Will Schulz

Will Schulz

Founder, NeuroGenesys • AW3 Technology