25 — Deep Learning

Attention Mechanism#

ArchitectureMathematical
◆ The PatternSelectively focusing on relevant parts of the input

Each token asks: "which other tokens are most relevant to me?" via dot-product similarity between queries and keys.

Attention(Q,K,V) = softmax(QKᵀ / √d) · V
Q = Query  |  K = Key  |  V = Value  |  √d = scaling to prevent saturation
// Attention heatmap — click cells to boost connections
Click cells to strengthen
Multi-Head Attention: Run h attention functions in parallel, each with different learned projections. Allows attending to syntax, semantics, and coreference simultaneously.
Pattern bridge: Selectively weighting inputs by relevance appears in VWAP (volume-weighted attention to price) and transformer self-attention.
Worked example

One query and ten keys of dimension 512. Without scaling, the dot products are large and the softmax puts 99.6% of the weight on a single key — attention becomes a hard lookup with almost no gradient for the rest. Dividing by √512 brings the largest weight down to 21%. The √d in the formula is there for exactly this reason.

Where it misleads
  • Attention weights are not explanations; high weight on a token does not mean it caused the output.
  • Full attention costs grow with the square of the sequence length.
  • Attention has no sense of order by itself; position encodings supply it.
In code
rng = np.random.default_rng(6)
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
d = 512
q, K = rng.normal(size=d), rng.normal(size=(10, d))   # one query, ten keys
raw = softmax(K @ q).max()                             # unscaled scores grow with sqrt(d)
scaled = softmax(K @ q / np.sqrt(d)).max()
Python, in your browser — edit the code and run it again

Assumes import numpy as np. Each snippet carries its own example numbers; the comments say which are made up or simulated.

Sources
  • A. Vaswani et al., “Attention Is All You Need”, NeurIPS, 2017
  • D. Bahdanau, K. Cho & Y. Bengio, “Neural Machine Translation by Jointly Learning to Align and Translate”, ICLR, 2015
  • S. Jain & B. C. Wallace, “Attention Is Not Explanation”, NAACL, 2019

Last reviewed October 2026 · How this site checks its content · Report a mistake

Linked from 4
← Previous
Embeddings
Open in the full reader, with the topic sidebar