Derive Attention from Content-Based Routing
Attention turns each query into a bounded routing distribution over compatible keys, then transports the corresponding values.
- Authorship
- InterviewsVector
- Published / updated
- 2026-08-25 / 2026-08-25
- Review status
- Artifact tests passing · primary sources recorded
Original InterviewsVector material. Code examples are covered by repository tests and primary references are recorded. No named human reviewer is claimed.
The decision in one pass
Scaled dot-product attention is content-based routing. Each query describes what one output position requests; keys expose addresses that can satisfy that request; values carry the payload. Compute query-key compatibility, divide by the square root of the key dimension, apply the declared mask, normalize each visible row with a stable softmax, then take the weighted sum of values. Shapes, position identities, Q/K/V semantics, scaling, and mask convention are part of the contract. A large attention weight is routing evidence inside one layer—not a causal explanation, calibrated probability, or complete account of model behavior.
Why this matters
Many transformer failures that look mysterious reduce to ordinary routing defects: transposed axes, a mask with the wrong polarity, scale omitted, padding made visible, Q and K from different revisions, or a numerically unstable softmax. Deriving the operation from its contract makes these failures testable.
You will be able to
- Derive Q, K, and V roles from content-addressed routing rather than memorizing a formula.
- Trace tensor shapes from compatibility scores through weights and routed contexts.
- Explain the square-root scale, causal mask ordering, and stable softmax implementation.
- Build an audit binding Q/K/V semantics, positions, shapes, model revision, provenance, and material outputs.
- Defend what attention weights show and what they cannot establish about causality or importance.
Your Vector Loop for this lab
- 01
Model
Name output requests, addressable content, payloads, axes, positions, mask, scale, and model revision.
- 02
Derive
Derive compatibility, masked row normalization, and weighted value transport with explicit shapes.
- 03
Build
Capture bounded Q/K/V evidence and compute stable scaled dot-product routing.
- 04
Stress
Probe shape swaps, stale projections, all-masked rows, mask polarity, extreme logits, padding, and numeric resolution.
- 05
Operate
Trace routing distributions and contexts by layer, head, position, and content identity with controlled sampling.
- 06
Defend
Separate observed routing from causal influence, semantic explanation, confidence, and end-to-end quality.
Model attention as requests, addresses, and payloads
For every output position, a query vector expresses a learned request. Each candidate source position offers a key used for compatibility and a value used as payload. Query-key similarity chooses a routing mixture; it is the values—not the keys—that are combined into the context. This vocabulary exposes common bugs more clearly than saying a token simply ‘looks at’ another token.
| Tensor | Routing role | Identity that must be bound |
|---|---|---|
| Q | requests per output position | projection, layer, head, position, feature basis |
| K | addresses per source position | projection, source sequence, position, feature basis |
| V | payloads per source position | projection, source sequence, position, value basis |
| mask | eligible routing edges | causal/padding convention and polarity |
| context | weighted payload result | complete input and routing-policy identities |
Let the shapes prove the routing path
Q[nq, dk] · K[nk, dk]ᵀ → S[nq, nk]; softmax(S) · V[nk, dv] → C[nq, dv]
The inner key dimension must match. Scores relate each query to every eligible key. The key-count axis then contracts against the value rows, leaving one dv-dimensional context per query.
Axis names are stronger than raw dimensions. A square score matrix can survive an accidental transpose, and equal Q/K/V widths can hide a semantic swap. Tests should use unequal query and key counts when possible, retain position IDs, and include a fixture whose expected direction is obvious.
- 01Project in one model revisionBind Q, K, and V projection contents, layer/head identity, source sequence, and feature semantics.
- 02Score only matching key dimensionsReject broadcasting or reshaping that changes which coordinates form each dot product.
- 03Route values over the key axisThe score row length and value row count must match exactly before weighted summation.
Scale logits and mask edges before normalization
A = softmax((QKᵀ / √dk) + M); C = AV
For a causal decoder, M excludes keys whose position is greater than the query position. Masked edges must receive exactly zero normalized weight and at least one edge must remain visible in every row.
If independent query and key coordinates have roughly unit variance, their dot-product variance grows with dk. Dividing by √dk controls that scale before softmax. It is not an arbitrary temperature knob: changing or omitting it changes the bound attention function and should change the contract identity.
Normalize each visible row stably
softmax(s)i = exp(si − max(s)) / Σj exp(sj − max(s))
Subtracting the row maximum leaves the distribution unchanged while preventing a large positive logit from overflowing exp. The denominator remains positive because the maximum term contributes one.
A production kernel may tile the computation and avoid materializing the full score matrix, yet exact implementations must preserve the same masking, scaling, and normalization semantics. Compare outputs within a declared numeric envelope and retain the kernel, dtype, and accumulation policy alongside evidence.
| Check | Failure detected | Bounded response |
|---|---|---|
| finite Q/K/V | NaN or infinity enters arithmetic | reject at capture |
| logit envelope | unsupported magnitude or resolution | hold before exponentiation |
| row sum ≈ 1 | mask/normalizer defect | fail the routing audit |
| masked weight = 0 | future or padding visibility | block release |
| context fixture | wrong value axis | compare a hand-derived case |
Predict the maximum-routed token
The laboratory uses a bounded two-dimensional fixture. Apply position visibility, compare the scaled query-key scores, and predict the key with maximum normalized weight before the distribution is revealed. The grade tests routing arithmetic, not whether a learned model has discovered a useful feature.
Attention routing laboratory
Inspect a bounded Q/K routing fixture, predict which token receives maximum weight, then reveal the masked scaled-softmax weights and graded result.
Route one query from bounded Q/K evidence
Inspect a two-dimensional query and four keys. Predict the route with the maximum scaled dot-product score, q · k / √2. Candidate routes stay visually equal until you check.
Routing rule
Compute one dot product per key. Dividing by the common √2 scale changes magnitude, not rank; no mask or bias is applied in this bounded exercise.
| Vector | First dimension | Second dimension | Score |
|---|---|---|---|
| Q | 2 | 1 | — |
| K1 | 1 | 0 | withheld |
| K2 | 0 | 1 | withheld |
| K3 | 1 | 1 | withheld |
| K4 | -1 | 2 | withheld |
Values are illustrative and intentionally small enough to audit by hand. The diagram shows candidate connectivity, not a measured production attention map.
Make a prediction, then check it against the current evidence.
Capture material routing evidence
The reference artifact binds Q/K/V meanings and shapes, model and source revisions, ordered positions, causal-mask equality, square-root scaling, stable-softmax convention, numeric resolution, bounds, scope, and owners. Concrete frozen evidence is reconstructed at the public boundary. The material digest covers every weight and context, so the decision is reproducible rather than a detached PASS label.
1def format_example() -> str:2 report = audit_attention(ILLUSTRATIVE_CONTRACT, ILLUSTRATIVE_EVIDENCE)3 return "\n".join(4 (5 "example=illustrative_only",6 f"contract_id={report.contract_content_id}",7 f"evidence_id={report.evidence_content_id}",8 f"mask={report.mask_semantics}",9 f"query0_weights={','.join(f'{value:.3f}' for value in report.weights[0])}",10 f"query1_weights={','.join(f'{value:.3f}' for value in report.weights[1])}",11 f"query1_context={','.join(f'{value:.3f}' for value in report.contexts[1])}",12 f"material_id={report.material_evidence_id}",13 f"decision={report.decision}",14 )15 )Expected output
example=illustrative_only
contract_id=attention-contract@sha256:63e4c3c48a6507eb11d35f8a3a47b63b79ecb63ea80eca8d0447733d5a6399d9
evidence_id=attention-evidence@sha256:16a3bf685c8a4d8318cabfcff6be1833bbbb20e0f873f3f8b4e7efdc0d439f55
mask=causal-key-position-lte-query-position-v1
query0_weights=1.000,0.000
query1_weights=0.330,0.670
query1_context=3.302,13.395
material_id=attention-material@sha256:f859dd199d6659edef1507c4e2a13d95dcc8cd71397222fd9869d6b3da282b3b
decision=PASSVerify: python3 -m unittest discover courses/ai-engineering/reference-impl/attention_routing
Operate the routing boundary, not a heatmap
| Symptom | First contract check | Next evidence |
|---|---|---|
| future-token leakage | causal positions and mask polarity | known prefix invariance test |
| uniform rows | Q/K scale and projection revision | logit variance by layer/head |
| one-hot rows | scale, dtype, and extreme logits | pre-softmax range and gradient trace |
| wrong output shape | key/value row alignment | named-axis fixture |
| kernel mismatch | mask/scale/accumulation semantics | reference-versus-kernel bounded comparison |
Sample routing traces because full attention is quadratic in sequence length and can expose sensitive inputs. Prefer aggregate health signals by layer and request cohort, then capture a bounded redacted replay when an incident gate fires. The trace must include model, tokenizer, sequence, mask, kernel, precision, and evidence identities.
Operate at three altitudes
Production lens
- — Bind Q/K/V projection revisions, named axes, token positions, mask semantics, scale, dtype, kernel, and source evidence in routing traces.
- — Use stable row normalization and reject all-masked rows, non-finite inputs, unsupported magnitudes, and future-token visibility.
- — Sample or aggregate attention observability to control quadratic cost and sensitive-content exposure.
- — Compare optimized kernels against a bounded reference contract before interpreting performance gains as equivalence.
Staff lens
- — Standardize named tensor axes and mask polarity across training, inference, caching, compilation, and incident tooling.
- — Treat attention visualization as diagnostic evidence with privacy, sampling, and interpretation limits—not a default explanation product.
- — Require model and kernel releases to state whether they preserve exact routing semantics or introduce an approximation requiring fresh evaluation.
Interview defense
Derive scaled dot-product attention from a routing problem.
Each output position has a query describing what it requests. Source positions expose keys for compatibility and values as payload. QK transpose produces one score per query-key pair; divide by square root of dk to control dot-product scale, mask ineligible edges before normalization, apply a row-wise max-shift softmax, then multiply by V to route a weighted payload. I would bind named shapes, positions, projections, mask and scale semantics, reject invalid rows and numerics, and test a hand-derived fixture. The weights are an internal routing trace, not automatically a causal explanation.
Expect the interviewer to press on
- — Why are K and V required to have the same sequence length?
- — Why is the causal mask applied before softmax?
- — How can an optimized exact attention kernel avoid storing the full score matrix?
Misconceptions to remove
“Attention weights are probabilities that a token is important.”
They are normalized routing coefficients for values inside one operation. Importance, causality, and confidence require separate evidence.
“The mask can be applied after softmax by zeroing forbidden entries.”
Post-hoc zeroing loses row normalization unless weights are renormalized and makes it easier to leak or mis-handle ineligible edges. Define eligibility before normalization.
“FlashAttention is approximate attention.”
The primary FlashAttention algorithm is exact attention with IO-aware tiling; block-sparse variants are a separate approximation.
Check your model
1. Why must query and key dimensions match while value dimension may differ?
Each query-key compatibility is a dot product over their shared coordinate dimension. The resulting key weights then combine value rows into whatever payload dimension V declares.
2. What does subtracting the largest row logit change?
It changes no softmax ratio because every numerator and denominator receives the same factor, while preventing large positive exponentials from overflowing.
3. What does a high attention weight establish?
Only that this operation assigned a large routing coefficient to that value for this query under the bound model, mask, and evidence. It does not alone establish causal influence or semantic importance.
Prove the mechanism
Extend the artifact with explicit padding eligibility while keeping causal position semantics. Add fixtures proving padded and future keys receive zero weight and every valid row sums to one.
Add a production constraint
Implement a tiled online-softmax version that does not materialize the score matrix. Prove bounded equivalence to the reference across adversarial shapes, masks, and logit ranges.
Artifact: Attention routing audit
courses/ai-engineering/reference-impl/attention_routing/attention_routing_audit.py
Download reference implementationPrimary references and next links
References
- 1. Neural Machine Translation by Jointly Learning to Align and Translate
Bahdanau, Cho, and Bengio. Primary work framing learned soft alignment for neural sequence transduction.
- 2. Attention Is All You Need
Vaswani et al.. Primary source for scaled dot-product and multi-head attention in the Transformer.
- 3. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
Dao et al.. Primary paper on exact IO-aware tiled attention.
Continue through the graph
- Numerical Stability Is an API Contract →
Ground stable softmax in explicit numeric contracts.
- Multi-Head Attention Is Parallel Representation Routing →
Extend one routing operation into multiple learned subspaces.
- KV-cache capacity planning →
Connect K/V shapes to persistent decode state.
Glossary: query · key · value · scaled dot-product attention · causal mask · stable softmax