The interview problem
Explain how attention represents token order. Show what an unmasked attention layer does when tokens are permuted, calculate a two-dimensional rotary attention score, and diagnose a decoder that produces different results with a KV cache than with a full forward pass.
Original fundamentals practice, not a reported company interview. Examples are hypothetical. RoFormer paper version 5 dated November 8, 2023, retrieved September 27, 2026. Interview date: not applicable.
1. State the symmetry precisely
For unmasked self-attention with shared tokenwise projections and no positional inputs, permuting input rows permutes output rows in the same way. Assume deterministic evaluation with no other order-dependent operations; independently sampled dropout masks need not preserve exact equality for an individual training pass. This is permutation equivariance, not invariance of the entire output matrix. If a classifier then mean-pools those output rows, its pooled representation is invariant to that permutation.
Write attention as A(X) = softmax(QKᵀ/√d)V, with rowwise softmax. For a permutation matrix P, projected inputs become PQ, PK and PV. The score matrix becomes P(QKᵀ)Pᵀ; rowwise softmax permutes its rows and columns correspondingly. Multiplication by PV gives PA(X). Shared tokenwise feed-forward layers and residual paths preserve this property under the same assumptions.
Thus a mean-pooled unpositioned encoder cannot distinguish “dog bites person” from “person bites dog” solely from their ordering when they contain the same tokens. An output at a fixed index is different from mean pooling and can reveal which token occupies that index; do not claim every possible readout is invariant.
A fixed causal mask changes this argument. Permuting tokens while retaining a lower-triangular mask does not apply the corresponding permutation to the mask. The masked network has asymmetric access to prefixes and is not covered by the unmasked equivariance proof. “Without position embeddings, every Transformer ignores order” is too broad.
2. Compare where position enters
An absolute embedding adds a position-dependent vector to a token representation. A relative score bias modifies attention according to the distance between query and key positions. Rotary position embedding instead rotates query and key coordinate pairs by position-dependent angles, making their dot product depend explicitly on relative position. These are different mechanisms; their training and serving conventions must match.
A learned absolute table needs a defined policy outside its trained index range. A formula that can be evaluated at larger indices avoids a missing-table-entry error, but that fact alone does not establish reliable long-context predictions. Evaluate model quality at the lengths and distances the application needs.
3. Work through one rotary pair
Define R(φ) = [[cos φ, −sin φ], [sin φ, cos φ]]. Rotate query q at position m to R(mθ)q and key k at n to R(nθ)k. Their dot product is qᵀR((n − m)θ)k because rotations are orthogonal and their angles compose. This identity holds for fixed unrotated vectors; the vectors themselves may already contain contextual information.
Choose q = [1, 0], k = [1, 0], θ = π/2, query position m = 2 and key position n = 1. The rotated query is [−1, 0]; the rotated key is [0, 1]; the dot product is zero. Move the key to n = 2 and the score becomes one. Move both original positions by three, to m = 5 and n = 4, and the dot product remains zero because the relative displacement is unchanged.
For the same query at m = 2 and keys at n = 0, 1 and 2, all with unrotated vector [1, 0], the raw scores are [−1, 0, 1]. With a two-dimensional head, divide by √2 before softmax. The attention weights are approximately [0.140029, 0.283995, 0.575975]. Position changes weights even though the unrotated keys are identical. If the value vectors are also identical, however, their weighted average is unchanged. To see a changed output in this toy calculation, choose scalar values [0, 1, 2]; the weighted output is approximately 1.435946. This separates a change in attention weights from a guaranteed change in every possible value aggregation.
Each rotation preserves its vector norm, but rotating q and k by different angles can change their dot product. In larger heads, multiple coordinate pairs use different frequencies. This toy frequency has an exact period of four positions: displacement four produces the same rotation as zero. It illustrates periodicity, not a claim that an entire practical model repeats every four tokens.
4. Make cached and full computation agree
token representations → query/key projections → position rotations
↓
new key + value → append to KV cache
↓
attention over eligible cached keysSuppose the prefix occupies positions 0 through 99. The next token uses position 100, not zero merely because it arrives in a one-token decoding call. If cached keys were rotated at their original positions, rotate only the new key before appending it. Applying the rotation again to every cached key changes their meaning.
Use the same position convention for padding, packed sequences, prefix reuse and sliding windows. Resetting the newest query to zero while old cached keys retain positions 0–99 changes the relative angles. A coherent rebase requires consistent treatment of every relevant query and key and the model's other positional mechanisms. It is not achieved by editing one position counter.
A practical correctness check compares full-prefix logits with incremental cached logits for the same tokens, mask and position IDs in deterministic evaluation mode. Allow a small numerical tolerance for different execution kernels. Repeat with padding and multiple prefix lengths, and verify that packed examples cannot attend across document boundaries unless explicitly intended.
5. Distinguish representability from generalization
Training on length 2,048 and computing rotations for length 16,384 does not show that the model can retrieve or reason over that context. Test near and far evidence, distractors, order-sensitive tasks and realistic prompt distributions. Report accuracy by both total length and query-to-evidence distance; one average can hide a failure at the far end.
Changing a frequency base or rescaling positions changes the distances the trained model experiences. Treat it as a model change requiring evaluation, rather than a serving-only memory optimization. A single score need not decrease monotonically with distance: in the toy pair above it oscillates. Avoid turning an aggregate intuition about distance into a per-example monotonicity guarantee.
Position encoding also does not remove attention cost. A dense score matrix for one head at 16,384 tokens contains 268,435,456 entries. At two bytes each, that is 536,870,912 bytes, or 512 MiB, if materialized. Increasing length from 2,048 to 16,384 multiplies this matrix size by 64. Memory-efficient attention implementations can avoid materializing the full matrix; this calculation describes the explicit score representation, not a universal measured memory requirement.
6. Failure analysis and follow-ups
Check coordinate-pair layout, rotation sign, frequency ordering, position offsets, padding masks and cache reuse. A checkpoint trained with one pairing convention is not necessarily compatible with an implementation using another. Norm preservation alone cannot detect every bug: using the wrong rotation still preserves norm.
Follow-ups: Does RoPE make the whole model translation invariant? The relative dot-product identity alone does not prove that, especially when masks, boundaries or other features change. Does a causal mask count as position-related structure? It encodes prefix access and breaks the unmasked permutation argument. Can a model evaluate an unseen position but still perform poorly there? Yes. Is a correct KV-cache size enough to validate caching? No; positions and attention eligibility must also match.
Score 0–2 each for the exact symmetry claim, rotary calculation, cache-position consistency, long-context evaluation and memory arithmetic. A strong answer distinguishes a mathematical encoding property from end-to-end model behavior.
Sources and next steps
- Su and colleagues: RoFormer, version 5 — rotary query/key encoding and relative-position formulation.
The worked rotation, symmetry derivation, cache-debugging exercise and memory calculation are original. Continue with attention and Transformers for the underlying attention operation.
Continue your preparation
Choose a connected learning path or browse more ML fundamentals questions. Read our editorial method and attribution policy.