Grimoire
Sheet
patharchitectures/attention
difficultyintermediate
timeO(n²·d)
memoryO(n²)
described2017
revised4d ago

Scaled Dot-Product Attention

Content-based retrieval over a set of key–value pairs, with logits scaled by 1/√dk to keep softmax gradients out of saturation.

Theory

Given queries QRn×dkQ \in \R^{n \times d_k}, keys KRm×dkK \in \R^{m \times d_k} and values VRm×dvV \in \R^{m \times d_v}, attention returns a convex combination of value rows weighted by query–key similarity.

Attention(Q,K,V)=softmax ⁣(QKdk)V\mathrm{Attention}(Q, K, V) = \softmax\!\left( \frac{QK^{\top}}{\sqrt{d_k}} \right) V
eq. 1 — row-wise softmaxVaswani et al. §3.2.1

Why 1/dk1/\sqrt{d_k}

If qq and kk have i.i.d. components with zero mean and unit variance, their dot product has variance dkd_k. Unscaled logits therefore grow with dimension, pushing the softmax toward one-hot and its Jacobian toward zero.

Var[qk]=i=1dkVar[qiki]=dk\Var[\, q \cdot k \,] = \sum_{i=1}^{d_k} \Var[\, q_i k_i \,] = d_k
eq. 2

Gradient

Writing A=softmax(S)A = \softmax(S) with S=QK/dkS = QK^{\top}/\sqrt{d_k}, the backward pass through the softmax takes the usual diagonal-minus-outer-product form, applied per row.

LSi=(diag(ai)aiai)Lai\frac{\partial L}{\partial S_i} = \bigl( \diag(a_i) - a_i a_i^{\top} \bigr) \frac{\partial L}{\partial a_i}
eq. 3

The n2n^2 term is materialisation, not arithmetic necessity — see flash-attention for the tiled formulation with O(n)O(n) memory.

Implementation
python · torch ≥ 2.1
import math
import torch
from torch import Tensor


def attention(
    q: Tensor, k: Tensor, v: Tensor,   # [B, H, N, D]
    mask: Tensor | None = None,
    dropout_p: float = 0.0,
) -> Tensor:
    scale = 1.0 / math.sqrt(q.size(-1))
    logits = (q * scale) @ k.transpose(-2, -1)

    if mask is not None:
        logits = logits.masked_fill(mask, -6e4)

    attn = logits.softmax(dim=-1)
    if dropout_p > 0.0:
        attn = torch.dropout(attn, dropout_p, train=True)
    return attn @ v

Fold the scale into the query before the matmul when running fp16 — scaling after the product overflows for large dkd_k. A fully masked row yields NaN under -\infty, so mask with a large negative constant instead when rows can be empty.

FLOPs
4.3 G
Attn matrix
32 MB
vs flash
0.4 MB
measured at n = 4096, d = 128, fp16
Related
References
[1]Vaswani et al. — Attention Is All You Need (2017)arXiv:1706.03762
[2]Dao et al. — FlashAttention: Fast and Memory-Efficient Exact Attention (2022)arXiv:2205.14135
[3]Elhage et al. — A Mathematical Framework for Transformer Circuits (2021)transformer-circuits
[4]Press et al. — Train Short, Test Long: ALiBi (2021)arXiv:2108.12409