ML / FIELD NOTES
Machine learning / The mechanism, the math, the interview
01 / A

Attention.

From a weighted average
to the questions that go deeper.

A first-principles field manual for understanding, implementing, and defending attention. Build the intuition, derive the equations, then pressure-test your answers.

120 questions with follow-upsWorked math + runnable PythonSenior ML / Applied Science
00 / Study route map

Your interview route map

Attention is a learned, query-dependent weighted sum. Everything else follows from asking: how do we score candidates, how do we normalize scores, what information do we mix, and what does it cost?

This field manual takes you from scalar arithmetic to systems design. It assumes basic Python and introduces the linear algebra and probability it uses. It targets ML and applied-scientist interviews, including senior follow-ups. No finite guide covers every possible interview question. The goal is coverage of the major reasoning patterns, not memorizing an alleged exhaustive list.

If you have…Study in this orderYou should be able to do…
90 minutesFirst principles → Worked example → Recall sheet → Core questionsExplain Q/K/V, derive shapes and scaling, draw a causal mask, distinguish training from generation.
One dayAdd derivations, architecture, code, efficiency, then one mock.Implement attention, defend numerical choices, calculate memory, diagnose cache bugs.
One weekRead all chapters, answer the question bank aloud, implement without looking, complete all mocks.Handle mechanism, research critique, and production trade-offs under follow-up questions.

The answer structure that survives follow-ups

Definition → mechanism → equation and shapes → assumptions → trade-off → test. For example: “FlashAttention evaluates the same dense softmax attention operator. It tiles Q/K/V and uses an online softmax so the full score matrix need not be stored in GPU high-bandwidth memory. Arithmetic remains quadratic in context length. I would check output and gradient parity, then benchmark prefill and decode separately.” That is stronger than “it makes attention faster.”

How to use the question bank. Collapse the answers, say your answer aloud, then reveal and grade yourself. “Solid” should mean you can answer the follow-up too. A stored grade is your self-assessment, not a verified score. Search covers both chapters and question answers; topic and level filters apply to questions.
01 / First principles

Start with a weighted average, not a Transformer

1. What problem are we trying to solve?

Suppose we want a useful representation of the word bank. In “the canoe reached the bank,” canoe and reached help resolve the river sense. In “she deposited cash at the bank,” other words help. We need a way for each position to select information from the other positions, depending on the current input. Handwritten rules would not scale across concepts, tasks, and languages.

An ordinary average mixes all positions equally. A fixed learned weighted sum always uses the same positional weights. Attention instead computes the weights from the current representations. It is content-dependent routing: decide where information should come from, then combine it. The weights are learned indirectly through the task loss, not normally supplied as alignment labels.

2. The only prerequisites you need

ObjectMeaningExample
ScalarOne numberA score of 0.7
VectorAn ordered list of featuresx = [2, −1, 0.5]
Dot productMultiply matching coordinates, then sum[1,2] · [3,4] = 11
Matrix multiplicationAll row-by-column dot products(n × d)(d × m) → n × m
Probability vectorNonnegative entries summing to one[0.2,0.3,0.5]
Weighted sumA mixture of vectors0.2v₁ + 0.3v₂ + 0.5v₃
GradientLocal sensitivity of loss to a variable∂loss/∂score tells training how to change that score.

A dot product depends on both vector norms and their angle: q·k = ‖q‖ ‖k‖ cos θ. Calling it “similarity” is convenient but incomplete. A large norm can increase a score even without a better angular match. Cosine attention removes this norm effect and typically needs its own temperature or learned scale.

3. Build the mechanism in four decisions

  1. Represent what is wanted. Use a query vector q for the current position.
  2. Describe the candidates. Give each candidate a key kⱼ for matching and a value vⱼ carrying the information to retrieve.
  3. Turn scores into a distribution. Compute compatibility sⱼ = score(q,kⱼ), then normalize across candidate keys.
  4. Read the information. Return o = Σⱼ aⱼ vⱼ.
aⱼ = exp(sⱼ) / Σₜ exp(sₜ)     o = Σⱼ aⱼvⱼ

Why separate keys and values? The best features for finding a candidate need not be the best features for using it. In a directory, a name is useful for lookup while a phone number is useful as the returned payload. In neural attention both are usually learned vectors, so this is an analogy, not a literal database implementation.

Why soft rather than pick the best? A weighted mixture is differentiable and can combine several relevant sources. An argmax selection is discontinuous and has zero derivative almost everywhere with respect to scores. Hard selection needs a different training strategy, a relaxation, or a separate retrieval stage. Softmax is one choice, not the definition of all attention: sigmoid gates, sparsemax, and kernel-based rules exist, with different normalization and optimization properties.

4. Where do Q, K, and V come from?

For self-attention, each input row is a token representation xᵢ. Three learned linear maps produce its roles:

qᵢ = xᵢWQ,   kᵢ = xᵢWK,   vᵢ = xᵢWV

WQ, WK, WV are model parameters, shared across sequence positions in the layer. Q, K, V are input-dependent activations, recomputed for different inputs. “Self” means a common source sequence, not that the three matrices are equal. Bias terms may be present; many implementations omit them. At later layers the inputs are contextual hidden states, not raw word embeddings.

During training the loss sends gradients through the weighted sum and softmax to Q, K, V and their projection matrices. This creates a differentiable way to learn which information helps predict the target. It does not require us to label every word-to-word relationship.

One useful lens: learned kernel regression

If the keys are feature vectors and the values are targets or payloads, o(q)=Σⱼw(q,kⱼ)vⱼ / Σⱼw(q,kⱼ) resembles the normalized weighted estimator used in kernel regression. Softmax attention uses positive weights w(q,k)=exp(q·k/√dk). Neural attention learns the matching space and the payload space jointly. This view explains both the weighted-average intuition and the connection to kernel-based efficient attention. It does not mean every attention matrix is symmetric or a positive-semidefinite kernel matrix: Q and K can use different learned projections and masks can be directional.

5. Why did attention matter before Transformers?

A basic recurrent encoder-decoder compresses a source sequence into a single fixed-size state before producing a target sequence. An attentional decoder can instead access a bank of source hidden states at every target step. This reduces the pressure to carry every source detail through one final vector. Bahdanau attention used a learned additive compatibility function; Luong explored dot-product and related variants. Attention did not start with the Transformer, and an RNN can use attention. The Transformer made attention the central token-mixing mechanism instead of recurrence. [2] [3]

Additive: sᵢⱼ = uᵀ tanh(Wq qᵢ + Wk kⱼ + b)
Dot product: sᵢⱼ = qᵢᵀkⱼ    Bilinear: sᵢⱼ = qᵢᵀWkⱼ

In these scalar scoring formulas, q and k are written as column vectors; the stacked Q/K/V matrices elsewhere store their transposes as rows. Additive scoring can use different query and key widths before projecting them into a common hidden width. Dot products map especially well to matrix-multiplication hardware. Neither scoring family universally wins across all settings.

Teach-back: explain attention without saying “focus”

A strong answer: “For each query, compute a compatibility score with every permitted key, normalize scores over keys, and return the weighted sum of the associated values. Learned projections make matching and retrieved content task-dependent.” “Focus on important words” alone does not explain the computation.

02 / Formula, shapes & masks

Derive the formula and every shape

Stack queries as rows of Q, keys as rows of K, and values as rows of V. A single matrix multiplication computes all query-key scores. In this guide nq is query length, nk is key/value length, dk is query/key width, and dv is value width.

O = softmaxkeys(QKᵀ / √dk + M + R)V

M is an additive permission mask: 0 for allowed pairs, −∞ for forbidden pairs. R is an optional finite position or other score bias. Set them to zero for ordinary unmasked attention. The square root uses the per-head key width, not context length and not necessarily the residual width.

TensorOne headBatched multi-headMeaning
Q[nq, dk][B, Hq, nq, dk]One query vector per query position, per query head
K[nk, dk][B, Hkv, nk, dk]Keys; may be shared across query-head groups
V[nk, dv][B, Hkv, nk, dv]Payloads, paired one-to-one with keys
S and A[nq, nk][B, Hq, nq, nk]Scores and probabilities after mapping KV groups
O[nq, dv][B, Hq, nq, dv]Weighted value mixtures

For ordinary MHA, Hq = Hkv = H. GQA requires a mapping from each query head to a KV head; arbitrary unequal head axes do not magically broadcast correctly. The key and value lengths must agree. Query and key widths must agree. Value width can differ from key width mathematically, though fast kernels may constrain it.

Attention data flowQuery times transposed key gives scores. Scale and mask, apply row-wise softmax, multiply by values to obtain output.Q × Kᵀall pair scores÷ √dk + maskscale and permissionssoftmaxacross each rowA × Vmix payloadsOMatching space: dk. Retrieved information space: dv.
Scores choose the mixture; values determine what is mixed. These are separate paths through the computation.

Why normalize over keys?

Each query asks a separate question and gets its own distribution over candidates. Thus the last axis of [B,H,nq,nk] is normalized: softmax(scores, dim=-1). Each valid row sums to 1 before dropout. Columns generally do not sum to 1. Softmax over queries would make different queries compete for a key, which is a different operator.

Why divide by √dk?

Let q and k have independent, zero-mean, unit-variance coordinates, with products independent across coordinate index. Each product qᵣkᵣ has mean 0 and variance 1. Summing dk independent products gives:

E[q·k] = 0
Var(q·k) = Σᵣ Var(qᵣkᵣ) = dk
Var((q·k)/√dk) = 1

Without scaling, larger widths tend to produce larger score differences under these assumptions. Softmax becomes nearly one-hot and its Jacobian can become small. Dividing by √dk controls this initial scale. Dividing by dk would instead drive variance to 1/dk, making scores increasingly flat under the same assumptions. This is a variance argument, not a guarantee: learned norms, correlations, shared Q/K projections, or unusual initialization can violate it. LayerNorm and QK normalization influence statistics but do not make the assumptions a theorem. [1]

Stable softmax is an algebraic identity

softmax(s)ⱼ = exp(sⱼ − m) / Σₜ exp(sₜ − m),   m = maxₜ sₜ

Subtracting the same constant from a row cancels from numerator and denominator. Choosing the maximum avoids overflow because the largest exponent becomes 1. For scores [1000,1001], direct exponentiation overflows in common numeric types, but exp([-1,0]) is safe. This does not rescue an all-−∞ row: subtraction then produces undefined values. Define a policy before you implement the operator.

Make the mask explicit

MaskAllowed relationWhat it prevents
Causalkey_position ≤ query_positionReading future tokens in a next-token decoder
Paddingkey_valid == TrueReading pad tokens as content
Segment / packed sequencekey_segment == query_segmentCross-example leakage when examples share a tensor
Sliding windowWithin the permitted positional windowReading sources outside the chosen neighborhood
Causal permission, length 4:
1 0 0 0
1 1 0 0
1 1 1 0
1 1 1 1

The diagonal is allowed in standard next-token training. The representation at input position i predicts target token i+1; it may see token i. If the target were not shifted correctly, a causal mask alone would not fix label leakage. Combine causal, key-padding, and segment permissions with logical AND. A query-padding mask is also needed if padded query outputs or losses must be excluded.

Mask logits before softmax. Setting a forbidden score to zero does not forbid it: exp(0)=1. Multiplying probabilities by a zero/one mask afterward removes mass without renormalizing, so it is not the same distribution. A very negative finite sentinel is dtype-dependent and dangerous for all-masked rows, where equal sentinels can give a uniform distribution over forbidden entries.

Shape drill: B=2, H=8, nq=5, nk=11, dk=64, dv=48. What are A and O?

A: [2,8,5,11]; O: [2,8,5,48]. Concatenated heads have shape [2,5,384]. A learned output matrix maps 384 to the desired residual width. A square causal mask is not appropriate just because the queries happen to have length 5.

03 / Worked numerical example

One query. Three keys. No mystery.

Use a two-dimensional query and keys, and two-dimensional values. These numbers are chosen for arithmetic, not copied from a trained model. We omit projection matrices to isolate attention itself.

q = [1, 0]
K = [[1,0], [0,1], [1,1]]
V = [[1,0], [0,2], [3,1]]
  1. Dot products: qKᵀ = [1,0,1].
  2. Scale: s = [0.707107,0,0.707107] because dk=2.
  3. Exponentiate stably: subtract 0.707107 to obtain [0,−0.707107,0]; exponentials are [1,0.493069,1].
  4. Normalize: a ≈ [0.401112,0.197776,0.401112].
  5. Mix values: o = 0.401112[1,0] + 0.197776[0,2] + 0.401112[3,1].
o ≈ [1.604448, 0.796664]

The output is not the most similar key. It is a mixture of values. Identical scores for keys 1 and 3 imply equal attention weights, but those keys contribute different payloads. The second value contributes to the second output coordinate twice its weight.

A complete self-attention pass, including projections

For a separate two-token example, choose X=[[1,0],[0,1]], WQ=[[1,0],[0,1]], WK=[[1,1],[0,1]], and WV=[[2,0],[0,3]]. These matrices are illustrative parameter values; training would learn them. Matrix multiplication gives:

Q = XWQ = [[1,0],[0,1]]
K = XWK = [[1,1],[0,1]]
V = XWV = [[2,0],[0,3]]
QKᵀ / √2 = [[0.707107,0],[0.707107,0.707107]]
A ≈ [[0.669762,0.330238],[0.5,0.5]]
O ≈ [[1.339523,0.990715],[1,1.5]]

The second query has equal compatibility with both keys and returns their mean value. All positions used the same projection matrices but produced different queries and mixtures. An output projection could now map O into a residual stream; with a two-dimensional identity output projection, O is unchanged.

Add a mask to the original three-key example

Suppose only the first two keys are allowed. Replace the last score by −∞. The weights become approximately [0.669762,0.330238,0] and the output becomes [0.669762,0.660477]. Masking changes the normalization for the allowed entries, not just the forbidden entry.

Change the temperature

For positive temperature τ, use softmax(s/τ). Smaller τ sharpens the distribution. As τ→0, a unique maximum becomes one-hot; here two maxima tie, so the limit is [0.5,0,0.5]. As τ→∞, all finite allowed scores receive equal mass and the output becomes the mean of their values. Temperature here acts on attention logits, not the vocabulary logits used for sampling generated tokens.

Predict before revealing: if all values are equal, does changing Q or K change O?

No, for ordinary normalized attention without dropout and at least one allowed key. If every vⱼ=v, then o=Σⱼaⱼv=v. Q and K can change attention weights without changing the output. This is one reason attention maps alone cannot prove an explanation.

Predict: if we multiply Q by 2 and K by 0.5, what changes?

The logits QKᵀ are unchanged, so the attention output is unchanged for the same mask, bias, and V. Parameter and activation representations are not uniquely identifiable from the operator output. This is different from multiplying both Q and K by 2, which multiplies their dot-product scores by 4.

04 / Gradients & deeper math

The mathematics interviewers can push on

1. Softmax as entropy-regularized selection

Why does exponentiating scores make sense? Consider choosing a probability vector a to maximize score while rewarding uncertainty:

maximizeaⱼ≥0, Σaⱼ=1   Σⱼ aⱼsⱼ + τH(a)
H(a) = −Σⱼaⱼ log aⱼ,   τ > 0

With finite scores, the optimum is interior. Introduce a multiplier λ for the sum constraint. Stationarity gives sⱼ − τ(log aⱼ + 1) + λ = 0, so aⱼ ∝ exp(sⱼ/τ). Normalize and you recover softmax. Higher temperature puts more weight on entropy; lower temperature rewards concentrating on the best scores. Masking corresponds to restricting the permitted support before optimizing. This is a useful derivation, not a statement that every trained head explicitly solves a separate optimization program.

2. Derive the softmax Jacobian

For aᵢ=eˢⁱ/Z, differentiate numerator and denominator:

∂aᵢ/∂sⱼ = aᵢ(δᵢⱼ − aⱼ)
J = diag(a) − aaᵀ

The diagonal term is aᵢ(1−aᵢ) and off-diagonal terms are −aᵢaⱼ. Increasing one score raises that probability while decreasing the others. Each Jacobian row sums to zero, consistent with invariance to adding a constant to every logit. When a is nearly one-hot, these terms become small. At exactly one permitted key, attention weights are constant and score gradients are zero, though gradients still flow to the selected value.

3. Backpropagate through the whole attention operation

Take one head without dropout. Let S=QKᵀ/√dk, A=softmax(S), O=AV, and upstream gradient G=∂loss/∂O. A fixed mask or fixed bias does not receive gradients. Define D to have the same shape as S.

∂loss/∂V = AᵀG
E = ∂loss/∂A = GVᵀ
Dᵢⱼ = Aᵢⱼ (Eᵢⱼ − Σₜ AᵢₜEᵢₜ)
∂loss/∂Q = DK / √dk
∂loss/∂K = DᵀQ / √dk

Shapes verify the equations: AᵀG is [nk,nq][nq,dv] → [nk,dv]; GVᵀ is [nq,dv][dv,nk] → [nq,nk]. Forbidden pairs have zero probabilities and zero score gradients under an ideal mask. A learned relative-position bias receives D aggregated over whatever parameters share that bias.

For self-attention, X feeds three branches, so its gradients add:

∂loss/∂X = GQ WQᵀ + GK WKᵀ + GV WVᵀ
∂loss/∂WQ = XᵀGQ   (and similarly for WK, WV)

Here GQ, GK, and GV mean gradients of the projected activations, not the original upstream G. Batch and sequence axes are summed appropriately for parameter gradients. Adding an output projection introduces its usual matrix-multiplication gradient; dropout introduces the sampled, rescaled dropout mask.

Can a key with tiny weight ever learn to become important?

Yes, its gradient is usually small rather than exactly zero, and updates from other queries or examples can change its representation. However, saturated softmax can make learning slow. Exactly masked entries have no score gradient through the masked connection. Changing temperature or score normalization affects this optimization, but also changes model behavior.

4. Permutation equivariance, with a proof

Without positional information or an order-dependent mask, self-attention treats tokens as a set. Let P permute rows. Shared projections give Q′=PQ, K′=PK, V′=PV. Then:

S′ = PSPᵀ
softmaxrow(PSPᵀ) = P softmaxrow(S) Pᵀ
O′ = P A Pᵀ P V = P O

The outputs permute with the inputs: equivariance, not invariance. Pooling outputs by a symmetric sum or mean can yield an invariant sequence-level representation. A fixed causal mask or fixed positional embeddings generally breaks arbitrary permutation equivariance. If you permute all position data and mask relations alongside the tokens, you may simply be relabeling the same structured computation.

In cross-attention, jointly permuting keys and values leaves each fixed query output unchanged, provided the corresponding mask and bias columns are permuted too. Permuting only values changes the association between matching features and payloads.

5. Convex hull and why it does not limit the entire Transformer

A row of ordinary softmax attention before dropout is a convex combination of allowed value vectors: nonnegative coefficients summing to 1. Thus it lies inside their convex hull. This says nothing about the original token embeddings, because values are already projected. Concatenation, a learned output projection, residual addition, and the FFN change the representation. Attention dropout uses a random mask and a 1/(1−p) scale, so a sampled row generally no longer sums to 1. The simple convex-hull claim need not hold for that sampled output.

6. Low-rank logits do not imply equally low-rank probabilities

For an unmasked head, rank(QKᵀ) ≤ dk. Applying elementwise exponentiation and row normalization is nonlinear and can increase rank. For example, let Q=K=[[0],[1]]. Then S=[[0,0],[0,1]] has rank 1, but A=[[1/2,1/2],[1/(1+e),e/(1+e)]] has nonzero determinant and rank 2. Do not justify linear attention by claiming softmax preserves the score rank. Even a full-rank A is constrained by how its logits were parameterized; full rank does not imply arbitrary expressivity.

7. Why attention weights are not a causal explanation

Weights describe mixing coefficients at one head and layer. The causal contribution of a token also depends on its value vector, output projection, residual paths, other heads, later nonlinearities, and the target output. Different weight patterns can yield the same mixture; the equal-value example showed one case. A high weight is not a calibrated probability that a source is correct or responsible for a prediction.

Use attention visualizations to generate hypotheses. Test them with controlled ablations, counterfactual substitutions, attribution methods with stated assumptions, and behavior-level evaluation. A model-generated explanation must itself be checked against source evidence. Interventions also change the input distribution, so even ablation results need careful interpretation.

Numerical gradient drill: how do you check your backward equations?

Choose a tiny float64 example and a scalar objective loss=ΣᵢⱼOᵢⱼGᵢⱼ. Perturb each Q/K/V element by ±ε, evaluate the centered difference (loss(x+ε)−loss(x−ε))/(2ε), and compare it to the manual gradient. Use non-saturated scores and ε near 1e−6 in a small double-precision test, then inspect both absolute and relative error. Check masking separately. The companion standard-library code does this without an autograd dependency.

05 / Heads & Transformer blocks

Heads, masks, and the Transformer block

Multi-head attention is multiple mixing patterns

One head applies the same attention row to every coordinate of its value vector. If two different relationships matter, one mixture can blend them together. Multiple heads produce separate distributions and value subspaces, letting downstream computation combine different views. A head may learn syntax or coreference-like behavior, but heads are not assigned fixed human concepts and need not specialize neatly.

headₕ = Attention(XWQₕ, XWKₕ, XWVₕ)
MHA(X) = Concat(head₁,…,headH)WO

In the common configuration dk=dv=d/H, every Q/K/V projection combined across heads is d×d, and WO is d×d. Ignoring biases, attention has 4d² parameters. It does not have H times as many parameters as a single full-width attention layer. Increasing H at fixed d narrows heads and increases score-matrix count; it does not universally improve accuracy or speed. Keeping head width fixed while increasing H is a different comparison because total width grows.

Example, d=512 and H=8Shape
Input[B,n,512]
Fused QKV linear output[B,n,1536]
Each Q/K/V after reshape and transpose[B,8,n,64]
Attention output per head[B,8,n,64]
Transpose back, then concatenate[B,n,512]
Output projection[B,n,512]

Reshaping splits feature channels into heads; transposing places the head axis before sequence length so batched matrix multiplication works. After transposing back, a tensor may not be contiguous, so view can fail or require contiguous(); reshape may make a copy. Shape correctness alone does not prove the head and token axes were preserved correctly.

Self-attention and cross-attention answer different questions

PatternQ sourceK/V sourceTypical mask
Encoder self-attentionSource hidden statesSame sourcePadding; usually bidirectional
Decoder self-attentionTarget hidden statesSame target sequenceCausal plus padding/segment rules
Encoder-decoder cross-attentionDecoder hidden statesEncoder outputsSource padding; usually all real source tokens are visible
Learned-query poolingOne or several learned vectorsInput featuresInvalid feature mask
Multimodal cross-attentionFor example text statesFor example image/video featuresArchitecture and task dependent

Cross-attention can return a different number of output positions than there are source positions. Its output length equals query length. A decoder can cache projected encoder K/V because the encoder source stays fixed during target generation. Self-attention cache K/V grow with each appended token.

Attention is one sublayer, not the entire Transformer

A common modern decoder block uses pre-normalization:

U = X + Attention(Norm(X))
Y = U + FFN(Norm(U))

Attention mixes information across tokens. The FFN transforms each token’s features using shared weights independently of other positions. A simple FFN is W₂ activation(W₁x+b₁)+b₂; gated variants such as SwiGLU use a learned multiplicative gate and different parameter counts. Residual connections preserve a direct signal and gradient path. LayerNorm or RMSNorm controls feature scale; it is not the row-wise softmax over keys.

The original Transformer used post-LayerNorm, Norm(X+Sublayer(X)). Pre-norm often improves deep optimization behavior, but normalization placement is a design choice with training and representation consequences. RMSNorm scales by root mean square without subtracting the feature mean; LayerNorm subtracts the mean and divides by standard deviation, usually with learned affine parameters. Neither inherently normalizes Q·K to unit variance. [1]

Training can be parallel even though generation is sequential

During teacher-forced next-token training, all input tokens are known, so a causal matrix lets us compute representations for all positions simultaneously within a layer. The mask prevents future-token leakage. Layers still depend on previous layers. During ordinary autoregressive generation, the next sampled token is unknown until the current step finishes, so new token steps are sequential. KV caching removes repeated computation of old K/V, not this dependency.

The standard objective is −Σₜ log p(xₜ₊₁ | x≤ₜ). The attention matrix is not that vocabulary distribution. The final hidden state is mapped to vocabulary logits by an output head, followed by another softmax for the language-model loss or sampling.

Know the neighboring terms without confusing them

TermWhat changes?Interview caveat
Graph attentionAggregate neighbors using learned edge scores; graph adjacency supplies the permission structure.Attention can operate on graphs, not just token sequences. Some GAT variants use additive scoring and differ from Transformer attention.
Spatial / channel attentionGate or aggregate image locations or feature channels.A module called attention may use sigmoid gates rather than a QKᵀ softmax matrix.
Attention poolingUse learned or input-dependent queries to summarize a sequence.A pooled vector can be permutation invariant if positions and masks do not introduce order.
Hard attentionSelect a discrete subset or location.Selection changes differentiability; sparse learned routing is not automatically exact dense attention.
Retrieval-augmented generationRetrieve external documents before or alongside generation.External retrieval is not the same as per-layer soft attention over context tokens.
MoERoute tokens to selected feed-forward experts.Expert routing usually changes the FFN, not the token-to-token attention operator.
Architecture drill: can a bidirectional encoder directly serve as an ordinary next-token decoder?

Not without changing its masking and training setup. Bidirectional attention can read future context; a standard masked-language-model objective differs from autoregressive next-token training. Adding a causal mask at inference does not establish that the model learned the needed conditional distribution. Architecture, objective, and inference factorization must agree.

06 / Implement & test

Build it. Then try to break it.

Start with a transparent implementation, then compare a fused kernel against it. The standard-library reference includes manual backward equations and executable tests without dependencies. The PyTorch module below shows real head reshaping, output projection, and inference caching. It is educational, not a production serving implementation.

Write the contract before the code

import math
import torch
from torch import nn
import torch.nn.functional as F


class CausalMHA(nn.Module):
    """Teaching MHA: unpadded contiguous sequences, no RoPE or GQA.

    Cache is inference-only and stores projected K/V for every past token.
    Use torch.inference_mode() plus model.eval() when caching.
    """
    def __init__(self, d_model, heads, dropout=0.0):
        super().__init__()
        if heads <= 0 or d_model <= 0 or d_model % heads:
            raise ValueError("Positive d_model must be divisible by heads")
        if not 0.0 <= dropout < 1.0:
            raise ValueError("dropout must be in [0,1)")
        self.d = d_model
        self.h = heads
        self.dh = d_model // heads
        self.p = dropout
        self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
        self.out_proj = nn.Linear(d_model, d_model, bias=False)

    def forward(self, x, cache=None, use_cache=False):
        if x.ndim != 3 or x.shape[-1] != self.d or x.shape[1] == 0:
            raise ValueError("x must have shape [B,T,d_model], T>0")
        if cache is not None and not use_cache:
            raise ValueError("Passing cache requires use_cache=True")
        if (use_cache or cache is not None) and (
            self.training or torch.is_grad_enabled()
        ):
            raise ValueError("Cache requires eval() and inference_mode/no_grad")
        b, t, _ = x.shape
        packed = self.qkv(x).reshape(b, t, 3, self.h, self.dh)
        q, k, v = packed.permute(2, 0, 3, 1, 4).unbind(0)
        past = 0
        if cache is not None:
            old_k, old_v = cache
            if (old_k.ndim != 4 or old_k.shape != old_v.shape
                    or old_k.shape[:2] != (b, self.h)
                    or old_k.shape[-1] != self.dh
                    or old_k.device != k.device or old_v.device != v.device
                    or old_k.dtype != k.dtype or old_v.dtype != v.dtype):
                raise ValueError("Incompatible cache shape/device/dtype")
            past = old_k.shape[-2]
            k = torch.cat((old_k, k), dim=-2)
            v = torch.cat((old_v, v), dim=-2)
        # Query row i is at absolute position past+i.
        query_pos = past + torch.arange(t, device=x.device)
        key_pos = torch.arange(k.shape[-2], device=x.device)
        allowed = key_pos[None, :] <= query_pos[:, None]
        work_dtype = torch.float32 if q.dtype in (
            torch.float16, torch.bfloat16
        ) else q.dtype
        # Disable autocast here so explicit float32 math stays float32.
        with torch.autocast(device_type=x.device.type, enabled=False):
            scores = q.to(work_dtype) @ k.to(work_dtype).transpose(-2, -1)
            scores = scores / math.sqrt(self.dh)
            scores = scores.masked_fill(~allowed, -torch.inf)
            a = scores.softmax(dim=-1)
            a = F.dropout(a, p=self.p, training=self.training)
            y = a @ v.to(work_dtype)
        y = y.to(q.dtype).transpose(1, 2).reshape(b, t, self.d)
        y = self.out_proj(y)
        new_cache = (k.detach(), v.detach()) if use_cache else None
        return y, new_cache

Read the reshape rather than memorizing it

The fused projection makes [B,T,3d]. Reshape to [B,T,3,H,dh], permute to [3,B,H,T,dh], then unpack Q/K/V. After attention, transpose from [B,H,T,dh] to [B,T,H,dh] before merging H and dh. Reordering axes is not the same as reshaping their sizes.

Why the cache mask uses absolute positions

With p cached tokens and m new queries, local query i corresponds to global position p+i. It may see keys j≤p+i. For p=3,m=2, the allowed rows are [1,1,1,1,0] and [1,1,1,1,1]. A fresh 2×5 upper-left triangle would wrongly permit only [1,0,0,0,0] and [1,1,0,0,0].

Concatenating cache tensors at each step repeatedly copies memory; that is fine for teaching and poor for production. Real runtimes use preallocation, block/paged storage, or other managed layouts. Cache validity also depends on unchanged model weights, token prefix, position convention, and any adapter or modality state.

Test full and cached outputs, then gradients

torch.manual_seed(7)
model = CausalMHA(d_model=16, heads=4).double().eval()
x = torch.randn(2, 7, 16, dtype=torch.float64)

with torch.inference_mode():
    full, _ = model(x)
    parts, cache, start = [], None, 0
    for size in (2, 1, 4):
        out, cache = model(x[:, start:start+size], cache, use_cache=True)
        parts.append(out)
        start += size
    chunked = torch.cat(parts, dim=1)
    torch.testing.assert_close(full, chunked, rtol=1e-10, atol=1e-10)
    changed = x.clone()
    changed[:, 4:] += 10
    other, _ = model(changed)
    torch.testing.assert_close(full[:, :4], other[:, :4], rtol=1e-10, atol=1e-10)

# eval() disables dropout; it does not disable autograd.
x_grad = x.clone().requires_grad_(True)
torch.autograd.gradcheck(lambda z: model(z)[0], (x_grad,),
                         eps=1e-6, atol=1e-5, rtol=1e-3)

Execution status: these PyTorch snippets are syntax-checked and reviewed, but not executed here because PyTorch is unavailable. The dependency-free reference tests are executed. CPU float64 comparison tolerances are intentionally strict; do not copy them unchanged into BF16 GPU tests. The causal-isolation test assumes no cross-token operation outside the masked attention path, which holds for this module.

Switch to SDPA without changing the contract

# q: [B,H,m,dh], k_all/v_all: [B,H,past+m,dh]. No padding here.
query_pos = past + torch.arange(q.shape[-2], device=q.device)
key_pos = torch.arange(k_all.shape[-2], device=q.device)
allowed = key_pos[None, :] <= query_pos[:, None]
y = F.scaled_dot_product_attention(
    q, k_all, v_all,
    attn_mask=allowed,          # Boolean True means allowed in this API.
    is_causal=False,            # Explicit shifted mask already supplies causality.
    dropout_p=(self.p if self.training else 0.0),
)

The official API specifies that Boolean True participates in SDPA, while Boolean True means blocked in nn.MultiheadAttention masks. Functional SDPA always follows its dropout_p argument; it does not infer evaluation mode from your module. Set dropout explicitly to zero for inference. The documented non-square is_causal=True bias is upper-left aligned, so explicitly supplying cached absolute-position permissions avoids an easy error. Do not pass both the explicit mask and is_causal=True in the checked API. [4]

Calling SDPA does not prove a FlashAttention kernel was selected. Device, dtype, strides, head dimensions, mask form, dropout, and installed framework version affect eligibility. Use backend diagnostics and profiling rather than relying on the function name.

What to add for padded or packed batches

Combine causal permission [Tq,Tk] with valid-key permission [B,1,1,Tk] and, for packing, equal-segment permission. Track per-example logical lengths rather than one shared past counter. Padded query positions may have zero permitted real keys, especially with left padding. Exclude them or compute a safe fallback and zero their outputs before downstream operations; ignore their labels in the loss. Never let a real query silently attend nonexistent data.

For RoPE, rotate each new Q/K using its logical position and store the rotated K. Preserve training’s rotary pairing, frequencies, and scaling configuration. The common-shift identity is a useful primitive test; full-model cache parity is the stronger integration test.

Whiteboard debugging: find the bug before revealing the fix

These are intentionally broken snippets. Explain the symptom, make the smallest correction, and name a test that would have caught it.

Bug 1: the tensor shapes look right, but every query’s probabilities sum to the wrong value
scores = q @ k.transpose(-2, -1)
weights = scores.softmax(dim=-2)
output = weights @ v

Fix. Normalize over keys with dim=-1, and include the intended scale 1/sqrt(q.size(-1)). The second-to-last dimension is the query axis in [B,H,nq,nk]. Shape tests alone will pass here.

Test. Use a rectangular query/key example with nq≠nk and assert that weights sum to one along the last axis. Compare against a scalar-loop reference.

Bug 2: future tokens still influence earlier predictions
scores = scores.masked_fill(future_mask, 0.0)
weights = scores.softmax(dim=-1)

Fix. Use negative infinity for forbidden logits, not zero. A score of zero still contributes exp(0)=1 to the softmax. Before normalizing, handle any all-masked row according to an explicit contract.

Test. Perturb only tokens after position i and assert that outputs up to i do not change, with dropout disabled. Also assert exactly zero masked weights in the transparent reference.

Bug 3: model.eval() did not make inference deterministic
output = torch.nn.functional.scaled_dot_product_attention(
    q, k, v, dropout_p=0.1, is_causal=True
)

Fix. Functional SDPA applies the specified dropout probability regardless of the calling module’s training state. Pass dropout_p=(self.p if self.training else 0.0). Even then, backend nondeterminism or reduced-precision arithmetic may need separate controls when strict reproducibility matters.

Test. Run a fixed input repeatedly in eval mode and compare with dropout explicitly set to zero. Check training and evaluation behavior independently. [4]

Bug 4: full-sequence inference works, but single-token cached decode attends only to the first key
# q has one new position; k/v include the full prefix plus it.
output = torch.nn.functional.scaled_dot_product_attention(
    q, k_all, v_all, is_causal=True
)

Fix. Do not assume that a non-square causal flag aligns the query to the newest key. The checked PyTorch API uses upper-left alignment. With nq=1 this can expose only key 0. If k_all contains only valid past keys plus the current key, a single new query can attend all of them and needs no causal mask; otherwise build a mask from absolute query/key positions and pass it explicitly with is_causal=False. Multi-token appended chunks need a shifted triangular boundary.

Test. Compare full causal outputs to incremental outputs for one-token chunks and uneven multi-token chunks. Include a prompt longer than one token so a wrongly aligned mask cannot accidentally pass.

Bug 5: an attention visualization looks normalized, but the implementation changes output scale near padding
weights = scores.softmax(dim=-1)
weights = weights * key_valid
output = weights @ v

Fix. Mask invalid keys before softmax. Post-softmax masking without renormalizing loses probability mass. Renormalizing after masking is mathematically equivalent for a nonempty valid set in exact arithmetic, but it can be less stable if almost all mass was assigned to masked positions.

Test. Append masked padding containing very large logits/values and verify that valid outputs are unchanged. Check valid-row sums before dropout.

Bug 6: double-precision gradcheck fails even though ordinary float32 examples look fine
scores = (q.float() @ k.float().transpose(-2, -1)) / math.sqrt(dk)
weights = scores.softmax(dim=-1)
output = weights @ v.float()

Fix. Unconditionally calling .float() downcasts float64 inputs, losing the precision needed for sensitive numerical checks. Upcast FP16/BF16 intermediates when appropriate, but preserve float64. Decide and document the output dtype too.

Test. Assert dtype preservation for float64 and run centered finite differences or autograd gradcheck on small, non-saturated examples. Test low-precision execution separately with a tolerance appropriate to that dtype.

Bug 7: grouped-query attention is correct in one head but wrong in the others
# Intended mapping for Hq=4, Hkv=2 is [0,0,1,1].
k_for_q = k.repeat(1, 2, 1, 1)
v_for_q = v.repeat(1, 2, 1, 1)

Fix. For contiguous groups, use repeat_interleave(Hq // Hkv, dim=1), which gives [0,0,1,1]. Whole-axis repeat gives [0,1,0,1]. Either mapping can define an architecture if training and inference agree, but silently switching them changes the function. A native GQA kernel should avoid physically duplicating cache storage.

Test. Set each KV head to a distinct sentinel value and compare per-query-head outputs to the intended group mapping. Do not use identical random seeds or identical heads that can hide a mapping mistake.

Bug 8: a training batch contains NaNs only when left padding is used
allowed = causal_allowed & key_is_real
scores = scores.masked_fill(~allowed, float('-inf'))
weights = scores.softmax(dim=-1)

Fix. Early padded query rows may have no real permitted keys. A transparent all-−∞ softmax is undefined. Exclude those query rows, or provide a safe fallback row during computation and then zero invalid query outputs before they can affect downstream computation. Ignore padded targets in the loss. For a real query with no permitted key, fail fast rather than inventing content.

Test. Include both left and right padding, multiple sequence lengths, empty/all-padding examples if supported, and gradients. Masking only the loss does not necessarily prevent NaNs inside intermediate operations from contaminating backward computation.

07 / Attention & KV labs

Make the mechanism move

Edit Q, K, and V as JSON matrices. This is one head, with rows representing positions. The heatmap encodes probabilities; it is not an explanation of a model prediction. Numbers are rounded only for display. Defaults reproduce the worked example in the first query row.

Causal permission is key index ≤ query row index + offset. Use offset = past length for appended cached chunks. Matrix dimensions are limited to 8 here; this lab is for reasoning, not performance measurement.

Try three experiments.
  1. Set Q to all zeros. Each query returns the mean of permitted values.
  2. Make the first query [8,0] and lower temperature. The tied best keys still share mass.
  3. Turn on the causal mask. Row 1 sees only key 1; row 3 can see all three. Then test a single query with offset 2.

KV-cache memory calculator

This calculator uses the standard uncompressed K/V representation with equal key/value head width. It excludes weights, activations, allocator fragmentation, metadata, and temporary workspaces. MLA and architecture-specific shared caches need their own accounting.

Enable JavaScript to compute cache payload.
Cache bytes = 2 × B × layers × tokens × Hkv × head_width × bytes_per_element

The factor 2 counts K and V. The byte widths for quantized caches are ideal payload-only values: scales, zero points, alignment, and residual high-precision regions add overhead.

08 / Position & RoPE

Give content a sense of order

Content-only, unmasked self-attention is permutation equivariant. It can distinguish token content, but it cannot by itself distinguish different arrangements of the same set of input representations. Position schemes inject order into the input, the query/key geometry, or the logits. A causal mask also introduces order-dependent structure, so it is incorrect to claim that every decoder without explicit position embeddings is entirely order-blind.

Absolute position: add a vector

Learned position embeddings use a table P[Tmax,d] and input xᵢ + P[i]. Valid zero-based indices are 0 through Tmax−1. Beyond that, the table must be extended, interpolated, or otherwise changed; behavior is not defined by the original lookup alone. Rows rarely seen during training can be poorly trained.

The original Transformer used sinusoidal coordinates: [1]

PE(m,2i)=sin(mθᵢ),   PE(m,2i+1)=cos(mθᵢ)
θᵢ=10000−2i/d

Each pair traces a circle at a different frequency. The raw position-vector dot product is PE(m)·PE(n)=Σᵢcos((m−n)θᵢ), a function of relative offset. For the displayed [sin,cos] ordering, a shift by k corresponds to the usual rotation matrix R(−kθ), not R(+kθ). Sinusoids can be evaluated beyond training length, but that does not guarantee accurate long-context behavior.

After learned projections, the score contains content-content, content-position, position-content, and position-position terms. General projection matrices need not preserve the offset-only cancellation even in the last term. Absolute position therefore offers relative information without enforcing a purely relative score.

RoPE: rotate queries and keys

Use column vectors locally for the following derivation. Rotate a two-coordinate query by the query position m and a key by the key position n: [5]

R(α) = [[cos α, −sin α], [sin α, cos α]]
q̃ₘ = R(mθ)qₘ,   k̃ₙ = R(nθ)kₙ
q̃ₘᵀk̃ₙ = qₘᵀ R(mθ)ᵀR(nθ) kₙ
= qₘᵀ R((n−m)θ) kₙ

This works because rotations preserve length and R(a)ᵀR(b)=R(b−a). It is a constructive solution, not a claim that rotations are the only conceivable positional mechanism. For an even rotary width, split the features into pairs with different frequencies and apply the identity to each pair. Implementations may use adjacent pairs or split-half pairing; their sine/cosine layout must match training.

In common decoder RoPE implementations, rotate Q and K, not V. Some architectures rotate only part of each head. The identity concerns the explicit position transform holding content vectors fixed. Hidden states can already encode position and context, so it does not prove that the entire trained model is invariant to an arbitrary global shift.

Cache rule. Cache each key after applying its intended rotary position once. A new query uses its global position, not zero in every decode chunk. If old cached keys are re-rotated, or position indices are reset, full-versus-cached parity breaks. A windowed cache can evict old storage without resetting the logical position counter.

Relative bias and ALiBi

A relative-bias scheme adds bₕ(n−m) to the score. Learned buckets can represent nearby distances finely and distant distances coarsely. Once distances share the last bucket, they receive the same explicit bias; content scores can still differ.

For causal ALiBi, a permitted past key receives a head-specific linear penalty: [6]

sₘₙ = qₘᵀkₙ/√dk − slopeₕ(m−n),   n≤m, slopeₕ>0

The original slope schedule depends on head count. For eight heads, the familiar slopes are 1/2, 1/4, …, 1/256; do not generalize that exact exponent schedule to every head count. The formula is defined at arbitrary distances and favors recency. Reported extrapolation gains do not guarantee distant retrieval for every model or task. A low perplexity can coexist with poor access to far-away evidence.

SchemeInjection pointBeyond training lengthCache concern
Learned absoluteInput vectorTable extension needed beyond supported indicesCorrect position lookup
SinusoidalInput vectorFormula exists; quality not guaranteedCorrect input positions
RoPEQuery/key geometryFormula exists; unfamiliar distance/phase patterns can hurtStore correctly rotated keys
Bucketed relative biasLogitsDistant offsets may collapse into one bucketRecompute bias from logical positions
ALiBiLogitsDefined linear recency bias, task-dependent extrapolationUse true query-key distance

Context extension is a model change

Position interpolation maps a larger target range into the trained position range, for example m → m/4 when extending by four times. It also reduces local angular separation. Changing the RoPE base changes frequencies nonuniformly; frequency-dependent schemes use additional interpolation and scaling choices. These are distinct interventions, not universally interchangeable config flags. Start from the checkpoint’s documented scheme, then evaluate short-context regression and long-context behavior. Continued long-context training may be needed.

For head width 128 and base 10000, rotary wavelengths range from about 6.28 to 54,410 tokens. At context length 8192, 50 of the 64 pairs complete at least one full cycle. This arithmetic illustrates different frequency scales; it does not alone predict which features the model uses or establish a universal failure threshold.

Position whiteboard: why does a common shift cancel in RoPE?

Replace m,n by m+c,n+c while holding unrotated q,k fixed. The relative angle remains ((n+c)−(m+c))θ=(n−m)θ. Test this score identity numerically. Then separately test whole-model cache parity, because hidden-state changes, masks, and absolute embeddings can introduce other dependencies.

09 / Efficient attention

Know which cost you are reducing

Let B be batch size, n prompt length, d residual width, H query heads, and dh=d/H. Unless stated otherwise, count a multiply and add as two FLOPs and use standard MHA with dk=dv=dh. These are per-layer forward estimates; omit FFN, normalization, softmax, vocabulary projection, and backward unless explicitly included.

StageProjection matmulsAttention matmulsMemory pressure
Full-sequence training forward / prefill8Bnd²4Bn²d for QKᵀ and AVNaive attention stores Θ(BHn²) scores/probabilities; training also saves/recomputes backward state
One cached decode token with t keys including itself8Bd²4BtdRead growing KV cache; naive score vector Θ(BHt)
m appended tokens, p cached tokens8Bmd²Dense rectangle upper bound 4Bm(p+m)dMask must allow key j≤p+i for query i

A causal-aware kernel can skip upper-triangle work; an implementation that computes all scores then masks them still pays for those scores. Backward has additional matrix multiplications and saved-state or recomputation costs. At shorter n, projections and FFNs can dominate; “attention is quadratic” does not mean the whole model’s wall time is quadratic in every operating regime.

For a generated continuation of g tokens after prompt length p, cached pairwise decode work grows like Σₜ₌₁ᵍ(p+t)=gp+g(g+1)/2. It is linear in retained history per step, not constant time. Naively recomputing every full prefix costs much more. Caching relies on prior causal states remaining unchanged; adding future input to a bidirectional encoder generally changes previous states.

Derive KV memory rather than guessing

bytes = 2 × B × L × t × Hkv × dh × b

L is layer count, b bytes per element, and Hkv is the number of stored KV heads. The 2 counts K and V, assuming equal widths. With B=1, L=32, t=8192, Hkv=8, dh=128, b=2:

2 × 1 × 32 × 8192 × 8 × 128 × 2
= 1,073,741,824 bytes = 1 GiB

This is 128 KiB per token per sequence across all layers. If Hq=32, same-width MHA stores four times the KV payload, 4 GiB. These are logical payload sizes, not complete GPU memory requirements.

VariantWhat is shared or compressed?What remains?
MHAIndependent K/V for every query headFull head-specific matching and values
MQAOne KV head shared by all query headsSeparate query heads and their attention distributions
GQAEach group of query heads shares one KV headSeparate query-head score/output work; fewer K/V projections and cache entries
MLACache a compressed latent representation plus architecture-specific positional stateArchitecture-specific query transformations and reconstruction/absorbed projections; not just fewer KV heads

MQA and GQA target decode bandwidth and cache capacity, with possible quality trade-offs. Changing an existing checkpoint’s KV-head structure is not a lossless reshape in general; training or uptraining may be required. A kernel that physically repeats K/V can undermine the storage/bandwidth benefit. MLA requires deriving memory from its actual stored latent and positional tensors rather than plugging a fictitious head count into the standard formula. [9] [8] [13]

FlashAttention: exact softmax without storing the full matrix

The naive implementation writes the score and probability matrices to GPU high-bandwidth memory and later reads them. FlashAttention tiles the computation so blocks of Q/K/V and partial outputs fit in fast on-chip memory. It combines stable softmax statistics across blocks and recomputes appropriate intermediates in backward. The full n×n probability matrix need not be stored in HBM. It evaluates the same dense operator, subject to floating-point rounding, while still doing quadratic pairwise arithmetic. [7]

For one query, maintain a running maximum m, exponential sum ℓ, and unnormalized output numerator u. For a new score block s with corresponding value rows V:

m′ = max(m, max(s))
α = exp(m−m′),   eⱼ = exp(sⱼ−m′)
ℓ′ = αℓ + Σⱼeⱼ
u′ = αu + Σⱼeⱼvⱼ
O = u/ℓ after all blocks

Initialize by the first block containing an allowed key, or explicitly set old-state rescaling to zero when no previous mass exists. Skip a block that is entirely masked. Do not evaluate −∞−(−∞). A query whose entire permitted support is empty still requires a defined policy. The max rescaling converts old and new block contributions to the same numerical reference, which is why independently normalizing each block and averaging its outputs is wrong.

Online-softmax drill: why is max rescaling necessary?

Suppose the old maximum is 2 and a new block has maximum 7. Old exponentials were scaled by exp(−2), but new ones are scaled by exp(−7). Multiply old ℓ and u by exp(2−7)=exp(−5) before adding the new block. Both then represent the same global numerator and denominator. A simple arithmetic mean of normalized block outputs gives each block equal mass even when their score evidence differs.

PagedAttention solves a different problem

Paged KV storage maps logical sequence blocks to noncontiguous physical blocks, reducing waste from reserving large contiguous buffers and enabling controlled block sharing. It does not make attention sparse or reduce the logical KV entries by itself. Prefix sharing can reduce physically duplicated KV when token prefixes, positions, model state, and isolation constraints match. Paging and FlashAttention-style kernels can be complementary, subject to implementation support. [10]

Change the operator only when the trade-off is acceptable

ApproachWhat changes?Key caveat
Sliding window width wEach query reads a local neighborhood; pairwise work Θ(nwd)Without global links, distant influence needs multiple layers and can be weak
Block sparse / local plus globalA selected attention graphPattern affects quality; unstructured theoretical sparsity may not speed up hardware
Kernel linear attentionReplace or approximate softmax affinity with feature-map productsFeature width and recurrent-state capacity matter; not arbitrary exact softmax
KV quantizationStore lower-precision historyChanges numeric values; account for scales, outliers, dequantization, quality
Context / ring parallelismDistribute sequence blocks and communicationGlobal arithmetic remains; network traffic and topology become important

A causal local window that covers w positions including the query lets information travel at most roughly L(w−1) positions backwards over L plain local-attention layers. This is a graph reachability bound, not guaranteed useful recall. Global tokens, dilation, and interleaved full attention change the bound.

Why linear attention can be recurrent

Choose a feature map φ into r dimensions with a suitable nonnegative kernel approximation or replacement, w(q,k)=φ(q)ᵀφ(k). Then:

Sₜ = Sₜ₋₁ + φ(kₜ)vₜᵀ   [r,dv]
zₜ = zₜ₋₁ + φ(kₜ)   [r]
oₜ = φ(qₜ)ᵀSₜ / (φ(qₜ)ᵀzₜ)

Use a valid denominator policy, often with a small stabilization term. Fixed r,dv gives a state independent of history length and Θ(nrdv) sequence work, but that fixed state can lose token-specific information. Ordinary softmax generally prevents simply reassociating softmax(QKᵀ)V into Q(KᵀV); the feature-map operator is a mathematical change or approximation. SSM and gated recurrent hybrids offer other sequence-mixing mechanisms and are not all instances of this exact recurrence. [11]

Ring attention can circulate KV blocks among devices while queries remain partitioned, combining block softmax statistics as computation proceeds. It distributes capacity and can overlap communication with compute; it does not abolish dense pairwise work. Tensor parallelism partitions model features/heads, whereas context parallelism partitions sequence positions. Their communication patterns differ. [14]

10 / Production & multimodal

Turn a correct operator into a reliable system

Correctness gates before performance claims

  1. Match a small float64 reference, including forward outputs and gradients.
  2. Check causal isolation by perturbing future tokens; test padding and packed-sequence isolation.
  3. Compare full inference with one-token and uneven chunked KV inference using identical weights, positions, and disabled dropout.
  4. Test dtype/device behavior, empty-support policy, head mapping, and large score magnitudes.
  5. Only then benchmark realistic shapes and verify which kernel actually ran.

A fast kernel that silently falls back is not evidence of a hardware limitation until you inspect dtype, head width, strides, mask layout, dropout, and backend support. API support changes by version. Measure after warmup, synchronize asynchronous GPU work for timing, and separate kernel microbenchmarks from end-to-end request measurements.

SymptomLikely causes to isolateDiscriminating test
Full inference correct, decode wrongCache offset, double RoPE, KV group mapping, stale cacheCompare each layer and each chunk against full causal reference
NaNs only in padded batchesAll-masked rows, invalid mixed-precision scoresPrint valid-key count and max finite logit per query
Quality falls only for long inputsTruncation, position mismatch, lost-middle behavior, reduced evidence densityHold evidence fixed and sweep its location and distractor length
OOM at high concurrencyKV growth, fragmentation, workspaces, prefill peaksMemory accounting across weights, cache, activations, allocator reserves
Higher throughput, worse p99 latencyBatching/queueing policy, long prefills blocking decodeTrace queue wait, prefill, and per-token latency separately

Long-context evaluation must test use, not admission

“Accepts 128K tokens” means the implementation admits that input, not that the model retrieves or reasons over all of it. Evaluate evidence at the beginning, middle, and end; vary distractor count and contradiction. Test exact retrieval, multi-evidence aggregation, and the real task. Pair accuracy with confidence intervals and slice-level recall, especially for rare severe errors. Perplexity is useful but can be dominated by local prediction. [12]

Attention sinks are positions that receive disproportionate mass in some trained models even without obvious semantic relevance. Keeping a small initial prefix plus a recent window can stabilize some streaming setups, but evicted middle evidence is still unavailable for direct retrieval. Do not implement “keep sink tokens” as a universal cache policy without quality and security tests. [15]

Multimodal attention has a token-budget problem

For simple nonoverlapping patches, an image of H×W pixels with patch edge P produces (H/P)(W/P) patch tokens when dimensions divide evenly, before special tokens or merging. A 448×448 image with P=14 produces 1024 patches. If ten video frames use the same representation, that is 10,240 visual tokens before compression. These are illustrative geometry calculations, not a particular deployed model’s tokenization.

Full joint self-attention over text and image tokens allows all-to-all mixing but costs quadratically in combined length. Text-to-vision cross-attention costs Θ(ntext·nvision·d) for that interaction and can reuse fixed visual K/V, but does not itself let all visual tokens interact at every text layer. Resampling, patch merging, adaptive crops, and temporal sampling trade token budget against lost fine detail.

Applied-science case: ad content moderation

Suppose a multimodal moderator must check image text and landing-page evidence against policy definitions. Distinguish three failures: required evidence never entered the context, the model failed to attend/use available evidence, or the policy decision rule was wrong. A heatmap cannot identify which failure occurred by itself. Keep OCR spans, source identifiers, and page snapshots as auditable evidence; validate output claims against them.

Measure severe-defect recall and leakage alongside automation rate, per-asset cost, and latency. Stratify by tiny text, language, long landing pages, repeated frames, and contradictory evidence. Compare attention architecture changes at a controlled token budget and also at a controlled quality target. A cheaper model that misses rare severe defects can be the wrong system even when average accuracy improves.

Security boundary. Causal masks regulate token visibility, not trust. Untrusted page text can still contain instructions that try to override the moderation task. Separate instructions from evidence, constrain tool privileges and outputs, and evaluate prompt injection. High attention weight on a hostile instruction does not grant it authority.

A defensible optimization recommendation

For an existing dense model, first confirm correctness and the serving bottleneck. Use a compatible fused exact-attention implementation before changing the learned operator. If decode KV bandwidth or capacity dominates, evaluate GQA/MLA checkpoints or supported KV quantization with task-quality gates. If long multimodal prefill dominates, reducing redundant input tokens may help more than tuning the decoding cache. Choose from measured bottlenecks, not from whichever attention acronym is newest.

11 / Last-minute recall sheet

The whiteboard sheet

Reproduce this from memory before the interview. Every formula below has a domain of validity; say it aloud.

PromptSay / write thisDo not forget
DefinitionO=softmax(QKᵀ/√dk + mask + bias)VSoftmax over keys, independently for each query and head.
ShapesQ[nq,dk], K[nk,dk], V[nk,dv] → O[nq,dv]nq need not equal nk. dk need not equal dv.
ScaleVar(q·k)=dk → Var(q·k/√dk)=1Independent zero-mean unit-variance coordinates are assumptions.
Softmax gradientJ=diag(a)−aaᵀLarge score gaps can saturate it.
BackwarddV=AᵀG; E=GVᵀ; D=A⊙(E−rowsum(A⊙E)); dQ=DK/√dk; dK=DᵀQ/√dkBroadcast row sums. Dropout omitted.
MHA parameters4d², no biases, total projected width dFixed d means more heads are narrower, not free extra model width.
Forward full-sequence FLOPs8Bnd² + 4Bn²d for standard MHA projections plus attention matmulsMultiply-add counted as 2 FLOPs; excludes softmax, FFN, backward. Causal kernels can skip masked work.
Decode one new token at cache length tO(Bd² + Btd) per layerFor standard fixed-width MHA; excludes FFN and vocabulary head.
KV memory2BLtHkv dh × bytesUse KV heads, not query heads. GiB = 2³⁰ bytes.
Cache maskkey_abs_pos ≤ query_abs_posA fresh upper-left triangle can be wrong for rectangular cached queries.
FlashAttentionExact dense operator, tiled online softmax, less HBM traffic and intermediate storageNot linear arithmetic complexity. “Exact” allows floating-point rounding differences.
PagedAttentionPaged KV-cache storage and addressingNot a sparse-attention pattern; does not by itself reduce logical KV elements.
RoPE(Rm q)ᵀ(Rn k)=qᵀR(n−m)kCache positions correctly; relative form does not guarantee length extrapolation.
GQA / MQASeveral / one KV head shared across query headsQuery-head attention work remains; quality and kernel support matter.
ExplainabilityWeights show one mixing mechanism, not a causal attributionValues, projections, residuals, other layers, and interventions matter.

Coverage map: know what kind of interview you are practicing

Question familyQuestion IDsWhat a strong answer demonstrates
Foundations001–020You can explain weighted selection, Q/K/V roles, masking, and softmax without relying on slogans.
Mathematics021–040You can derive scaling, gradients, invariances, and edge cases and state assumptions.
Architecture041–060You know how heads, positional information, residuals, normalization, and objectives fit together.
Implementation061–075You can write correct tensor code and expose mask, precision, cache, and evaluation-mode bugs.
Systems076–095You can calculate cost and distinguish arithmetic, memory capacity, bandwidth, and scheduling.
Research and variants096–110You can explain what an alternative changes, what it preserves, and how to evaluate the trade-off.
Applied design111–120You can make a constrained recommendation and connect correctness and model quality to serving metrics.

Search by an ID such as q076 to jump to a specific prompt. The question bank repeats important concepts with different follow-ups so you practice retrieval, not just recognition.

Glossary: translate the shorthand

TermPlain meaning
ActivationAn input-dependent intermediate value, such as Q, K, V, or a hidden state. It is different from a learned parameter.
LogitA score before a probability-normalizing function. Attention logits rank keys; vocabulary logits rank next-token candidates.
Residual streamThe per-token hidden representation that sublayers update by adding their outputs.
Head dimensionThe feature width inside one attention head. Often d/H, but not a universal architectural requirement.
PrefillProcessing known prompt tokens to produce hidden states and usually populate the KV cache.
DecodeComputing subsequent output tokens, usually one autoregressive step at a time.
TTFT / TPOTTime to first token / time per output token. TTFT can include queueing and preprocessing as well as prefill; define your measurement boundary.
HBM / SRAMLarge GPU high-bandwidth memory / small on-chip fast memory. Moving values between them can dominate runtime.
Bandwidth-boundSpeed is limited primarily by moving data rather than by available arithmetic throughput.
FLOPA floating-point arithmetic operation. This guide counts a multiply and add as two FLOPs; other sources may report multiply-accumulates instead.
KV cacheStored per-layer keys and values for already processed tokens, reused by later queries.
Receptive fieldThe positions that can influence a representation directly or through multiple layers. Visibility does not guarantee effective use.
EquivarianceChanging an input by a transformation causes a corresponding transformation of the output. Invariance means the output does not change.
AblationA controlled removal or change used to test what contributes to observed behavior.
Kernel, two meaningsA similarity function in kernel methods; or an executable low-level GPU routine. FlashAttention's GPU kernel is not a kernel-feature approximation.

The 45-second answer

“Attention lets each query form an input-dependent weighted sum of values. Learned projections produce queries, keys, and values; query-key dot products become a distribution over permitted keys using scaled row-wise softmax. The scale √dk controls score variance under standard initialization assumptions. Multi-head attention learns several such mixtures, then projects their concatenation. A decoder adds a causal mask so each position cannot read future tokens. Dense full-sequence attention has quadratic pairwise work, while cached one-token decode reads a growing KV history. Faster kernels, smaller KV representations, and sparse patterns address different bottlenecks.”

Red flags that lose an otherwise good interview

12 / 120 interview questions

120 ways to test your understanding

Every question includes a direct answer, an answered follow-up, and a trap. Core questions check mechanism; applied questions check implementation and use; advanced questions test derivations and trade-offs. There is deliberate reinforcement across chapters and questions, but these are distinct prompts.

120 of 120 questions0 solid · 0 to review · 120 ungraded
001What is attention in one precise sentence?Core

Answer. For each query, compute compatibility scores with permitted keys, normalize those scores, and return a weighted sum of the associated value vectors. In standard softmax attention without dropout, the coefficients are nonnegative and sum to one. The output is a value mixture, not a key or token index.

Follow-up. Must all attention normalize to one? No. That is the contract of normalized softmax attention; other gating or attention operators can use different rules.

Trap. “Focus on important words” describes an intuition, not the computation.

002What are queries, keys, values, and their learned projection matrices?Core

Answer. Q, K, V are input-dependent activations. WQ, WK, WV are learned parameters that map hidden states into matching and payload spaces. A query describes what a position seeks; keys describe candidates for matching; values carry information to mix. The same projection parameters are normally shared across sequence positions within a layer.

Follow-up. Why separate keys and values? Features that identify useful information need not be the features you want to return.

Trap. Calling Q, K, V the learned weights confuses activations with parameters.

003Why can self-attention have different Q, K, and V?Core

Answer. Self-attention means all three come from the same source sequence, not that they are identical. Different projections of X produce different roles: Q=XWQ, K=XWK, V=XWV. In deeper layers X already contains contextual information from earlier layers.

Follow-up. What if WQ=WK? Unmasked logits become a symmetric Gram matrix, but row-softmax weights need not be symmetric. A larger-norm other key can score above the query’s own key.

Trap. Tied Q/K does not guarantee maximal self-attention.

004Why use a weighted average instead of a plain average or an argmax?Core

Answer. A plain average ignores the query and mixes all values equally. A learned content-dependent mixture can favor different sources for different inputs. Soft weights also allow gradients to flow through scores. Hard argmax selection is discontinuous and has zero derivative almost everywhere with respect to scores.

Follow-up. Can hard retrieval still be learned? Yes, using surrogate losses, relaxations, or separate retrieval training. Ordinary backpropagation through the discrete selection itself is not enough.

Trap. A differentiable mixture is not guaranteed to be the best retrieval system for every scale.

005What does a dot-product score measure?Core

Answer. q·k = ||q|| ||k|| cos(theta), so it combines angular alignment and vector norms. Norms can carry learned signal or cause overly large scores. Calling the score similarity does not mean it is cosine similarity or a calibrated relevance probability.

Follow-up. How does cosine attention differ? Normalize Q/K norms and typically introduce a temperature or scale to control score spread.

Trap. A larger score can come from a larger norm rather than a better directional match.

006Compare additive, bilinear, and dot-product attention.Applied

Answer. Additive attention uses a learned function such as uᵀtanh(Wq q + Wk k + b). Bilinear attention scores qᵀWk. Dot product uses qᵀk, often after separate projections. Dot products map naturally to efficient matrix multiplication; additive scoring offers a different parameterization and can reconcile different source widths.

Follow-up. Is additive always more expressive in practice? No unconditional ordering follows without specifying width, parameter budget, and scoring family.

Trap. Hardware efficiency and parameterization matter more than a blanket ranking of scoring functions.

007Which axis does softmax normalize, and how would you test it?Core

Answer. For scores shaped [B,H,nq,nk], softmax runs along nk, the last axis. Each query/head receives a separate distribution over permitted keys. Columns generally do not sum to one. Normalizing queries instead produces a different operator while preserving plausible tensor shapes.

Follow-up. What test catches the error? Use rectangular nq≠nk and assert each valid row sums to one before dropout; compare a scalar reference.

Trap. Shape checks alone cannot detect the wrong softmax axis.

008Why divide by the square root of key width?Core

Answer. Under independent zero-mean unit-variance query/key coordinates, q·k is a sum of dk products with variance dk. Dividing by sqrt(dk) gives variance one, limiting initial score spread and reducing softmax saturation. This uses per-head key width, not sequence length.

Follow-up. Why not divide by dk? Under the same assumptions, variance becomes 1/dk and increasingly flat scores are encouraged.

Trap. The initialization argument is not a permanent guarantee after learning.

009What does temperature do to attention, including tied maxima?Applied

Answer. For tau>0, softmax(s/tau) sharpens as tau decreases and flattens as tau increases. As tau approaches zero, a unique maximum gets all mass; tied maxima split mass equally. As tau approaches infinity, all finite permitted scores get uniform mass.

Follow-up. Can you change tau at inference? Yes mechanically, but it changes the learned function and needs quality evaluation. Attention temperature is separate from vocabulary sampling temperature.

Trap. Masked keys remain excluded; the uniform limit is over permitted finite keys.

010Why does subtracting the maximum make softmax stable?Core

Answer. Adding or subtracting a common row constant cancels between numerator and denominator. Subtracting the maximum makes the largest exponent one and all others at most one, preventing overflow from large positive logits. It preserves the mathematical probabilities.

Follow-up. Does it fix an all-masked row? No. If every score is negative infinity, maximum subtraction is undefined and there is no distribution over an empty support.

Trap. Stability tricks do not replace an explicit empty-support policy.

011What exactly does a causal mask allow?Core

Answer. In standard next-token training, query position i can read keys j≤i, including itself. The hidden state at i predicts token i+1 because the targets are shifted. Mask future logits before softmax. Causality is about the prediction factorization, not making every attention matrix strictly lower triangular.

Follow-up. What if labels are unshifted? The model can learn to copy the visible current token, so a causal mask alone does not prevent that leakage.

Trap. Diagonal permission and target shifting must be reasoned about together.

012What should happen when every key is masked for a query?Applied

Answer. A transparent all-negative-infinity softmax is undefined. For a real query, fail fast unless the application defines another semantic result. For a padded query, exclude it or compute a safe fallback and zero its output before downstream use, then exclude its loss. Backend behavior may differ.

Follow-up. Why not use a finite negative sentinel? Equal finite sentinels produce a uniform distribution over forbidden keys, not tiny probabilities or an empty result.

Trap. Zeroing only the loss may not prevent intermediate NaNs from contaminating gradients.

013How do padding and packed-sequence masks differ?Core

Answer. Key-padding masks block nonexistent pad positions. Packed-sequence masks prevent one example from reading another example’s tokens in the same tensor. Combine permitted relations with logical AND, along with causality if needed. Padded query outputs or losses require separate handling.

Follow-up. Can position resets replace segment masks? No. Reused position indices do not stop attention across packed examples.

Trap. Specify whether Boolean True means allowed or blocked before combining masks.

014How is cross-attention different from self-attention?Applied

Answer. Cross-attention takes Q from one sequence and K/V from another. Its output length equals query length, while K/V share source length. A decoder can query encoder states, or text can query visual features. Self-attention uses one source sequence for all roles.

Follow-up. Is cross-attention causal? Not inherently. Permissions depend on the task; a fixed fully observed encoder source is usually visible in full except padding.

Trap. Self/cross describes data sources; causal/bidirectional describes visibility.

015When is attention output inside the convex hull of values?Applied

Answer. For ordinary softmax attention before dropout, each output row is a convex combination of allowed value rows. The claim concerns projected values, not raw embeddings. Dropout can break the row-sum constraint; output projection and residual addition change the space/result to which the claim applies.

Follow-up. What about signed weights? A signed combination need not be convex; it is affine only if the weights also sum to one.

Trap. Softmax does not produce negative weights merely because of rounding.

016Is attention a form of kernel regression?Applied

Answer. It resembles normalized kernel regression: o(q)=sum_j w(q,k_j)v_j / sum_j w(q,k_j), with softmax affinity w=exp(q·k/sqrt(dk)). Neural attention learns both matching features and payloads. This view helps derive feature-map alternatives.

Follow-up. Does that imply a symmetric positive-semidefinite token affinity matrix? Not generally: Q and K can use different projections and masks can be directional.

Trap. The similarity-function meaning of kernel differs from a GPU compute kernel.

017How does attention differ from external document retrieval?Core

Answer. Dense soft attention mixes available values inside a model layer. External retrieval commonly selects documents or passages from a much larger store and returns them as context or structured results. Retrieval can be learned, but discrete top-k selection is not the same differentiable weighted sum.

Follow-up. Can a mixture equal one original value without one-hot weights? Yes, for example when all values are equal.

Trap. Do not claim every possible source contributes: masks, sparsity, and numerical underflow matter.

018Why are attention weights insufficient as a causal explanation?Applied

Answer. Weights describe one layer/head’s mixing coefficients. Output effects also depend on values, output projections, residual paths, later layers, and the target prediction. Distinct attention patterns can produce the same output. High mass is not a calibrated probability that a token caused the decision.

Follow-up. What should you use instead? Combine attribution with controlled perturbations and behavior tests, stating baseline and causal assumptions. Integrated gradients is not automatically causal identification.

Trap. A plausible heatmap or generated rationale is evidence to inspect, not proof.

019Did attention originate with the Transformer?Core

Answer. No. Recurrent encoder-decoder models used attention to access multiple source hidden states instead of relying only on a final compressed state. Bahdanau-style additive alignment and Luong-style scoring predate Transformers. The Transformer made attention the primary token-mixing mechanism rather than recurrence.

Follow-up. What bottleneck did it address? The decoder no longer had to recover every source detail from one fixed final encoder vector.

Trap. Attention is a mechanism; Transformer is an architecture built around it.

020Why is causal training parallel but ordinary generation sequential?Applied

Answer. Teacher forcing supplies every training input token in advance. A causal mask lets each position compute without reading future content, so positions can be processed together within each layer. During ordinary generation the next input token is unknown until the previous prediction is selected.

Follow-up. What does caching remove? Repeated computation of previous K/V and causal prefix states, not the dependency on the newly generated token. Speculation can verify proposals in parallel.

Trap. The generation dependency is not proof that attention itself is inherently sequential.

021Derive the full tensor shapes for one attention head.Core

Answer. Q has shape [nq,dk], K [nk,dk], and V [nk,dv]. QKᵀ is [nq,nk]; row-softmax preserves that shape; multiplying by V gives [nq,dv]. Query and key feature widths agree; key and value sequence lengths agree.

Follow-up. Can dk differ from dv? Yes mathematically. A fast implementation may impose narrower supported shape constraints.

Trap. Neither equal query/key length nor equal key/value width is required by the basic equation.

022Derive the softmax Jacobian.Applied

Answer. For a_i=exp(s_i)/sum_j exp(s_j), differentiation gives da_i/ds_j=a_i(delta_ij−a_j). Therefore J=diag(a)−aaᵀ. Off-diagonal terms describe competition between logits. Row sums are zero because a uniform logit shift changes nothing.

Follow-up. What happens near one-hot? The entries become small, so score gradients can shrink. At temperature tau, differentiation with respect to unscaled scores adds 1/tau.

Trap. a_i(1−a_i) gives only the diagonal, not the full derivative.

023Derive gradients with respect to Q, K, and V.Advanced

Answer. Let G=dL/dO and A=softmax(QKᵀ/sqrt(dk)). Then dV=AᵀG, E=GVᵀ, and D=A elementwise-multiplied by (E−row_sum(A*E)). Finally dQ=DK/sqrt(dk), dK=DᵀQ/sqrt(dk). D is the gradient with respect to scaled logits.

Follow-up. How do input gradients combine in self-attention? Add dQ WQᵀ, dK WKᵀ, and dV WVᵀ because X feeds all three branches.

Trap. Do not omit the scale or treat the softmax Jacobian as elementwise.

024Derive softmax from an optimization problem.Advanced

Answer. Maximize sum_j a_j s_j + tau H(a) over the probability simplex, where H(a)=−sum_j a_j log a_j and tau>0. Lagrange stationarity yields s_j−tau(log a_j+1)+lambda=0, so a_j is proportional to exp(s_j/tau). Normalizing gives softmax.

Follow-up. How do masks enter? Restrict the simplex to permitted keys. An empty feasible support does not define a distribution.

Trap. Entropy reward has a positive coefficient; confusing its sign gives the wrong optimizer.

025Prove unpositioned self-attention is permutation equivariant.Applied

Answer. For row permutation P, Q′=PQ, K′=PK, V′=PV. Scores transform as PSPᵀ and row-softmax gives A′=PAPᵀ. Therefore O′=A′V′=PAV=PO. This requires shared token projections and no fixed order-dependent information.

Follow-up. When is the output invariant instead? A symmetric pooling operation such as mean can make a sequence-level readout invariant.

Trap. A fixed causal mask or fixed positions generally breaks arbitrary token-permutation equivariance.

026What permutation leaves cross-attention outputs unchanged?Applied

Answer. For fixed queries, jointly permuting K and V preserves their pairings and leaves the weighted sum unchanged. Corresponding mask and score-bias columns must be permuted too. This differs from self-attention equivariance, where queries also move.

Follow-up. What if only K is permuted? Keys then select the wrong payload associations, changing the function in general.

Trap. Order-insensitive source aggregation requires all relevant source metadata to transform consistently.

027Do low-rank logits imply low-rank attention weights?Advanced

Answer. No. rank(QKᵀ)≤dk, but row-wise softmax is nonlinear. Q=K=[[0],[1]] gives rank-one logits [[0,0],[0,1]], while probabilities [[1/2,1/2],[1/(1+e),e/(1+e)]] have nonzero determinant and rank two.

Follow-up. Does full rank imply arbitrary attention expressivity? No. Low-dimensional parameterization still constrains which logit relationships are possible.

Trap. Do not move softmax through a low-rank factorization as if it were linear.

028Is the attention matrix symmetric when Q equals K?Applied

Answer. The unmasked score matrix QQᵀ is symmetric. Row normalization uses different denominators for different rows, so softmax(QQᵀ) need not be symmetric. Causal or asymmetric masks can also remove score symmetry.

Follow-up. Must self-score be largest? No. If q=[1] and another key=[2], q·k_other=2 exceeds q·q=1. Equal normalized vector norms change that comparison.

Trap. Symmetric logits and symmetric probabilities are different properties.

029What changes if every score in a row receives the same constant?Applied

Answer. Nothing changes in softmax: exp(s_j+c) shares a common factor exp(c), which cancels. The output stays the same for fixed values. This gives stable max-subtraction and a null direction of the softmax Jacobian.

Follow-up. What if the constant is added to one column across all queries? That favors one key in each row and generally changes outputs.

Trap. Row-wise shift invariance is not invariance to arbitrary elementwise shifts.

030Which Q/K transformations leave dot-product attention unchanged?Advanced

Answer. For invertible R, replacing Q by QR and K by K R^(-T) preserves QKᵀ. A simple case scales Q by c and K by 1/c. This non-uniqueness shows that individual matching coordinates are not uniquely identifiable from scores.

Follow-up. What if both are scaled by c? Scores scale by c², changing softmax sharpness unless c²=1 or the scores are degenerate.

Trap. Preserving a product does not mean transformed parameters have identical optimization or regularization behavior.

031What if every value vector is identical?Core

Answer. With normalized weights and no attention dropout, every output is that same value vector regardless of the score distribution. Q/K can change without changing O. This holds with masks as long as at least one value remains permitted.

Follow-up. What happens to score gradients for a loss depending only on that mixture? They cancel because the mixture is independent of scores; gradients to values can still flow.

Trap. Different attention maps do not necessarily mean different outputs.

032What happens when exactly one key is permitted?Applied

Answer. Its softmax weight is one, and the output equals its value. The normalized distribution is constant with respect to its finite score, so score gradients for that row are zero. The value path still receives gradients.

Follow-up. Is this the same as all keys masked? No. One-key support defines a valid distribution; empty support does not.

Trap. A zero score gradient can be mathematically correct, not a failed implementation.

033What does duplicating a key-value pair do?Applied

Answer. Duplicating one pair adds another identical exponential term to the softmax denominator and doubles that pair’s combined unnormalized mass. Unless the surrounding configuration makes it irrelevant, the output changes. Duplicating every pair equally preserves the mixture under content-only attention.

Follow-up. How can this matter in context design? Repeated evidence can attract more aggregate mass without being more reliable. Position encodings can further distinguish duplicates.

Trap. Attention is not automatically invariant to repeated copies of one source.

034Why cannot you replace softmax(QKᵀ)V with Q(KᵀV)?Advanced

Answer. Associativity applies to matrix multiplication, but softmax is a nonlinear row normalization inserted between products. Removing it changes both weighting and normalization. Feature-map linear attention creates a different or approximate affinity that can be evaluated associatively with a separate denominator.

Follow-up. When can reassociation be exact? For the unnormalized linear operator (QKᵀ)V, assuming identical arithmetic idealizations; finite precision can still differ.

Trap. An algebraic speedup must preserve every intervening operation, not just matrix dimensions.

035How would you independently check an attention backward pass?Applied

Answer. Use small float64 Q/K/V and a scalar loss such as sum(O*G). Perturb each input coordinate by ±epsilon and compare the centered difference to the analytic gradient. Disable dropout and avoid highly saturated logits. Test masks with nonempty support.

Follow-up. Why both absolute and relative tolerances? Relative error is unstable near zero gradients; absolute error alone may hide large proportional errors.

Trap. A finite forward output does not establish correct gradients.

036What assumption does the usual dot-product variance derivation hide?Advanced

Answer. It needs control of coordinate-product means, variances, and cross-coordinate covariances. Independence and zero-mean unit-variance coordinates are convenient sufficient conditions. Shared or correlated learned projections can violate them, particularly self-scores with Q/K tied.

Follow-up. What is the general warning? Var(sum z_i)=sum Var(z_i)+2 sum_{i<j} Cov(z_i,z_j). Covariances need not vanish after learning.

Trap. LayerNorm normalizes token features but does not prove query-key products are independent.

037Can attention dropout change the row sum and convex-hull property?Applied

Answer. Yes. Standard inverted dropout samples entries of A, zeros some, and scales survivors by 1/(1−p). A particular row need not sum to one, so its output need not be a convex combination. Conditional on A and V, the expected output matches AV.

Follow-up. Does evaluation keep that randomness? A module dropout layer disables it in eval; functional SDPA requires dropout_p=0 explicitly.

Trap. Expectation-preserving is not sample-by-sample normalization-preserving.

038Why can attention have a large receptive field but still forget distant evidence?Advanced

Answer. A direct permitted edge only makes information accessible. Learned logits, value compression, competing distractors, limited head width, later processing, and training distribution determine whether it is used. Long paths are not required for dense attention, but useful retrieval is not guaranteed.

Follow-up. What experiment separates access from use? Fix evidence and move it across context depth while controlling token budget and distractors; evaluate the actual answer.

Trap. Graph reachability is not an accuracy guarantee.

039Is content-only attention translation invariant like a convolution?Applied

Answer. Neither per-position operator should casually be called translation invariant. Convolutions are translation equivariant under suitable boundary assumptions. Content-only attention is permutation equivariant, which includes compatible shifts/permutations. Relative-position attention can preserve shift relations when masks and boundaries transform consistently.

Follow-up. What produces invariance? An appropriate symmetric global readout can remove output-position dependence.

Trap. Conflating invariance with equivariance is the error; boundaries and positional information matter.

040What numerical problems remain after stable softmax?Advanced

Answer. Max subtraction prevents exponential overflow for finite scores, but QKᵀ can overflow before softmax, tiny probabilities can underflow, reductions can accumulate rounding error, and all-masked rows remain undefined. Large or nonfinite values can also corrupt AV.

Follow-up. How do you respond? Check score/value ranges, use appropriate accumulation precision, validate inputs/masks, and compare to a high-precision reference.

Trap. “Numerically stable softmax” does not mean the entire attention block is numerically safe.

041Why use multiple attention heads?Core

Answer. Each head computes a separate query-dependent distribution and value mixture. This allows different feature subspaces to use different routing patterns at the same position. One wide head uses one distribution across its value coordinates. Learned output projection mixes the concatenated results.

Follow-up. Do heads correspond to human concepts? Sometimes interpretable patterns emerge, but fixed roles are not guaranteed and heads may be redundant.

Trap. Multi-head structure is not simply an ensemble of independent complete models.

042How many parameters does standard MHA have?Applied

Answer. At residual width d with combined query/key/value widths each d, the three input projections contribute 3d² weights and the output projection d², totaling 4d² without biases. Splitting into H heads of width d/H does not multiply that count by H.

Follow-up. What changes the calculation? Different key/value widths, GQA KV projections, biases, or a different output width.

Trap. State whether total width or per-head width is held fixed when comparing head counts.

043What are the exact reshape steps in batched MHA?Applied

Answer. Project X[B,T,d] into Q/K/V, reshape each into [B,T,H,dh], then transpose to [B,H,T,dh]. Compute scores [B,H,T,T] and mixtures [B,H,T,dh]. Transpose back before merging H and dh, then apply WO.

Follow-up. Why can view fail after transpose? Strides may be noncontiguous. reshape can copy; contiguous().view makes the storage requirement explicit.

Trap. Reshape alone does not permute the head and sequence axes.

044What is the role of the output projection?Core

Answer. Concatenation preserves separate head outputs; WO maps that combined feature vector to the desired residual width and mixes information across heads. It is a learned linear operation, not another attention distribution.

Follow-up. Can WO be omitted? It defines a valid variant if dimensions fit, but changes expressivity and parameterization relative to standard MHA.

Trap. The post-projection output need not stay inside the original values’ convex hull.

045Do more heads always improve a fixed-width model?Applied

Answer. No. With fixed d, increasing H reduces dh. More independent mixtures trade against narrower per-head matching/payload spaces. Leading projection and pairwise matmul costs can stay similar, while score storage, softmax overhead, and hardware efficiency change.

Follow-up. How would you choose H? Compare quality and real workload latency at controlled width, parameter budget, training setup, and context length.

Trap. Same leading-order arithmetic is not identical runtime or an unconditional expressivity improvement.

046What does the feed-forward sublayer add beyond attention?Core

Answer. Attention mixes information across positions. The FFN applies a learned nonlinear feature transformation independently to each token using shared weights. A common form expands width, applies an activation, and projects back; gated variants use multiplicative feature interactions.

Follow-up. Is FFN optional mathematically? A model without it is possible, but it is a different architecture and often has different capacity and training behavior.

Trap. Do not describe attention and FFN as interchangeable because both contain matrices.

047Compare pre-norm and post-norm Transformer blocks.Applied

Answer. Pre-norm uses X+Sublayer(Norm(X)); post-norm uses Norm(X+Sublayer(X)). Pre-norm preserves a direct residual gradient path and often makes deep optimization easier. The original Transformer used post-LayerNorm. Neither arrangement universally wins on every quality/optimization metric.

Follow-up. Why do residuals matter? They let sublayers learn refinements around an identity path and improve optimization; they are not a mathematical prerequisite for defining attention.

Trap. Easier training is not proof of universally better final accuracy.

048How do LayerNorm, RMSNorm, and attention softmax differ?Applied

Answer. LayerNorm normalizes each token across feature dimensions using mean and variance, typically with learned affine parameters. RMSNorm scales by root mean square without subtracting the mean. Attention softmax normalizes candidate-key logits into a per-query distribution. These operations act on different axes and serve different purposes.

Follow-up. Does either feature norm guarantee stable QK scores? No. Learned projections and correlations still matter.

Trap. Do not substitute feature normalization for key-axis softmax or its scaling argument.

049Compare encoder-only, decoder-only, and encoder-decoder attention.Core

Answer. An encoder commonly uses bidirectional self-attention over observed input. A decoder-only language model uses causal self-attention to model a next-token factorization. An encoder-decoder adds target-side causal self-attention plus cross-attention to encoded source states. Objectives and visibility must match intended use.

Follow-up. Can an encoder become a decoder just by changing an inference mask? That defines a new computation but does not establish training for the desired conditional distribution.

Trap. Architecture, training objective, and generation procedure are separate but coupled choices.

050How does teacher forcing differ from free-running generation?Applied

Answer. Teacher forcing supplies the true previous target tokens during training; free-running generation supplies the model’s previous selected tokens. Both can use the same causal attention rule, but the input distributions differ when generated history contains errors.

Follow-up. Does a causal mask eliminate that distribution shift? No. It prevents future access, not exposure to model-generated prefixes.

Trap. Mask correctness and robustness to accumulated generation errors are different issues.

051How do sinusoidal and learned absolute positions differ?Applied

Answer. Learned positions are a trainable lookup table with a finite supported index range. Sinusoidal vectors are generated from fixed frequencies and can be evaluated at any index. Both are often added to token embeddings, introducing absolute-index information through projected content/position interactions.

Follow-up. Does a defined sinusoid imply reliable extrapolation? No. The model may not use unfamiliar positions or distances well without suitable training.

Trap. Mathematical addressability and task-level usable context are not the same.

052Derive the central rotary-position identity.Advanced

Answer. For column vectors, q_rot=R(mθ)q and k_rot=R(nθ)k. Then q_rotᵀk_rot=qᵀR(mθ)ᵀR(nθ)k=qᵀR((n−m)θ)k. Repeat over coordinate pairs with different frequencies. The explicit rotation depends on relative offset.

Follow-up. Does the whole model become shift invariant? Not necessarily. Content hidden states, masks, and other positional signals can change. The identity holds with underlying q/k fixed.

Trap. A transpose changes the sign of the first rotation; do not reverse the relative offset accidentally.

053What must be cached when using RoPE?Applied

Answer. In a common RoPE decoder, store each key after applying its intended logical position once; values are usually unrotated. New queries/keys use continued logical positions, not local chunk indices reset to zero. Preserve checkpoint-specific frequencies, pairing, and scaling.

Follow-up. What if a sliding cache evicts tokens? Physical storage offsets can change while logical positions continue. Keep those notions separate.

Trap. Applying rotation twice or resetting positions silently breaks cache parity.

054How does ALiBi encode position?Applied

Answer. It adds a negative distance-dependent logit bias with a different fixed slope per head. For causal key n≤query m, a common form subtracts slope_h*(m−n). This imposes recency preference without input position vectors.

Follow-up. Does it guarantee retrieval beyond training length? No. The formula extrapolates, but quality remains model/task-dependent and the recency penalty can suppress distant evidence.

Trap. The exact original slope schedule depends on head count; a single eight-head example is not the general formula.

055What can go wrong when extending RoPE context length?Advanced

Answer. New distances and phase combinations can be unfamiliar; learned retrieval behavior may not extrapolate. Position interpolation compresses the target index range, changing local angular resolution. Base or frequency-aware scaling changes that trade-off differently. Serving must match the trained configuration.

Follow-up. How do you validate an extension? Measure short-context regressions, evidence-depth curves, long-document reasoning, and cache parity, not just successful allocation or perplexity.

Trap. Context extension is not a universally safe configuration-only optimization.

056How is attention used in a Vision Transformer?Applied

Answer. Image patches are projected to token features, position information is added or incorporated, and attention mixes spatial tokens. With simple nonoverlapping P×P patches, an H×W divisible image yields (H/P)(W/P) patches before special tokens and merging.

Follow-up. What happens when both image dimensions double at fixed P? Token count quadruples; dense pairwise attention work grows about sixteenfold at fixed width.

Trap. Actual multimodal tokenizers can resize, merge, crop, or compress patches, so inspect the real pipeline.

057What is learned-query attention pooling?Applied

Answer. One or more learned queries attend over a sequence of input features to produce a fixed-size set of summaries. Query count sets output length independently of input length. Without positional information, jointly permuting source features preserves each query output.

Follow-up. Why multiple queries? They can learn different summary mixtures, though diversity is not guaranteed without suitable training signals.

Trap. A learned query vector is a parameter; its projected/contextual activation still depends on architecture.

058How are graph or channel attention related to Transformer attention?Applied

Answer. They share the broad idea of input-dependent weighting, but differ in axis, score function, and permission structure. Graph attention often aggregates allowed neighbors; channel attention may gate feature channels; spatial attention may weight image locations. Not every named attention module computes softmax(QKᵀ)V.

Follow-up. What should you clarify first? Which entities are queries/candidates, what is normalized, and whether information is gated or aggregated.

Trap. The word attention alone does not specify the operator.

059Why is multi-head attention not equivalent to one bigger softmax?Advanced

Answer. Separate heads have separate normalizations and can choose different mixtures for different feature subspaces. Combining all head features before one softmax instead produces one shared distribution based on the combined score. Nonlinearity prevents generally moving the split through softmax.

Follow-up. Can parameters make them equivalent in special cases? Yes, for example identical head distributions with compatible value/output mappings. That does not establish general equivalence.

Trap. A matched parameter count does not imply identical function classes.

060What belongs to attention versus the final language-model output head?Applied

Answer. Attention softmax distributes mass over context keys and creates hidden representations. A language-model head projects final hidden states to vocabulary logits; its loss or sampling softmax distributes mass over possible next tokens. They have different dimensions, meanings, and temperatures.

Follow-up. Where does MoE fit? Often in the feed-forward sublayer, routing tokens to experts rather than routing between token positions.

Trap. Attention probability is not the probability of the generated word or the truth of a source.

061What is the minimal contract of a batched attention function?Core

Answer. Specify Q[B,Hq,nq,dk], K[B,Hkv,nk,dk], V[B,Hkv,nk,dv], dtype/device, masks, head-group mapping, dropout, and output [B,Hq,nq,dv]. Validate sequence/feature compatibility and nonempty permitted support or a documented empty-row policy.

Follow-up. Why not validate only final shape? Wrong softmax axes and head mappings can return exactly the expected shape while changing semantics.

Trap. A correct-looking output shape is necessary, not sufficient.

062Why do PyTorch Boolean attention masks cause migration bugs?Applied

Answer. Functional scaled_dot_product_attention uses True for allowed entries. nn.MultiheadAttention Boolean attention and key-padding masks use True for blocked entries. Reusing the same Boolean tensor can therefore invert visibility while all shapes remain valid.

Follow-up. What test catches this? A tiny example with one allowed key and unmistakably different values; the output must equal the allowed value.

Trap. Mask conventions are API-specific, not an industry-wide rule.

063Why can SDPA remain stochastic after model.eval()?Applied

Answer. Functional SDPA applies dropout according to dropout_p, independent of a parent module’s training flag. Pass dropout_p=self.p if self.training else 0.0. A separate nn.Dropout module handles its own evaluation state, but a functional call does not infer it.

Follow-up. Is zero dropout sufficient for bitwise reproducibility? Not always. GPU kernels and reduction order can introduce nondeterminism or numeric differences.

Trap. Evaluation mode and gradient disabling are different controls.

064How should a causal mask align for a cached multi-token chunk?Advanced

Answer. With p previous tokens and m new queries, query row i is at p+i and may read key j≤p+i. Build [m,p+m] permissions from these absolute positions. The checked PyTorch non-square is_causal flag uses upper-left alignment, which is wrong for this appended-chunk layout.

Follow-up. Can one-token decode omit the causal mask? Yes if K/V contain only valid past/current keys, no future or unused slots, and padding is handled.

Trap. A rectangular triangle is meaningless until query/key positions are defined.

065How should a padded query with no permitted keys be handled?Applied

Answer. Do not feed an all-negative-infinity row into a naive softmax and hope the loss mask fixes it. Skip that row or temporarily supply a safe support and zero the query output before downstream use; exclude its loss. Real empty-support queries should fail unless another explicit semantic policy exists.

Follow-up. Why not post-hoc multiply NaNs by zero? IEEE arithmetic makes NaN*0 remain NaN, and backward can still propagate invalid values.

Trap. Finite sentinels manufacture distributions over forbidden keys.

066How do you prevent cross-example leakage in packed training?Applied

Answer. Combine causality with a same-segment permission relation and valid-key masks. Position resets or separator tokens alone do not enforce independence. Loss shifting must also respect example boundaries, so the last token of one example does not predict the first of another unintentionally.

Follow-up. What is a strong test? Change every token in one packed segment and verify outputs and losses of another independent segment remain unchanged.

Trap. A causal mask alone still exposes earlier packed examples.

067When does reshape silently copy, and why does it matter?Applied

Answer. Transposing a tensor changes strides, often making it noncontiguous. view requires a compatible memory layout; reshape may allocate a copy. In attention, transpose heads back into [B,T,H,dh] before merging. Copies can be correct but affect memory and latency.

Follow-up. How do you check? Inspect strides/contiguity and profile allocations, then compare semantic outputs with distinct per-head values.

Trap. Fixing a view error by arbitrary reshaping can preserve dimensions while scrambling head/token meaning.

068What precision policy should an educational attention reference use?Advanced

Answer. Use float64 for small numerical gradient checks. For low-precision inputs, accumulate scores/softmax and often AV in float32, while preserving float64 inputs rather than unconditionally downcasting. Check actual autocast behavior so an explicit float cast is not silently undone by operator policy.

Follow-up. How do production kernels differ? They may use mixed internal precision and reordered reductions. Compare with dtype-appropriate tolerances and task-level regression tests.

Trap. Exact mathematical attention does not require bitwise-identical floating-point outputs.

069Which tests should every attention implementation pass?Applied

Answer. Test shape and row sums, masked probabilities, causal future perturbation, padding/segment isolation, full-versus-cached parity, head mapping, and gradients. Include rectangular lengths, length one, uneven chunks, and invalid inputs. Use a transparent independent reference rather than comparing two wrappers around the same bug.

Follow-up. What test targets positional bugs? Compare full and incremental execution with nonzero cache offset and the actual rotary configuration.

Trap. Random square tensors alone provide weak coverage.

070Why should inference caches normally be detached from autograd?Advanced

Answer. Inference does not need training graphs for previous tokens; retaining them wastes memory. An inference-only cache can store detached K/V under no_grad or inference_mode. During training, detaching reused history would truncate gradients and change optimization, so the interface should reject accidental cache use.

Follow-up. Does eval() detach anything? No. It changes behaviors such as dropout, not autograd recording.

Trap. A serving optimization can be a training correctness bug.

071How do you implement the mapping in grouped-query attention?Applied

Answer. Map each query head to its intended KV group. For Hq=4,Hkv=2 and contiguous groups, indices are [0,0,1,1]. repeat_interleave on the head axis matches that pattern; whole-axis repeat yields [0,1,0,1]. A native kernel can reuse KV without materializing duplicates.

Follow-up. Is either mapping inherently impossible? No, but training and inference must agree on the architecture’s mapping.

Trap. Identical KV heads in tests hide mapping mistakes.

072Why is post-softmax masking usually the wrong implementation?Applied

Answer. Multiplying probabilities by a mask removes mass without renormalizing. Allowed weights then sum below one and output scale depends on invalid scores. Mask logits before normalization. Post-mask renormalization is mathematically equivalent for nonempty support in exact arithmetic but can be less stable.

Follow-up. What diagnostic input helps? Append masked keys with huge positive scores and distinctive values; valid outputs should remain unchanged.

Trap. A zero forbidden weight alone does not prove the remaining distribution is correct.

073Why does an SDPA call not guarantee FlashAttention execution?Applied

Answer. Backend selection depends on installed version, device, dtype, head dimensions, strides, masks, dropout, and other constraints. A math or memory-efficient fallback can preserve correctness but have different performance. Inspect backend diagnostics and kernel traces.

Follow-up. How do you benchmark fairly? Warm up, synchronize timing appropriately, fix shapes/dtypes, and separate end-to-end overhead from the kernel itself.

Trap. Function names are not evidence of which GPU kernel ran.

074How do you validate an optimized kernel’s gradients?Advanced

Answer. Compare outputs and gradients to a small high-precision reference with identical masks and no stochastic dropout. Check Q/K/V separately and test nontrivial rectangular shapes. For dropout-enabled comparisons, matching random masks or comparing appropriate statistics is necessary.

Follow-up. What if outputs agree but gradients do not? Inspect backward recomputation, softmax scaling, mask derivatives, and dtype conversions rather than accepting forward-only parity.

Trap. Forward parity does not validate training correctness.

075What makes a cached prefix unsafe to reuse?Applied

Answer. A cache depends on token IDs, positions, model weights/version, adapters, modality representations, and other state that affects hidden representations. Reusing it after a mismatch can silently change predictions. Sharing physical blocks across requests also needs authorization and isolation guarantees.

Follow-up. Does a matching raw prompt string suffice? No. Tokenization or model configuration may differ even for identical text.

Trap. Cache identity is broader than a string hash.

076Derive standard MHA forward FLOPs rather than saying O(n squared).Core

Answer. At batch B, length n, width d, four d×d projections cost 8Bnd² FLOPs when multiply-add counts as two. QKᵀ and AV together cost 4Bn²d at total head width d. This excludes softmax, normalization, FFN, and backward.

Follow-up. What about causality? A kernel that skips masked pairs reduces the quadratic constant; computing then masking the full matrix does not.

Trap. Different FLOP conventions can differ by two; state yours.

077How do prefill and one-token decode differ computationally?Applied

Answer. Prefill processes many known queries and has large matrix multiplications plus quadratic pairwise attention. Cached one-token decode computes one new query set and reads a growing history, with per-layer attention work O(td) plus projections O(d²). Decode often becomes memory-bandwidth sensitive, but workload and hardware decide.

Follow-up. Why does batch size matter? Batching changes arithmetic intensity, weight reuse, cache volume, and latency/queueing trade-offs.

Trap. Not every prefill is compute-bound or every decode bandwidth-bound.

078Calculate KV-cache memory for a concrete decoder.Core

Answer. For 32 layers, 8 KV heads, head width 128, 8192 tokens, batch one, and two-byte elements: 2*32*8*128*8192*2 = 1,073,741,824 bytes = 1 GiB. The factor two counts keys and values.

Follow-up. What if query heads are 32? GQA still stores 8 KV heads. Same-width MHA with 32 KV heads would store 4 GiB.

Trap. Use binary GiB and stored KV heads, not an unlabeled GB estimate.

079What does the KV payload formula leave out?Applied

Answer. It omits model weights, optimizer state if training, intermediate activations, temporary workspaces, allocator reservations/fragmentation, cache metadata, alignment, and quantization overhead. Prefix sharing or layer-specific representations can alter physical storage.

Follow-up. How do you choose concurrency? Budget complete peak memory with headroom and measure the serving allocator, rather than divide all GPU memory by logical KV bytes.

Trap. A payload-only maximum is not a safe production concurrency setting.

080How do MHA, MQA, and GQA trade cache memory for flexibility?Applied

Answer. MHA stores per-query-head K/V, MQA shares one KV head, and GQA shares K/V within groups. Fewer KV heads reduce K/V projection width and cache payload, while query heads still compute separate distributions. Quality and kernel efficiency are empirical.

Follow-up. Can you convert an MHA checkpoint by reshaping? Not losslessly in general. Averaging/grouping heads changes parameters and often needs uptraining or retraining.

Trap. Reducing KV heads does not proportionally remove all query-head attention arithmetic.

081How is MLA different from simply reducing KV heads?Advanced

Answer. Multi-head latent attention caches a compressed latent representation from which attention-relevant content is derived, often with separate rotary-position state. Suitable projections can be absorbed into query/output computations to avoid naively expanding every cached key/value at decode. Details depend on the architecture.

Follow-up. How do you calculate its memory? Count the actual latent and positional cache tensors per token/layer, not the standard Hkv*dh formula with an invented head count.

Trap. MLA is not just another spelling of MQA or GQA.

082What exactly does FlashAttention optimize?Applied

Answer. It tiles exact dense attention to reduce HBM reads/writes and avoid materializing the full score/probability matrix. Online softmax combines block statistics, and backward can recompute intermediates instead of storing them all. Pairwise arithmetic remains quadratic in sequence length.

Follow-up. Is it approximate? It computes the same mathematical operator, with possible floating-point differences from operation order.

Trap. Linear intermediate-memory scaling is not linear arithmetic complexity.

083Derive the online-softmax update used by tiled attention.Advanced

Answer. Maintain maximum m, sum l, and numerator u. For new block scores s, let m_new=max(m,max(s)), alpha=exp(m−m_new), and e=exp(s−m_new). Update l=alpha*l+sum(e), u=alpha*u+sum(e*v); normalize u/l after all blocks.

Follow-up. What about an all-masked tile? Skip it or handle zero prior mass explicitly; do not compute negative infinity minus negative infinity. Entirely empty rows still need policy.

Trap. Averaging independently normalized block outputs gives the wrong weights.

084What does PagedAttention change, and what does it not change?Applied

Answer. It manages logical KV blocks using noncontiguous physical storage, improving allocation utilization and enabling controlled sharing. It does not by itself change which logical keys each query attends to or reduce the number of logical KV elements.

Follow-up. Can it coexist with fused exact attention? Yes in compatible serving implementations, because cache layout and attention-kernel data movement solve related but distinct problems.

Trap. Paging is not sparse attention.

085Why might KV-cache quantization hurt differently from weight quantization?Advanced

Answer. Cache quantization directly perturbs context-specific keys and values. Key error changes scores and softmax weights; value error changes payloads. Effects can compound with context length, outliers, grouping, and task sensitivity. Weight quantization changes a different source of computation.

Follow-up. How would you evaluate? Sweep context length and evidence depth, compare severe-error slices, and account for scales, residual precision, dequantization cost, and memory savings.

Trap. Nominal four-bit payload is not automatically a fourfold end-to-end speedup.

086How does continuous batching affect attention serving?Applied

Answer. It admits and removes requests as they progress, improving utilization compared with waiting for a fixed batch to finish. Requests can have different cache lengths and prefill/decode phases, making scheduling, ragged layouts, and memory management important.

Follow-up. What is the trade-off? Larger batches can improve throughput while increasing per-request latency and cache pressure. Measure queueing and p99, not only aggregate tokens per second.

Trap. More batching is not universally better for interactive latency.

087Why use chunked prefill?Applied

Answer. Breaking a long prompt into chunks can reduce peak workspaces and let a scheduler interleave decode work, improving responsiveness under some workloads. Each chunk must attend to the permitted prior prefix and its own causal portion using correct positions.

Follow-up. Does it eliminate quadratic prompt attention? No. Exact attention over all prompt pairs still performs the required total pairwise work, though scheduling and memory peaks change.

Trap. Chunking execution is not the same as truncating the attention window.

088How does speculative decoding use attention without violating causality?Advanced

Answer. A draft proposes several tokens, and the target evaluates their conditional probabilities in a causal verification pass. Each candidate position sees only the accepted prefix and earlier proposed tokens. An appropriate acceptance/correction procedure can preserve the target sampling distribution.

Follow-up. Why does cache rollback matter? Rejected suffix states must not remain as accepted history. Track logical length and any paged blocks consistently.

Trap. Parallel verification does not permit later draft tokens to leak into earlier conditional scores.

089What is required for safe and correct prefix-cache sharing?Applied

Answer. Reuse requires identical token prefix and compatible model, adapter, position, and modality state. Reference-count shared blocks and apply copy-on-write or equivalent rules for divergence. Enforce tenant/data isolation and consider cache-hit side channels.

Follow-up. Can two prompts sharing a suffix share causal suffix K/V? Not generally: suffix representations depend on their different preceding contexts.

Trap. Matching visible token text somewhere in a prompt is insufficient.

090Compare tensor parallelism with context parallelism for attention.Advanced

Answer. Tensor parallelism partitions model features or heads across devices and typically communicates projected/output results. Context parallelism partitions sequence positions and requires exchanging K/V or partial attention statistics so queries see their permitted context. Both trade device capacity for communication.

Follow-up. Where does ring attention fit? It circulates KV blocks and combines exact block statistics while overlapping communication and compute where possible.

Trap. Distributing dense attention does not reduce its global pairwise arithmetic order.

091What determines whether ring attention actually speeds up a workload?Advanced

Answer. Block sizes, network bandwidth/latency, GPU compute, overlap, topology, sequence length, and balancing determine whether communication is hidden. Longer contexts may provide enough computation per block to amortize transfers; small workloads can be dominated by communication.

Follow-up. How do you validate correctness? Compare global outputs/gradients to a nonpartitioned reference, including causal and boundary masks.

Trap. Near-infinite context in a paper title is not unlimited practical memory or free communication.

092How should memory and time scale when prompt length doubles?Applied

Answer. At fixed width/batch, projection work doubles and dense pairwise attention work quadruples. Logical KV memory doubles. A naive stored attention matrix quadruples; fused attention can avoid storing that matrix. Actual runtime depends on which term and hardware bottleneck dominate.

Follow-up. What about one-token decode at twice the retained history? Its pairwise attention work and logical KV reads approximately double, with projections unchanged.

Trap. A single quadratic slogan cannot describe every phase or memory category.

093Why can a theoretically cheaper sparse attention implementation run slower?Applied

Answer. Sparse indexing, irregular memory access, small matrix blocks, launch overhead, low hardware occupancy, and unsupported layouts can outweigh arithmetic savings. Dense GEMMs exploit highly optimized hardware. Structured block sparsity is often easier to accelerate than arbitrary fine-grained sparsity.

Follow-up. What should you report? End-to-end latency and memory at matched task quality, plus achieved kernel behavior and workload shapes.

Trap. Fewer mathematical operations does not guarantee faster execution.

094What should an attention benchmark report?Applied

Answer. Report hardware, software versions, dtype, head dimensions/counts, batch and sequence distributions, mask/cache layout, warmup, synchronization/timing method, selected kernel, peak memory, and correctness tolerance. Separate prefill, decode, and end-to-end request latency.

Follow-up. Why include quality? Approximate/sparse/quantized alternatives can gain speed by changing the model function; compare at an acceptable quality level.

Trap. A best-case square-tensor microbenchmark is not a serving SLA.

095How do you diagnose OOM without immediately reducing context length?Advanced

Answer. Decompose peak memory into weights, KV cache, prefill activations/workspaces, allocator reserves, and fragmentation. Check whether returning attention matrices forces quadratic storage, whether caches duplicate, and whether a kernel falls back. Then choose a targeted intervention with quality tests.

Follow-up. Why can OOM occur only during prefill? Its activation/workspace peak can exceed the steady decode footprint even when the final KV cache fits.

Trap. A logical memory formula is a starting model, not a full allocator trace.

096What does sliding-window attention sacrifice?Applied

Answer. It restricts each query to a local neighborhood, reducing pairwise work to roughly O(nwd) for window width w. Distant tokens cannot interact directly in one local layer. Multiple layers propagate information farther, but useful recall remains a learned behavior.

Follow-up. What is the reach bound for L plain causal local layers? Roughly L(w−1) positions backward when w includes the current token, absent global links or dilation.

Trap. Receptive field and effective retrieval quality are different.

097How do global tokens change sparse attention connectivity?Advanced

Answer. Global tokens can read many positions and be read by local tokens, shortening communication paths across a sparse graph. They may form a bottleneck because large amounts of information must pass through limited representations. Patterns vary in whether global reads/writes are symmetric.

Follow-up. What evaluation catches the bottleneck? Multi-evidence tasks requiring several distant facts, not only one isolated needle.

Trap. A short graph path does not guarantee enough information capacity.

098What is kernel linear attention and when is it truly linear in sequence length?Advanced

Answer. Replace or approximate affinity by phi(q)ᵀphi(k) with feature width r. Associativity lets you precompute sum phi(k)vᵀ and a normalization vector. Complexity is linear in n when r and value width are treated as fixed; causal recurrence maintains those statistics.

Follow-up. What can grow instead? Feature width needed for approximation quality or state capacity, plus numerical costs.

Trap. It is not generally exact ordinary softmax attention with unchanged finite-dimensional features.

099Write the recurrent state of causal linear attention.Advanced

Answer. Maintain S_t=S_(t−1)+phi(k_t)v_tᵀ and z_t=z_(t−1)+phi(k_t). Then o_t=phi(q_t)ᵀS_t / (phi(q_t)ᵀz_t), with an appropriate denominator policy. State size is r*dv+r per head rather than retaining every token.

Follow-up. What is lost? A fixed-size aggregate can make exact token-specific retrieval harder and may suffer interference; the trade-off depends on the feature map and model.

Trap. Constant history-state size is not unlimited exact memory.

100How do state-space and recurrent hybrids differ from softmax attention?Applied

Answer. State-space or gated recurrent layers summarize history in evolving state according to their update rules. Softmax attention keeps addressable token-level keys/values and performs query-dependent retrieval. Hybrid models combine mechanisms, often retaining attention in selected layers for retrieval benefits.

Follow-up. Are all recurrent alternatives linear attention? No. Their state transitions, gates, and normalization can be fundamentally different.

Trap. Compare actual equations and empirical task behavior rather than treating all efficient sequence mixers as equivalent.

101What are attention sinks, and why do streaming caches care?Advanced

Answer. Some trained models allocate substantial attention mass to early or special positions even when semantic relevance seems low. Dropping these positions can destabilize certain windowed inference setups. Keeping a small initial prefix plus recent history has empirical support for some models.

Follow-up. Does that preserve all old knowledge? No. Evicted middle tokens are not directly retrievable just because sink tokens remain. See the StreamingLLM source in the bibliography.

Trap. Sinks are an observed mechanism in studied models, not a universal cache-eviction law.

102What is an induction head, and what does it explain about in-context learning?Advanced

Answer. A studied induction pattern continues a repeated sequence: after seeing A followed by B earlier, a later A can lead attention toward the earlier continuation B. Compositions of heads can implement matching and copying circuits. This offers mechanistic evidence for some forms of in-context pattern completion.

Follow-up. Does it explain all few-shot reasoning? No. Findings in studied architectures do not establish a complete theory of in-context learning in every large model.

Trap. An interpretable circuit is not a universal explanation of model intelligence.

103What is the difference between attention expressivity and trainability?Advanced

Answer. An architecture may represent a desired routing function in principle yet fail to learn it with available data, optimization, initialization, or width. Saturated scores, redundant heads, bottlenecks, and weak supervision can prevent practical use of theoretical capacity.

Follow-up. How would you investigate? Combine controlled synthetic tasks with real-task ablations, learning curves, and head/score diagnostics; isolate optimization from insufficient information.

Trap. Existence of a parameter setting does not prove SGD will find it.

104How should you interpret a head-pruning experiment?Applied

Answer. If removing a head preserves a measured metric, that head may be redundant under the tested distribution or compensated by other paths. It does not prove it is useless on all inputs. Pruning before retraining and pruning with recovery training answer different questions.

Follow-up. What controls matter? Repeated seeds, rare/error slices, context lengths, ablation location, and retraining budget.

Trap. Low average attention entropy or an attractive heatmap is not a pruning criterion by itself.

105Why is low attention entropy not automatically good?Advanced

Answer. Sharp distributions can reflect accurate retrieval, unwanted saturation, positional shortcuts, or collapsed heads. Diffuse distributions can correctly average multiple relevant values. Entropy must be interpreted with task behavior, value content, and head/layer role.

Follow-up. What metric would you pair with entropy? Targeted retrieval/causal interventions and output-quality slices, not entropy alone.

Trap. Optimizing a diagnostic statistic can damage the actual task.

106What does QK normalization change relative to standard scaling?Advanced

Answer. Normalizing Q/K can reduce sensitivity to vector norms and stabilize score magnitudes; a learned scale or temperature can restore adjustable sharpness. Depending on the method, it changes the scoring function and its optimization dynamics, not merely an implementation detail.

Follow-up. Does it replace all normalization? No. Residual-stream norms, key-axis softmax, and score scaling have different roles and axes.

Trap. Name the exact normalization rule before claiming equivalence to cosine or LayerNorm.

107What is the lost-in-the-middle problem and how would you measure it?Applied

Answer. Some models use relevant information less effectively when it appears in the middle of a long context than near its ends. Measure task accuracy across evidence insertion depth while controlling total length, distractors, wording, and answer leakage.

Follow-up. Why not test one needle only? Exact copying can miss multi-hop reasoning, conflicting evidence, and aggregate tasks. Include representative application behavior and uncertainty.

Trap. An advertised context window is not measured usable recall.

108How do position interpolation and changing the RoPE base differ?Advanced

Answer. Interpolation rescales position indices, compressing angular separation for all affected frequencies. Changing the base changes the frequency spectrum nonuniformly, typically affecting slower frequency bands more. Frequency-aware methods add other choices. Each changes the trained positional geometry.

Follow-up. Which should you choose? Start with the checkpoint’s supported extension recipe and evaluate short/long-context quality; there is no model-independent winner.

Trap. A successful load at a larger context length is not evidence of quality preservation.

109Can attention learn to ignore irrelevant tokens entirely?Advanced

Answer. In exact arithmetic with finite unmasked logits, softmax weights are positive, though they may be tiny. Explicit masks, sparse normalization, hard routing, or numerical underflow can create zero weights. Even tiny weights can matter if values have large magnitude.

Follow-up. Can the output ignore a token despite nonzero attention? Yes, value/output projections or downstream cancellation can make its contribution irrelevant to a target prediction.

Trap. Attention weight alone is not the size of the final causal contribution.

110How would you fairly compare dense, sparse, and linear attention research?Advanced

Answer. Control model/training budget, data, sequence distribution, hardware/software, and evaluation tasks. Report quality-versus-time/memory curves, not isolated asymptotic claims. Identify whether the operator is exact, approximate, or architecturally different, and include long-range retrieval and short-context regressions.

Follow-up. Why compare at matched quality too? A cheaper operator with worse task quality may need a larger model or more training, reversing the systems advantage.

Trap. An apples-to-apples FLOP count alone is not an apples-to-apples product comparison.

111Design attention for a multimodal moderation system with long pages and images.Applied

Answer. First identify evidence needs, latency/cost limits, and severe-error constraints. Compare joint token attention with text-to-vision/page cross-attention and controlled evidence compression. Preserve tiny-text/OCR and source references needed for policy decisions; do not optimize only average accuracy.

Follow-up. How do you diagnose a miss? Determine whether evidence was omitted, was present but unused, or was interpreted under the wrong policy rule.

Trap. A high-weight patch or rationale is not verified policy evidence.

112A video model is too slow. Which token-budget questions come first?Applied

Answer. Measure frame sampling, patch count, resolution/crops, token merging, and temporal redundancy. At 448×448 with 14×14 patches, simple patchification yields 1024 tokens/frame before merging. Ten frames produce 10,240 visual tokens, potentially dominating dense interactions.

Follow-up. What is the quality risk? Aggressive sampling can miss brief defects; spatial reduction can erase small text. Evaluate event duration and text-size slices.

Trap. Token count estimates must reflect actual preprocessing, not a model family’s marketing name.

113You have 16 GiB available for KV payload and 1 GiB per request. What concurrency do you recommend?Advanced

Answer. Sixteen is the arithmetic payload-only upper bound, not a safe recommendation. Check uneven context lengths, growth during generation, allocator blocks, metadata, peak workspace, and headroom. Set admission control from measured complete memory and latency behavior.

Follow-up. How would you raise capacity? Evaluate compatible GQA/MLA models, KV quantization, prefix sharing, and storage management with quality/isolation gates.

Trap. Never convert a memory upper bound directly into an SLA-backed concurrency target.

114Latency regressed after enabling an allegedly faster attention kernel. How do you investigate?Applied

Answer. Confirm the kernel actually runs, then separate prefill, decode, queueing, transfers, and other model operations. Check shape/dtype/mask changes, fallback paths, warmup, memory copies, and batch policy. Compare to a pinned baseline with correctness parity.

Follow-up. What if kernel time improved but end-to-end worsened? Look for changed batching/queueing, extra conversions, and bottlenecks shifted to other stages.

Trap. A local speedup does not guarantee a request-level speedup.

115How would you investigate severe-label recall loss after KV quantization?Advanced

Answer. Reproduce on a fixed dataset and compare full-precision versus quantized outputs with identical prompts and model weights. Slice by context depth/length, OCR size, language, rare labels, and key/value outliers. Inspect score and output deviations without treating attention maps as ground truth.

Follow-up. What is a sensible rollback gate? A pre-agreed severe-error tolerance with uncertainty, plus latency/memory targets, not an unquantified claim of negligible quality loss.

Trap. Average agreement can hide rare but important regressions.

116Does a causal mask defend against prompt injection in retrieved content?Applied

Answer. No. It controls which token positions are visible, not which text has authority. A hostile instruction inside visible content can still influence the model. Keep trusted instructions separate, treat retrieved material as evidence, constrain outputs/tools, and test injection attacks.

Follow-up. Would masking all retrieved text solve it? It also removes required evidence. The problem needs trust-aware system design, not a blanket attention prohibition.

Trap. Visibility, salience, and authority are different concepts.

117How would you test whether an attention architecture change improves the actual task?Advanced

Answer. Use controlled data splits, a matched training/fine-tuning budget, comparable token budgets, and multiple seeds where feasible. Evaluate task accuracy and rare severe errors with uncertainty, plus throughput, latency, and memory. Include short and long inputs and deployment-relevant distributions.

Follow-up. What about attention-head visualizations? Use them to form hypotheses, then test behavior or interventions. They are not acceptance criteria.

Trap. A single attractive benchmark or head map is insufficient evidence.

118What would you cache in encoder-decoder multimodal generation?Applied

Answer. Fixed encoder outputs can have their projected cross-attention K/V cached per decoder layer where applicable. Decoder self-attention K/V grows with generated tokens. Cache visual or page encoder features only when inputs and preprocessing/model versions match.

Follow-up. Can cross-attention K/V be shared across decoder layers automatically? No. Different layers can have different projection weights, so derived K/V differ unless the architecture explicitly shares them.

Trap. Cache reuse must follow the computation graph, not just matching tensor dimensions.

119How do you choose between truncation, retrieval, and a larger attention window?Advanced

Answer. Choose based on where necessary evidence lives and what interactions the task needs. Retrieval can reduce irrelevant tokens but may omit distributed or subtle evidence. Larger context retains more information at higher cost and still needs usable-context validation. Truncation is simplest but risks systematic omission.

Follow-up. What experiment decides? Measure evidence coverage and end-task quality separately, then compare latency/cost at acceptable severe-error rates.

Trap. More context cannot recover evidence that preprocessing never supplied.

120Give a senior-level recommendation for optimizing an existing attention service.Advanced

Answer. Start with correctness parity and phase-specific profiling. For unchanged dense-model semantics, use compatible exact fused kernels and remove avoidable copies/materialized attention matrices. If KV capacity/bandwidth remains limiting, evaluate cache layout and supported lower-memory model/cache options behind quality gates.

Follow-up. What makes the recommendation senior-level? It names the bottleneck, quantified assumptions, chosen trade-off, falsifiable tests, and rollback criteria rather than listing acronyms.

Trap. Do not propose an architectural replacement before measuring the existing bottleneck.

13 / Mocks & readiness

Practice under follow-up pressure

Use a blank page and timer. Grade each dimension 0 (missing/wrong), 1 (partly right or prompted), or 2 (correct, independent, with assumptions). These rubrics are practice tools, not an employer’s hiring rubric.

Mock A: mechanism and derivation, 35 minutes

TimePromptFull-credit evidence
0–5 minExplain attention from a weighted averageSeparates queries, matching keys, and returned values; distinguishes activations from parameters
5–12 minDerive the formula and shapes for rectangular cross-attentionQ[nq,dk], K[nk,dk], V[nk,dv]; softmax over keys
12–20 minDerive √dk and softmax JacobianStates independence/variance assumptions; includes off-diagonal derivative terms
20–28 minCompute the toy example and add a maskRe-normalizes allowed keys; returns weighted V, not K
28–35 minProve equivariance and discuss attention explanationsCorrect P algebra and mask caveat; does not equate weights with causal attribution

Score /10. At least 8 with no wrong mask/shape claim is a useful readiness signal. Rework every derivation for which you needed a memorized phrase rather than an equation.

Mock B: implementation and debugging, 45 minutes

  1. 15 minutes: Implement batched causal MHA with correct head reshaping and output projection.
  2. 10 minutes: Add a detached inference cache. Explain why a new rectangular lower triangle is wrong and derive absolute-position permissions.
  3. 10 minutes: Write three tests: full/chunk parity, future-token perturbation, and numerical gradient agreement on a small unmasked or validly masked example.
  4. 10 minutes: Diagnose all-masked rows, eval-mode SDPA dropout, and float64 downcasting.

Score /10: shapes, causal semantics, cache correctness, numerical behavior, test quality, each 0–2. A fast implementation with future leakage is not a pass. Production kernels can be invoked after the reference contract is right.

Mock C: serving and applied design, 45 minutes

Illustrative scenario: a decoder has 32 layers, 32 query heads, 8 KV heads, head width 128, and two-byte KV elements. Requests retain 8192 tokens. Assume 16 GiB of device memory is available for logical KV payload only after other reservations. The product needs low first-token latency and sustained decoding while some requests include many video frames.

  1. 0–10 minutes: Derive cache bytes. Expected: 1 GiB/request, so 16 is a payload-only upper bound, not a safe serving concurrency target. Same-width MHA would use 4 GiB/request.
  2. 10–20 minutes: Explain prefill versus decode work and what to profile. Expected: prompt pairwise compute versus history reads, plus projection/FFN/queueing effects.
  3. 20–30 minutes: Choose exact kernels, paging, batching, and input compression where justified. Expected: distinguish which intervention changes model semantics or quality.
  4. 30–40 minutes: Design long-context and moderation-quality tests. Expected: evidence-depth and severe-error slices, not just average latency or one needle.
  5. 40–45 minutes: Defend rollback criteria and failure isolation. Expected: numerical parity, quality guardrails, tail latency, and memory headroom.

Score /10: accounting, bottleneck diagnosis, optimization distinctions, quality evaluation, operational safeguards, each 0–2. Do not invent a latency estimate without hardware and workload measurements.

Study plans

BudgetPlan
90 minutes25 minutes first principles and shapes; 20 worked examples and gradients; 15 recall sheet; 30 core questions aloud
One dayTwo hours foundations/math; two implementation and tests; two positions/systems; one question bank; one timed mock and corrections
One weekDay 1 weighted selection and shapes; day 2 derivations; day 3 implement from memory; day 4 position/cache; day 5 systems and multimodal; day 6 mocks A/B; day 7 mock C plus weakest question slices

Readiness checklist, score yourself /20

Use 0/1/2 for each item. The useful threshold is not a magic hiring score: aim for at least 16/20 and no zero on masks, caching, or tests before calling yourself ready.

  1. Explain Q/K/V without anthropomorphic “focus” language.
  2. Write every matrix shape and correct softmax axis.
  3. Derive √dk with its assumptions.
  4. Derive softmax and Q/K/V gradients.
  5. Handle causal, padding, segment, and empty-support masks.
  6. Implement multi-head reshaping and verify head mapping.
  7. Explain RoPE and reproduce full-versus-cache parity.
  8. Calculate FLOPs and cache bytes with explicit units.
  9. Distinguish FlashAttention, paging, GQA, and sparse/linear operators.
  10. Design quality tests and give one bottleneck-driven recommendation.

After a weak answer, record the missing assumption or test, not just the topic name. “Forgot to account for Hkv rather than Hq” is actionable; “review attention” is not.

14 / Runnable Python

A small implementation you can audit

The standard-library Python reference implements stable attention, Boolean and additive masks, manual Q/K/V gradients, finite-difference checks, and cache-parity tests. It deliberately favors transparent loops over speed. It is embedded here so this HTML remains a single-file study artifact.

Companion file

python3 attention-reference.py

The standard-library test suite was run during preparation. The separate PyTorch teaching snippets are syntax-checked and reviewed, but were not runtime-tested because PyTorch is not installed in the authoring environment. No GPU performance claims have been validated here.

Read the complete standard-library implementation and tests
"""Transparent attention reference, Python standard library only.
Run: python3 attention-reference.py
One head, list-of-list matrices, no dropout. Boolean True means allowed.
This is a correctness reference, not a production kernel.
"""
import math
import random
import unittest


def shape(x):
    if not x or not isinstance(x[0], list) or not x[0]:
        raise ValueError('Use a nonempty matrix')
    width = len(x[0])
    if any(not isinstance(row, list) or len(row) != width for row in x):
        raise ValueError('Ragged matrix')
    return len(x), width


def transpose(x):
    shape(x)
    return [list(row) for row in zip(*x)]


def mm(a, b):
    _, width = shape(a)
    rows, _ = shape(b)
    if width != rows:
        raise ValueError('Matrix multiplication shape mismatch')
    return [[sum(x*y for x,y in zip(row,col)) for col in zip(*b)] for row in a]


def stable_softmax(row):
    if not row or any(math.isnan(x) or x == math.inf for x in row):
        raise ValueError('Empty row, NaN, or positive infinity in scores')
    m = max(row)
    if m == -math.inf:
        raise ValueError('All-masked row: no probability distribution exists')
    e = [math.exp(x-m) for x in row]
    z = sum(e)
    return [x/z for x in e]


def causal_mask(nq, nk, offset=0):
    if not isinstance(offset, int):
        raise ValueError('Offset must be an integer')
    return [[j <= i+offset for j in range(nk)] for i in range(nq)]


def attention(q, k, v, allowed=None, bias=None):
    """Return (output, probabilities). Scores use 1/sqrt(key width).

    q: [nq,dk], k: [nk,dk], v: [nk,dv].
    allowed: optional Boolean [nq,nk], True participates.
    bias: optional additive [nq,nk]; finite bias or -inf only.
    All-masked rows raise rather than silently fabricating a distribution.
    """
    nq, dk = shape(q)
    nk, kk = shape(k)
    nv, _ = shape(v)
    if dk != kk or nk != nv:
        raise ValueError('Q/K widths or K/V lengths differ')
    if any(not math.isfinite(x) for a in (q,k,v) for row in a for x in row):
        raise ValueError('Q, K, V must contain finite numbers')
    if allowed is not None:
        if shape(allowed) != (nq,nk) or any(type(x) is not bool for row in allowed for x in row):
            raise ValueError('allowed must be a matching Boolean matrix')
    if bias is not None:
        if shape(bias) != (nq,nk) or any(math.isnan(x) or x == math.inf for row in bias for x in row):
            raise ValueError('Invalid additive bias')
    scores = mm(q, transpose(k))
    for i in range(nq):
        for j in range(nk):
            scores[i][j] /= math.sqrt(dk)
            if bias is not None:
                scores[i][j] += bias[i][j]
            if allowed is not None and not allowed[i][j]:
                scores[i][j] = -math.inf
    a = [stable_softmax(row) for row in scores]
    return mm(a,v), a


def backward(q,k,v,a,g):
    """Given g=dLoss/dOutput, return (dQ,dK,dV); mask/bias fixed.

    dV=A.T G; E=G V.T; D=A*(E-row_sum(A*E));
    dQ=D K/sqrt(dk); dK=D.T Q/sqrt(dk).
    """
    scale = 1/math.sqrt(len(q[0]))
    dv = mm(transpose(a),g)
    e = mm(g,transpose(v))
    d = []
    for ai,ei in zip(a,e):
        center = sum(x*y for x,y in zip(ai,ei))
        d.append([x*(y-center) for x,y in zip(ai,ei)])
    dq = [[x*scale for x in row] for row in mm(d,k)]
    dk = [[x*scale for x in row] for row in mm(transpose(d),q)]
    return dq,dk,dv


def cached_chunks(q,k,v,sizes):
    """Illustrate append-only causal caching of already projected K/V.

    This does not recompute projections, rotate positions, or manage batches.
    Full-model cache parity must test those additional responsibilities too.
    """
    if any(type(s) is not int or s <= 0 for s in sizes) or sum(sizes) != len(q):
        raise ValueError('Chunk sizes must cover all queries exactly')
    if len(q) != len(k) or len(q) != len(v):
        raise ValueError('This helper models self-attention')
    keys,values,out=[],[],[]
    start=0
    for size in sizes:
        end=start+size
        keys.extend(k[start:end])
        values.extend(v[start:end])
        block,_=attention(q[start:end],keys,values,allowed=causal_mask(size,end,start))
        out.extend(block)
        start=end
    return out


class AttentionTests(unittest.TestCase):
    def setUp(self):
        rng=random.Random(29)
        self.q=[[rng.uniform(-.8,.8) for _ in range(2)] for _ in range(4)]
        self.k=[[rng.uniform(-.8,.8) for _ in range(2)] for _ in range(4)]
        self.v=[[rng.uniform(-.8,.8) for _ in range(3)] for _ in range(4)]

    def assertMatrix(self,a,b,tol=1e-10):
        self.assertEqual(shape(a),shape(b))
        for ar,br in zip(a,b):
            for x,y in zip(ar,br):
                self.assertTrue(math.isfinite(x) and math.isfinite(y))
                self.assertAlmostEqual(x,y,delta=tol)

    def test_toy(self):
        out,a=attention([[1.,0.]],[[1.,0.],[0.,1.],[1.,1.]],[[1.,0.],[0.,2.],[3.,1.]])
        self.assertMatrix(out,[[1.6044483707191437,.7966637219606423]])
        self.assertAlmostEqual(sum(a[0]),1.)

    def test_stable_softmax(self):
        self.assertMatrix([stable_softmax([1000,1001])],[stable_softmax([0,1])])

    def test_all_masked_raises(self):
        with self.assertRaises(ValueError):
            attention([[1]],[[1]],[[1]],allowed=[[False]])

    def test_invalid_numerics(self):
        for bad in [math.nan,math.inf]:
            with self.assertRaises(ValueError):stable_softmax([0,bad])
        with self.assertRaises(ValueError):attention([[math.nan]],[[1]],[[1]])

    def test_rectangular_and_row_sums(self):
        out,a=attention(self.q[:2],self.k,self.v)
        self.assertEqual(shape(out),(2,3))
        self.assertEqual(shape(a),(2,4))
        for row in a:self.assertAlmostEqual(sum(row),1.)

    def test_boolean_additive_mask_parity(self):
        mask=causal_mask(4,4)
        bias=[[0. if x else -math.inf for x in row] for row in mask]
        out,a=attention(self.q,self.k,self.v,allowed=mask)
        other,_=attention(self.q,self.k,self.v,bias=bias)
        self.assertMatrix(out,other)
        for i,row in enumerate(a):
            for j in range(i+1,4):self.assertEqual(row[j],0.)

    def test_causal_future_perturbation(self):
        mask=causal_mask(4,4)
        before,_=attention(self.q,self.k,self.v,allowed=mask)
        k=[r[:] for r in self.k];v=[r[:] for r in self.v]
        k[3]=[99.,-75.];v[3]=[800.,-900.,700.]
        after,_=attention(self.q,k,v,allowed=mask)
        self.assertMatrix(before[:3],after[:3])

    def test_cache_single_tokens(self):
        full,_=attention(self.q,self.k,self.v,allowed=causal_mask(4,4))
        self.assertMatrix(full,cached_chunks(self.q,self.k,self.v,[1,1,1,1]))

    def test_cache_uneven_chunks(self):
        full,_=attention(self.q,self.k,self.v,allowed=causal_mask(4,4))
        self.assertMatrix(full,cached_chunks(self.q,self.k,self.v,[1,2,1]))

    def test_permutation_equivariance(self):
        p=[2,0,3,1]
        out,_=attention(self.q,self.k,self.v)
        other,_=attention([self.q[i] for i in p],[self.k[i] for i in p],[self.v[i] for i in p])
        self.assertMatrix(other,[out[i] for i in p])

    def test_shape_and_mask_validation(self):
        with self.assertRaises(ValueError):attention([[1,2]],[[1]],[[1]])
        with self.assertRaises(ValueError):attention([[1]],[[1]],[[1]],allowed=[[1]])
        with self.assertRaises(ValueError):shape([[1,2],[1]])

    def check_gradients(self,mask=None):
        q=[row[:] for row in self.q[:2]];k=[row[:] for row in self.k];v=[row[:] for row in self.v]
        g=[[.2,-.5,.7],[-.1,.9,.3]]
        _,a=attention(q,k,v,allowed=mask)
        analytic=backward(q,k,v,a,g)
        def loss():
            out,_=attention(q,k,v,allowed=mask)
            return sum(x*y for row,gr in zip(out,g) for x,y in zip(row,gr))
        eps=1e-6
        for matrix,grad in zip((q,k,v),analytic):
            for i,row in enumerate(matrix):
                for j,old in enumerate(row):
                    matrix[i][j]=old+eps;plus=loss()
                    matrix[i][j]=old-eps;minus=loss()
                    matrix[i][j]=old
                    self.assertAlmostEqual((plus-minus)/(2*eps),grad[i][j],delta=2e-8)

    def test_backward_finite_difference(self):self.check_gradients()

    def test_masked_backward_finite_difference(self):
        self.check_gradients([[True,True,False,False],[True,False,True,True]])


if __name__=='__main__':
    unittest.main(verbosity=2)

Printing expands chapter exercises and interview answers, but omits this long embedded source listing. Download the code separately when you want to annotate it.

15 / Primary sources

Read with a question in mind

This guide is an original synthesis and set of examples. The links below are primary papers and official API documentation, not a claim that every question is taken from an actual interview. Foundational equations are stable; kernel support and framework behavior are version-dependent. Paper titles and URLs were checked during preparation. No benchmark speedups are promised for your hardware.

  1. Attention Is All You NeedVaswani et al., 2017. Core scaled dot-product attention, multi-head attention, the original post-norm encoder-decoder.
  2. Neural Machine Translation by Jointly Learning to Align and TranslateBahdanau, Cho, Bengio, 2014. Attention before Transformers; learned alignment in recurrent sequence-to-sequence models.
  3. Effective Approaches to Attention-based Neural Machine TranslationLuong, Pham, Manning, 2015. Global and local attention; dot-product and related scoring functions.
  4. PyTorch scaled_dot_product_attention APIDocumentation checked 9 September 2026. Mask semantics, non-square causal alignment, dropout behavior, supported backends. APIs evolve; check your installed version.
  5. RoFormer: Enhanced Transformer with Rotary Position EmbeddingSu et al., 2021. Rotary encoding and relative position inside the query-key dot product.
  6. Train Short, Test Long: Attention with Linear Biases Enables Input Length ExtrapolationPress, Smith, Lewis, 2021. Head-specific linear distance biases in attention scores.
  7. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessDao et al., 2022. Tiled exact attention and reduced memory traffic; distinguishes algorithmic work from data movement.
  8. GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsAinslie et al., 2023. Shared KV groups and quality/efficiency trade-offs.
  9. Fast Transformer Decoding: One Write-Head is All You NeedShazeer, 2019. Sharing one KV head to reduce incremental decoding memory bandwidth.
  10. Efficient Memory Management for Large Language Model Serving with PagedAttentionKwon et al., 2023. Paged KV storage, memory utilization, and serving.
  11. Transformers are RNNs: Fast Autoregressive Transformers with Linear AttentionKatharopoulos et al., 2020. Kernel feature maps, associative evaluation, and recurrent accumulation.
  12. Lost in the Middle: How Language Models Use Long ContextsLiu et al., 2023. Evidence that context length supported is not the same as context effectively used.
  13. DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language ModelDeepSeek-AI, 2024. Multi-head latent attention and compressed KV representations, alongside a separate MoE design.
  14. Ring Attention with Blockwise Transformers for Near-Infinite ContextLiu, Zaharia, Abbeel, 2023. Distributing long-context attention and overlapping block communication with computation.
  15. Efficient Streaming Language Models with Attention SinksXiao et al., 2023. Empirical attention sinks and a streaming-cache strategy; not a claim that evicted evidence stays recoverable.
  16. In-context Learning and Induction HeadsOlsson et al., 2022. Mechanistic evidence for induction circuits in studied models, with limits on generalizing to all in-context learning.

Connect this guide to your local study repository

In your existing LLMs-from-scratch/pkg/llms_from_scratch/ch03.py, follow SelfAttention_v1 → SelfAttention_v2 → CausalAttention → MultiHeadAttention → PyTorchMultiHeadAttention. The last class uses fused QKV projection and SDPA with evaluation-aware dropout. The examples teach progressively richer attention, but do not implement the full cache-aware module in this guide. This local pointer is optional; the HTML does not load that repository or need it to work.

What “interview-ready” means here. You can derive the mechanism, implement a correct reference, state when an optimization changes semantics, and design tests that would expose your own mistakes. Memorized vocabulary is not enough. Use the mock rubrics to decide what still needs work.