76 Transformers Interview Questions and Answers (2026)

Transformers now sit under nearly every serious language, vision, and speech model, and interviewers know it. They aren't impressed that you've heard of attention. They want you to explain why scores get scaled by √d_k, how a causal mask works, and what grouped-query attention does to the KV cache. Walk in with buzzwords instead of mechanics and you'll get caught at the first follow-up.
These 76 questions come with concise, interview-ready answers and code where it actually helps. They're ordered Junior → Mid → Senior, so you lock in attention fundamentals and the transformer block before moving on to complexity, scaling, efficient attention, and long-context tricks. Work through them in order and you'll answer the follow-ups as confidently as the openers.
Q1.What is the difference between self-attention and cross-attention?
Both use the same scaled dot-product attention. The difference is where Q, K and V come from. In self-attention all three come from the same sequence. In cross-attention the queries come from one sequence and the keys and values come from another.
Self-attention:
Q = XW_Q, K = XW_K, V = XW_V all come from the same input X.
Each token builds a context-aware representation by mixing in information from the other tokens of its own sequence.
Used in encoder layers (bidirectional) and decoder layers (with a causal mask).
Cross-attention:
Q = YW_Q comes from the decoder or target stream. K = XW_K, V = XW_V come from the encoder output or another modality.
Each target position asks: "which parts of the source are relevant to me?"
Examples: an encoder-decoder translation model attending to the source sentence, or text-to-image diffusion attending to text embeddings.
Shape consequence:
Self-attention scores are n × n. Cross-attention scores are n_q × n_kv, so the two sequence lengths can differ.
The output always has one row per query, so it follows the query sequence's length.
Masking: cross-attention usually needs no causal mask, because the whole source is visible. It typically uses only a padding mask on the keys.
Q2.What conceptual roles do Queries, Keys, and Values play in scaled dot-product attention?
Attention works like a soft, differentiable lookup table. The query says what a token is looking for. Each key advertises what a token offers for matching. Each value is the content actually returned, weighted by how well the query matched the corresponding key.
Query (Q): the question: It is a projection of the current token that encodes what information it needs (for example, a verb looking for its subject).
Key (K): the address or label:
The relevance score is q·k / √d_k.
Keys exist only for matching and never appear in the output directly.
Value (V): the payload:
The output is Σ softmax(scores)_j · v_j, a weighted blend of values.
Separating V from K lets a token be found for one reason and contribute different information.
Soft vs hard lookup: A Python dict returns the one exact match. Attention returns a weighted mix over all entries, which makes it differentiable end to end.
Practical note: during autoregressive decoding, past K and V are reused by every new query. That is why we keep a KV cache but no query cache.
Q3.What does the softmax produce in the attention equation?
softmax produce in the attention equation?The softmax turns raw query-key similarity scores into attention weights. For each query you get a probability distribution over the keys: non-negative weights that sum to 1. These weights then combine the values.
Shape and meaning:
Input: the logits QKᵀ/√d_k, with shape n_q × n_k.
Output: a matrix of the same shape where each row sums to 1.
Entry (i, j) is how much query i reads from token j.
Why it matters:
Multiplying the weights by V gives a convex combination of values, so the output stays on a stable scale whatever the sequence length.
The exponential amplifies differences between scores, so attention can be sharp (close to selecting one token) or diffuse.
It is differentiable, unlike a hard argmax lookup.
Masking hooks in here:
Masked positions are set to -inf before the softmax, so they get exactly 0 weight.
This is how causal masks and padding masks work.
Caveat: the weights must sum to 1, so a head cannot attend to nothing. This produces "attention sinks" (heavy weight on the first token), which some variants address with an extra null slot or softmax-off-by-one.
Q4.What is the full mathematical formula for scaled dot-product attention?
Scaled dot-product attention is Attention(Q, K, V) = softmax(QKᵀ / √d_k + M) V. It scores every query against every key, scales the scores, optionally adds a mask M, turns each row into a probability distribution, and returns a weighted average of the values.
Inputs and shapes:
Q = XW_Q (n × d_k), K = XW_K (m × d_k), V = XW_V (m × d_v).
QKᵀ is n × m: entry (i, j) is how strongly query i matches key j.
The output is n × d_v: one mixed value vector per query.
Why divide by √d_k:
If the components of q and k are roughly independent with unit variance, q·k has variance d_k. Large logits saturate the softmax into near one-hot outputs with vanishing gradients.
Scaling brings the variance back to about 1.
Softmax is applied row-wise (over keys): softmax(s)_j = exp(s_j) / Σ_k exp(s_k), so each query's weights are non-negative and sum to 1.
Mask M (optional): Additive: 0 where attention is allowed, −∞ where it is blocked (causal or padding). This happens before the softmax.
Multi-head extension:
head_i = Attention(QW_i^Q, KW_i^K, VW_i^V).
MultiHead = Concat(head_1..head_h) W_O, typically with d_k = d_model / h.
Cost: O(n·m·d) time and O(n·m) memory for the score matrix, which is quadratic in sequence length for self-attention.
Q5.What is the purpose of a causal (look-ahead) mask in an autoregressive decoder?
A causal mask stops each position from attending to later positions. Token t's representation then depends only on tokens ≤ t, which matches generation, where the future doesn't exist yet. It also lets the model be trained on all positions in parallel without cheating.
Prevents cheating during training: The target at position t is token t+1. Without the mask, the model could just attend to it and copy it, giving near-zero loss and learning nothing useful.
Enables parallel teacher forcing:
One forward pass over the whole sequence yields T next-token predictions at once.
Each prediction sees exactly the context it would see at inference time.
Train/inference consistency: Because past representations never depend on future tokens, they can be computed once and reused. This is what makes the KV cache valid during incremental decoding.
Implementation:
Use a lower-triangular T×T mask, e.g. torch.tril(torch.ones(T, T)).bool().
Entries above the diagonal get −∞ added before the softmax.
Alternatively, pass is_causal=True to F.scaled_dot_product_attention.
Scope: it applies to decoder self-attention only. Encoder self-attention and cross-attention to encoder outputs are not causally masked.
Q6.What is the difference between bidirectional and causal attention?
In bidirectional attention, every token attends to every other token, past and future. In causal attention, each token attends only to itself and earlier tokens. The first suits understanding tasks over a complete input; the second is required for left-to-right generation.
Bidirectional (encoder-style: BERT, T5 encoder, ViT):
There is no causal mask, only padding masking. Representations use full left and right context.
It can't be trained with plain next-token prediction, because the answer would be visible. It uses objectives such as masked language modeling or span corruption.
Best for classification, NER, retrieval embeddings, and encoding the source for seq2seq.
Causal (decoder-style: GPT, Llama):
A lower-triangular mask means token t sees only tokens ≤ t.
Trained with next-token prediction. Every position gives a training signal in a single pass.
Past states never change, so a KV cache makes generation incremental.
Trade-offs:
Bidirectional gives richer per-token context but generates poorly.
Causal is generative and scales well as a universal interface.
Both are O(n²). Causal kernels can skip the masked upper triangle, roughly halving compute.
Hybrids:
Prefix-LM: bidirectional over the prompt, causal over the continuation.
Encoder-decoder: a bidirectional encoder, a causal decoder, and cross-attention between them.
Q7.How does padding masking differ in purpose from causal masking?
Padding masking is a batching fix: it hides fake pad tokens so they don't contaminate real ones. Causal masking is a modeling constraint: it hides real future tokens so the model can't see what it must predict.
Padding mask:
Purpose: sequences of different lengths are padded to the same length for batching. Pad tokens carry no meaning and must not receive attention weight.
Data-dependent: it differs per example (from attention_mask).
Masks along the key dimension, shape (B, 1, 1, T_k).
Used everywhere batches have variable lengths: encoder, decoder and cross-attention.
Pad queries still produce outputs; they are excluded from the loss instead (e.g. ignore_index=-100).
Causal mask:
Purpose: enforce autoregressive information flow so position t depends only on tokens ≤ t.
Structural: it depends only on positions and is identical for every example.
Masks query-key pairs where j > i, a T×T upper triangle.
Used only in decoder self-attention.
Key distinction:
Removing the padding mask makes outputs depend on batch composition (a correctness bug).
Removing the causal mask leaks the training targets (the model cheats).
They are orthogonal and are usually combined (AND of allowed positions) in decoders.
Q8.Why do Transformers use multi-head attention instead of a single large attention head?
Multi-head attention lets each position attend in several different ways at once, at roughly the same cost as one full-width head. A single head produces only one softmax distribution per query, so it must average all the relationships it cares about into one weighting.
A single softmax is a bottleneck:
Each query gets one weighted average over values. If a token needs both its syntactic head and its previous token, one head blurs them together.
The original paper notes that averaging inhibits attending to different representation subspaces.
Heads work in different subspaces:
Each head has its own W_Q, W_K, W_V projecting into a d_model/h space.
Different heads can therefore define different notions of similarity (position, syntax, coreference, copying).
It costs about the same: Splitting d_model across h heads keeps parameters and matmul FLOPs essentially unchanged. You get more attention patterns for free.
Ensemble-like robustness: multiple heads give redundancy and more stable training.
Caveats:
Returns diminish. Many heads can be pruned after training with little loss (Michel et al., 2019).
With too many heads, d_k gets so small that each head's expressiveness (rank) is limited.
Q9.Why did the Transformer architecture replace RNNs for sequence modeling?
Transformers replaced RNNs mainly because self-attention processes all positions in parallel and connects any two tokens in one step. That makes training far faster on GPUs and long-range dependencies easier to learn, which in turn enabled scaling to huge models and datasets.
Parallelism over the sequence:
An RNN computes h_t from h_{t-1}, so there are O(N) sequential steps.
Attention is a few big matmuls over all tokens at once, which suits GPUs and TPUs.
Short path between any two tokens:
The path is O(1) per layer versus O(N) in an RNN.
Distant dependencies and their gradients don't decay through many recurrent steps.
No fixed-size memory bottleneck:
An RNN squeezes the whole history into one hidden vector.
Attention can look up any earlier token directly, which made the attention bolted onto seq2seq RNNs redundant.
Scales well:
Stable deep stacks with residuals and LayerNorm, plus predictable scaling laws.
This enabled large pretraining followed by fine-tuning (BERT, GPT).
Trade-offs:
Attention costs O(N²) time and memory in sequence length.
It needs positional encodings, since attention is order-agnostic.
Autoregressive inference is still sequential and needs a growing KV cache.
These costs are why linear RNNs and state-space models (Mamba, RWKV) are seeing renewed interest.
Q10.What is the bottleneck of traditional sequence-to-sequence encoder-decoder architectures with fixed context vectors?
The encoder must compress the entire source sequence into one fixed-size vector, and the decoder sees only that vector. This becomes an information bottleneck: long or complex inputs lose detail, and translation quality degrades sharply as sentence length grows.
Fixed capacity, variable input:
A 5-word and a 50-word sentence both map to the same-sized final hidden state, so information per token shrinks as length grows.
Empirically, RNN encoder-decoders (Cho et al., 2014) performed well on short sentences and degraded quickly on long ones.
Recency bias
The final hidden state is dominated by recent tokens; early tokens must survive many recurrent updates, which is hard even with LSTM/GRU gating.
No selective access: Every decoding step uses the same summary, although different output words depend on different source words (e.g. alignment in translation).
Long gradient paths: Errors at the decoder must backpropagate through the whole encoder chain to reach early tokens, which worsens vanishing gradients.
The fix: attention (Bahdanau et al., 2014): Keep all encoder hidden states and build a fresh, weighted context vector at each decoding step. Transformers then generalized this idea to attention everywhere.
Q11.What was the key conceptual shift introduced by the paper "Attention Is All You Need"?
The paper showed that recurrence and convolution are unnecessary for sequence transduction: a model built solely on attention can model sequences, using self-attention to relate positions within a sequence and cross-attention to relate the two sequences. This made training fully parallel across positions and gave direct long-range connections.
Before: attention as an add-on: Attention helped RNN encoder-decoders align source and target, but the RNN still did the sequence modeling, one step at a time.
After: attention as the core computation: Encoder and decoder are stacks of self-attention plus position-wise feed-forward layers, with residual connections and LayerNorm.
Why it mattered:
Parallelism: all positions are processed at once during training, a good fit for GPUs, so training is much faster than with RNNs.
Constant path length between any two tokens, which eases learning of long-range dependencies.
Scalability: this architecture became the foundation for BERT, GPT and modern LLMs.
Supporting ideas that made it work:
Scaled dot-product attention (divide by sqrt(d_k)) and multi-head attention, so the model can attend to different subspaces.
Positional encodings, to restore order information lost by dropping recurrence.
Q12.Why do Transformers require explicit positional information while RNNs do not?
An RNN processes tokens one after another, so order is baked into its computation. Self-attention treats its input as an unordered set: permute the tokens and the outputs are permuted in the same way. So Transformers must inject position explicitly.
RNNs: order is implicit: The hidden state h_t = f(h_{t-1}, x_t) depends on everything before step t, so swapping two tokens changes the result.
Self-attention is permutation-equivariant:
Attention scores depend only on content (q_i · k_j), not on where tokens sit. The FFN is applied per token, so it adds no order either.
Without positions, "dog bites man" and "man bites dog" would produce the same set of representations.
How position is added:
Absolute encodings added to the embeddings: sinusoidal (original paper) or learned (BERT, GPT-2).
Relative schemes inside attention: RoPE rotates q and k, and ALiBi adds a distance-based bias. These tend to extrapolate better to longer sequences.
Nuance: A causal mask breaks the symmetry, so decoder-only models without positional encodings (NoPE) can partly infer position. Bidirectional encoders cannot.
Q13.How did the original attention mechanism for RNN-based machine translation compute a context vector at each decoding step?
In Bahdanau attention, the decoder builds a fresh context vector at every step. It scores each encoder hidden state against the previous decoder state, normalizes the scores with softmax into alignment weights, and takes the weighted sum of the encoder states.
Encode: A bidirectional RNN produces an annotation h_j for each source token (forward and backward states concatenated). All of them are kept, not just the last.
Score (alignment model): For decoder step i: e_ij = v^T tanh(W s_{i-1} + U h_j). This is a small feed-forward network, hence the name additive attention, trained jointly with the rest of the model.
Normalize: α_ij = softmax_j(e_ij) gives a soft alignment over source positions.
Combine: c_i = Σ_j α_ij h_j
Decode: c_i, the previous output y_{i-1} and s_{i-1} produce the new state s_i and the next-token distribution.
Variant: Luong attention (2015): Uses multiplicative scores (dot: s_t · h_j; general: s_t^T W h_j) computed from the current decoder state. This is the direct ancestor of Transformer dot-product attention.
Q14.What is the role of the feed-forward sublayer in a Transformer block?
The feed-forward sublayer is a per-token MLP applied after attention. Attention mixes information across tokens, and the FFN then transforms each token's representation nonlinearly. It holds most of the block's parameters and much of the model's stored knowledge.
Structure:
FFN(x) = W_2 · act(W_1 x + b_1) + b_2, with an inner width d_ff of about 4·d_model. The original used ReLU; later models use GELU or SwiGLU.
It is position-wise: the same weights apply to every token independently, with no cross-token interaction.
Division of labor: Attention routes information ("which tokens matter"). The FFN processes it ("what to compute from it").
Adds nonlinearity and capacity:
Attention output is a weighted average of value vectors, so it is linear in the values. Without FFNs, stacked layers would have limited expressive power.
The FFN accounts for roughly two-thirds of the parameters in a standard block.
Interpretation as key-value memory: Rows of W_1 act like keys that detect patterns, and columns of W_2 write the associated values into the residual stream (Geva et al., 2021). Factual knowledge is often localized here.
Modern variants:
SwiGLU gating (LLaMA, Mistral).
Mixture-of-Experts replaces the single FFN with many expert FFNs and a router, which scales parameters without scaling per-token compute.
Q15.What role do residual connections play around each sublayer of a Transformer block?
Each sublayer computes an update that is added to its input (x + Sublayer(x)). This gives gradients an identity path through the whole stack, so deep Transformers can be trained. It also means each layer only has to learn a refinement of the representation, not rebuild it.
Gradient flow: ∂(x + F(x))/∂x = I + ∂F/∂x. The identity term keeps gradients from vanishing as they pass through dozens of layers.
Easy-to-learn defaults: A layer can approximate the identity by outputting near zero, so adding depth rarely hurts. This is the same insight behind ResNets.
Information preservation: Token identity and positional information from the embeddings are carried forward. Attention cannot accidentally wipe them out by averaging.
The residual stream view: The sum acts as a shared communication channel: attention and FFN sublayers read from it and write additive updates back. This is a core idea in mechanistic interpretability.
Design constraints:
Every sublayer must output d_model dimensions so the addition works, which is why the width is constant through the stack.
Residuals are paired with LayerNorm. Where the norm is placed (pre-norm vs post-norm) decides whether the identity path stays clean, and therefore how stable training is.
Q16.What are the two core sublayers inside a standard Transformer encoder block?
An encoder block has two sublayers: multi-head self-attention and a position-wise feed-forward network. Each is wrapped in a residual connection plus layer normalization.
Multi-head self-attention:
Every token attends to every other token (bidirectional, no causal mask). This is the only place where information moves between positions.
Multiple heads let the model attend to different relationships in parallel subspaces.
Position-wise feed-forward network:
The same two-layer MLP is applied independently to each token (d → 4d → d with ReLU or GELU).
It transforms each token's representation and holds most of the block's parameters.
The wrapping around each sublayer:
Original post-norm form: LayerNorm(x + Sublayer(x)). Modern pre-norm form: x + Sublayer(LayerNorm(x)).
Residuals preserve gradient flow through deep stacks, and normalization stabilizes activation scale.
Q17.What sublayers make up a decoder block in the original encoder-decoder Transformer?
Each decoder block has three sublayers: masked multi-head self-attention, encoder-decoder (cross) attention, and a position-wise feed-forward network. Each is wrapped in a residual connection followed by LayerNorm.
Masked (causal) self-attention:
Each target position attends only to earlier positions. Future positions are masked to −∞ before the softmax.
This preserves autoregressive generation while still allowing parallel teacher-forced training.
Cross-attention:
Queries come from the decoder. Keys and values come from the final encoder output.
This is how the decoder conditions on the source sequence, for example to align with source words in translation. No causal mask is needed here.
Position-wise FFN: It is the same per-token two-layer MLP as in the encoder.
Wrapping and stack:
Each sublayer uses LayerNorm(x + Dropout(Sublayer(x))).
The original model stacks 6 such blocks, followed by a linear projection and softmax over the vocabulary.
Decoder-only models such as GPT drop the cross-attention, leaving the same two sublayers as an encoder block plus a causal mask.
Q18.What is the difference between sinusoidal positional encodings and learned positional embeddings?
Both give each absolute position a vector that is added to the token embedding. Sinusoidal encodings are a fixed, parameter-free function of position. Learned embeddings are a trainable lookup table with one row per position, up to a maximum length.
Sinusoidal (original Transformer):
Computed as sin/cos(pos / 10000^(2i/d)): no parameters, deterministic.
Can produce a vector for any position. In practice, models still degrade past the training length because they never learned to use those positions.
Has useful structure: PE(pos+k) is a linear function (a rotation) of PE(pos), which may help the model learn relative offsets.
Learned (BERT, GPT-2):
An nn.Embedding(max_len, d) trained jointly with the model, so it can fit whatever positional patterns the data needs.
Hard cap at max_len: positions beyond it have no embedding. Rarely seen late positions may also be undertrained.
Adds max_len × d parameters.
In practice, the two perform about the same at in-distribution lengths (Vaswani et al. reported nearly identical results).
Both are absolute schemes. Modern LLMs mostly use relative methods (RoPE, ALiBi) instead.
Q19.How do sinusoidal positional encodings convey token positions?
Each position is mapped to a vector of sines and cosines at geometrically spaced frequencies, much like a continuous binary counter. Fast dimensions encode fine position and slow dimensions encode coarse position. The vector is added to the token embedding.
Formula:
PE(pos, 2i) = sin(pos / 10000^(2i/d))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d))
Wavelengths range from 2π up to about 10000·2π.
Multi-scale uniqueness:
High-frequency pairs change sharply between neighbouring tokens, while low-frequency pairs change slowly across the sequence.
Together they give each position a distinct, bounded fingerprint in [-1, 1].
Relative offsets are linear:
Each (sin, cos) pair is a point on a circle, so moving by k positions is a fixed rotation that depends only on k.
This lets attention learn offset-based patterns. The dot product PE(p)·PE(p+k) depends only on k and tends to decay as k grows.
Limitation: adding the encoding mixes position with content, so the model must disentangle the two. RoPE builds on the same frequencies but applies them as rotations instead.
Q20.At what point in the forward pass are positional embeddings combined with token representations?
It depends on the scheme. Absolute encodings are added once, right after the token embedding lookup and before the first Transformer block. Relative schemes inject position inside every attention layer instead.
Absolute (sinusoidal or learned):
Look up token embeddings.
In the original Transformer, scale them by sqrt(d_model).
Add the position embeddings element-wise (summed, not concatenated, so the dimension stays d_model).
Apply dropout, then feed the first block. BERT also adds segment embeddings and applies LayerNorm here.
After that, position lives only implicitly in the residual stream: Deeper layers must preserve it themselves.
RoPE:
Applied in every attention layer, after the W_q and W_k projections and before QK^T.
Nothing is added at the input.
ALiBi and T5 bias:
Added to the attention logits after QK^T / sqrt(d) and before softmax.
Applied in every layer for ALiBi. T5 computes its bias in the first layer of each stack and shares it across all layers.
Q21.What are the structural differences between encoder-only, decoder-only, and encoder-decoder Transformer architectures?
The three differ in which attention masks they use and whether there is cross-attention. Encoder-only uses bidirectional self-attention. Decoder-only uses causal (masked) self-attention. Encoder-decoder pairs a bidirectional encoder with a causal decoder that also cross-attends to the encoder output.
Encoder-only (BERT, RoBERTa):
Layer = full self-attention + FFN, with no mask, so each token sees the whole sequence.
Outputs one contextual vector per token, typically topped with a classification or token-tagging head.
Pretrained with masked language modeling. It cannot generate text autoregressively in a natural way.
Decoder-only (GPT, Llama):
Layer = causal self-attention + FFN. A lower-triangular mask means token i only sees tokens up to i.
Prompt and output share one stream. An LM head predicts the next token.
Supports a KV cache for incremental decoding.
Encoder-decoder (original Transformer, T5, BART):
Encoder stack: bidirectional self-attention over the input.
Decoder stack, in three sublayers per layer:
1) causal self-attention over generated tokens; 2) cross-attention, with queries from the decoder and keys/values from the final encoder output; 3) FFN.
Input and output are separate sequences with separate positional handling.
Shared pieces across all three:
Token embeddings, positional information, residual connections, LayerNorm, and multi-head attention.
The architectural difference really comes down to the mask and the presence of cross-attention.
Q22.Why is a decoder-only architecture like GPT preferred for autoregressive text generation?
GPT preferred for autoregressive text generation?A decoder-only model is trained with exactly the factorization used at generation time: p(x) = Π p(x_t | x_<t). Training and inference therefore match, and generation is just repeated next-token prediction over a single growing sequence.
The causal mask matches the task: Each position sees only earlier tokens, so the model never relies on future context it won't have when generating.
Parallel training via teacher forcing:
All n next-token predictions in a sequence are computed in one forward pass, unlike RNNs.
This makes pretraining on huge corpora efficient.
Efficient incremental decoding:
Past keys and values never change, because of the causal mask, so they can be cached in a KV cache.
Each new token costs O(n) attention instead of recomputing the whole sequence.
No artificial input/output boundary:
Prompt, context, and response live in one stream.
This suits continuation, chat, and in-context examples better than a fixed source/target split.
Simplicity at scale: A single homogeneous stack with one objective is easy to scale, parallelize, and serve.
Contrast with encoder-only models: Bidirectional models like BERT have no natural left-to-right factorization, so generating from them is awkward.
Q23.What is the difference between the masked language modeling objective and the causal next-token prediction objective?
MLM corrupts some tokens and predicts them from both sides (bidirectional context). Causal LM predicts every token from only the tokens before it. MLM yields strong representations; causal LM yields a true generative model.
Masked language modeling (BERT):
About 15% of tokens are selected. Of those, 80% become [MASK], 10% become a random token, and 10% stay unchanged. The model predicts the originals.
There is no attention mask, so each prediction uses left and right context.
Loss only covers the selected tokens, so there is less signal per sequence.
Pretrain/finetune mismatch: [MASK] never appears downstream. The 80/10/10 split mitigates this.
Causal next-token prediction (GPT):
Inputs are shifted by one, and position t predicts token t+1.
A lower-triangular attention mask enforces that only the left context is visible.
Every position contributes to the loss, giving a dense signal.
It defines a full joint distribution, so you can sample from it directly.
Downside: exposure bias. The model trains on ground-truth prefixes but generates from its own outputs.
Consequences:
MLM suits classification, tagging, and embeddings.
Causal LM suits generation, prompting, and in-context learning.
Hybrids exist: T5 span corruption, prefix LM, and UL2 mixtures.
Q24.Why does self-attention have quadratic time and memory complexity with respect to sequence length?
Every token attends to every other token. The score matrix QKᵀ therefore has n×n entries, each a d-dimensional dot product: O(n²·d) compute. Naively materializing that matrix (per head) costs O(n²) memory.
Where the n² comes from:
Q and K are each n×d, so Q @ K.T is n×n and costs about 2n²d FLOPs.
Softmax runs over each row of the n×n matrix.
The weights (n×n) are multiplied by V (n×d), another 2n²d FLOPs.
Contrast with the rest of the layer: Projections and the FFN are per-token, so they cost O(n·d²): linear in n.
Memory:
The n×n score matrix per head per batch element is stored for softmax and backprop.
Example: at n=32K with 32 heads in fp16, that is about 64 GB per layer per sample.
What mitigations change:
FlashAttention: tiles the computation with an online softmax and never materializes n×n. Memory becomes O(n), but compute is still O(n²).
Sparse, sliding-window, or linear attention: reduce the compute itself, at some cost in quality or expressiveness.
KV cache at decode: each step is O(n), but generating n tokens is still O(n²) total. The cache grows linearly with n.
Q25.How does the final output layer turn the last hidden states into next-token probabilities?
The last hidden state is normalized, then projected by a d×V unembedding matrix into one logit per vocabulary token. A softmax turns those logits into a probability distribution over the next token.
Final norm: apply a final LayerNorm/RMSNorm to the residual stream, which is needed in pre-norm models.
Unembedding:
Compute logits = h · W_U (shape (B, T, V)).
Each logit is a dot product between h and that token's output vector, i.e. a similarity score.
If weights are tied, W_U = Eᵀ.
Softmax: p_i = exp(z_i/τ) / Σ_j exp(z_j/τ).:
Temperature τ sharpens or flattens the distribution.
Implementations subtract the max logit for numerical stability.
Training vs inference:
Training: logits at every position feed cross-entropy against the shifted targets. log_softmax is fused into the loss.
Inference: only the last position's logits are needed.
Decoding then picks a token via greedy, top-k, top-p or similar sampling.
Cost: the projection is T·d·V FLOPs and the logits tensor can be huge (vocab of 100k+), so it's often chunked. Some models add logit soft-capping (e.g. Gemma) to bound magnitudes.
Q26.Why are attention scores scaled by the square root of the key dimension in scaled dot-product attention?
Dividing by √d_k keeps the variance of the dot-product logits at about 1, whatever the head dimension. Without it, large logits push softmax into saturation, where it becomes nearly one-hot and its gradients vanish.
Variance grows with dimension:
Assume the components of q and k are independent with mean 0 and variance 1.
Then q·k = Σ q_i k_i has mean 0 and variance d_k, so its standard deviation is √d_k.
Dividing by √d_k brings the variance back to 1.
Why large logits hurt:
Softmax is sensitive to differences between logits. With a spread of around ±20, one key takes nearly all the weight.
A saturated softmax has a Jacobian near zero, so Q and K learn slowly or training becomes unstable.
Attention also collapses to hard selection early, before the model has learned what to attend to.
Why √d_k and not d_k: Scale is set by the standard deviation, not the variance. Dividing by d_k would shrink the logits toward 0 and make attention nearly uniform.
Context: Vaswani et al. note that unscaled dot-product attention underperforms additive attention at large d_k, and this scaling fixes it. Some variants use QK-norm or a learned temperature instead.
Q27.Why is self-attention permutation-equivariant without positional information?
Attention computes each output as a weighted sum over the set of input tokens. The weights depend only on token contents, never on their indices. So if you shuffle the inputs, the outputs are shuffled in exactly the same way, and the model cannot tell word order.
The math:
For a permutation matrix P, feeding PX gives Q' = PQ, K' = PK, V' = PV.
Scores become PQKᵀPᵀ. Row-wise softmax commutes with permuting rows and columns, so Attn(PX) = P·Attn(X).
The rest of the block preserves this:
The FFN, LayerNorm and residual connections act on each token independently, so the whole stack is equivariant.
After pooling (for example a mean), the model becomes fully permutation-invariant: "dog bites man" looks the same as "man bites dog".
Contrast with RNNs and CNNs: RNNs build order into sequential processing. CNNs build in local relative position through their kernels. Attention has no such structural bias.
Fix: inject position:
Absolute encodings (sinusoidal or learned) are added to the embeddings.
Relative methods (RoPE, ALiBi, T5 bias) modify the attention scores directly.
A causal mask breaks the symmetry partially, which is why decoder-only models without explicit positional encodings (NoPE) can still learn some position.
Q28.Why are queries, keys, and values produced through learned linear projections rather than using raw token embeddings directly?
Separate learned projections let each token play three different roles (asking, being matched, contributing content) in task-specific subspaces. Using raw embeddings would force all three roles to share one representation and a fixed, symmetric similarity.
Raw embeddings give a poor similarity:
The score x_i·x_j is symmetric, but relevance is not: a pronoun needs its noun, while the noun may not need the pronoun.
Each token matches itself most strongly (x·x = ‖x‖²), so attention would mostly stay on the token itself.
With projections, the score becomes the bilinear form x_iᵀ W_Q W_Kᵀ x_j, which is a learned and asymmetric notion of relevance.
Decoupling roles: What makes a token findable (K) can differ from what it passes on (V). For example, it might be matched on syntax but deliver meaning.
Enables multi-head attention:
Each head has its own W_Q, W_K, W_V that project into a smaller d_k subspace.
Different heads can then specialize in different relations (position, coreference, syntax) at roughly the same cost as one full-width head.
Learnability:
Without projections, the attention layer would have almost no parameters of its own.
The projections are where gradient signal shapes what each layer attends to, and deeper layers project an already contextualized residual stream.
Q29.Why is dot-product attention used instead of additive attention?
Dot-product attention computes all query-key scores with a single matrix multiply, which is much faster and more memory-efficient on GPUs. Once it is scaled by √d_k, it matches additive attention in quality.
The two scoring functions:
Additive (Bahdanau): score = vᵀ tanh(W_q q + W_k k). This is a small feedforward network evaluated for every query-key pair.
Dot-product (Luong/Vaswani): score = q·k / √d_k, which needs no extra parameters inside the score.
Efficiency:
Dot-product scores are one QKᵀ GEMM, which is heavily optimized and maps well onto tensor cores and fused kernels like FlashAttention.
Additive attention needs an n × m × d intermediate tensor followed by a nonlinearity, so it is memory-bound and harder to fuse.
Quality:
The two are theoretically similar in complexity.
Unscaled dot-product attention lost to additive attention at large d_k because of softmax saturation. Scaling closes that gap.
Expressiveness is enough:
The learned W_Q and W_K already make the score a learned bilinear form.
Stacking multiple heads and layers supplies the nonlinearity that additive attention puts inside each score.
Q30.Why is the softmax in attention applied over the key dimension rather than the query dimension?
softmax in attention applied over the key dimension rather than the query dimension?Each query needs its own distribution over the things it can read from. Normalizing over keys gives every output a weighted average of values whose weights sum to 1. Normalizing over queries would answer a different and unhelpful question: how a key divides itself among the queries.
Output row i is Σ_j w_ij v_j:
For this to be a proper weighted average, the weights w_ij must sum to 1 over j (the keys).
This keeps every output on the same scale as the values.
What goes wrong with query-wise softmax:
Each query's weights over the keys would no longer sum to 1, so output magnitudes would vary arbitrarily.
Queries would compete with each other: one query's attention would depend on what other positions want. That couples positions in an odd way and breaks causal decoding, since future queries would affect past outputs.
Masking and caching depend on it:
Causal and padding masks restrict which keys each query may see, so normalization must happen over that same per-query key set.
Incremental decoding with a KV cache computes one new query against all cached keys. This only works if each query is normalized independently.
In code, this means softmax runs over the last axis (keys).
Q31.Why is masking applied before the softmax rather than after it?
softmax rather than after it?Softmax normalizes over every logit in the row. Masking before it removes blocked positions from both the numerator and the denominator, so the remaining weights form a proper distribution over allowed positions only.
Masking before softmax (correct):
Set blocked logits to −∞, so exp(−∞) = 0.
Allowed weights renormalize and sum to 1.
Blocked positions contribute nothing to the forward pass or the gradients.
Zeroing after softmax (wrong):
Rows no longer sum to 1, so the output is a shrunken, inconsistently scaled average.
Masked logits still sat in the softmax denominator. Future or pad tokens therefore influence the surviving weights, and the gradient flows into them. This is information leakage in causal models.
You could renormalize afterwards, but that just reimplements pre-softmax masking with extra work and worse numerics.
Practical bonus: an additive mask on the logits is cheap and fuses easily into attention kernels (e.g. FlashAttention).
Q32.Why is a large negative value such as negative infinity used for masked positions in the attention score matrix?
Masking happens on logits that are then exponentiated. Adding −∞ (or a very negative number) makes exp of that logit 0, or effectively 0, so the position gets zero probability and the softmax renormalizes over the rest.
Why not just use 0?:
A logit of 0 gives exp(0) = 1, which is a perfectly ordinary weight. Zero means "neutral", not "blocked".
Multiplying logits by 0 fails for the same reason.
Additive form is convenient:
scores + M, where M is 0 for allowed positions and −∞ for blocked ones. This is cheap, broadcastable and kernel-friendly.
Gradients through masked entries are exactly 0.
−∞ vs a finite large negative number:
True −∞ gives exact zeros. However, if an entire row is masked (e.g. a padded query under left padding), the softmax computes −∞ − (−∞), which is NaN.
Many implementations therefore use torch.finfo(dtype).min or −1e9. These yield a uniform distribution instead of NaN on fully masked rows.
Dtype matters: −1e9 overflows to −∞ in fp16 (max about 65504). Use a dtype-aware minimum.
Q33.How do you combine a padding mask and a causal mask into a single attention mask?
Build both masks as booleans that broadcast to (B, heads, T_q, T_k) and combine them with logical AND, if True means "may attend". Then convert the result to an additive mask: 0 where allowed, −∞ or the dtype minimum where blocked.
Shapes:
Causal mask: (1, 1, T, T) lower-triangular. It is the same for every example.
Padding mask: (B, 1, 1, T_k), from attention_mask. It blocks pad keys for every query.
Broadcasting produces (B, 1, T, T).
Combination rule depends on the convention:
True = allowed: use AND (causal & pad). This is the convention of F.scaled_dot_product_attention.
True = blocked: use OR. This is the convention of nn.MultiheadAttention's key_padding_mask and attn_mask.
Additive float masks: sum them. −∞ + 0 is still −∞. Use the dtype minimum to avoid overflow when two minimums add up.
Edge case: fully masked rows:
With left padding, pad queries can have every key blocked, which produces NaN with −∞.
Fixes: use a finite minimum, or let pad queries attend to themselves. Their outputs are ignored in the loss anyway.
Q34.What is the purpose of the output projection matrix after concatenating attention heads?
The output projection W_O (shape h·d_v × d_model) learns how to mix the heads' outputs and maps the concatenated result back into the model's residual stream. Without it, each head could only write into its own fixed slice of dimensions.
Mixes information across heads:
Concatenation just stacks the head outputs side by side. W_O lets each output dimension be a learned combination of every head's features.
An equivalent view: concat(head_1..head_h) W_O = Σ_i head_i W_O^i. Each head gets its own output matrix, and the results are summed into the residual stream.
Restores the model dimension: The output must be d_model wide so the residual add (x + MHA(x)) works. W_O also allows h·d_v ≠ d_model if desired.
Decouples head subspaces from the residual basis: Heads compute in small learned subspaces. W_O decides where in the shared d_model space their results are written, so downstream layers and the FFN can read them.
Cost: d_model² parameters, which is a quarter of the attention layer's weights.
Q35.How many trainable parameters are in a standard multi-head self-attention layer with hidden dimension d_model?
d_model?The layer has 4·d_model² + 4·d_model parameters: four d_model × d_model weight matrices (Q, K, V, output) plus their biases. The total does not depend on the number of heads.
Breakdown:
W_Q, W_K, W_V: each is d_model × d_model, which is all h heads' d_model × d_k matrices stacked, with h·d_k = d_model.
W_O: d_model × d_model.
Biases: 4·d_model. Many modern LLMs drop them, giving exactly 4·d_model².
Example: d_model = 768 (BERT-base): 4·768² + 4·768 = 2,359,296 + 3,072 = 2,362,368
Why h doesn't matter: more heads only means a finer split of the same matrices.
Variants change the count:
MQA and GQA share K/V across heads. W_K and W_V shrink to d_model × (g·d_k), where g is the number of KV groups.
LayerNorm parameters (2·d_model) are usually counted separately.
Q36.Does using h heads with head dimension d_model/h increase computational cost compared to a single head of size d_model?
h heads with head dimension d_model/h increase computational cost compared to a single head of size d_model?Not in matmul FLOPs: projections and attention matmuls cost the same as one d_model-wide head. The real overheads are the h × N × N attention matrices (softmax work and memory) and lower hardware efficiency for small heads.
Projections are unchanged: Q, K, V and output projections cost 4·N·d² either way. They are the same matrices, just reshaped.
Attention matmuls are unchanged:
QKᵀ: h · N² · (d/h) = N²·d, identical to a single head.
The same holds for attention × V.
What does scale with h:
The number of score entries is h·N² instead of N², so scaling, masking, softmax and dropout do h× more elementwise work.
Storing attention weights for backprop takes h× more memory. FlashAttention avoids materializing them.
Hardware efficiency:
Small d_k means many small batched matmuls with lower arithmetic intensity, so wall-clock time can rise slightly.
This is why d_k is typically kept around 64 to 128.
Q37.What are the tensor shapes at each stage of a multi-head attention forward pass for a sequence of length N and hidden dimension d?
N and hidden dimension d?With batch B, h heads and d_k = d/h, activations go from (B, N, d) to per-head (B, h, N, d_k), through (B, h, N, N) attention scores, and back to (B, N, d).
Input X: (B, N, d)
Projections Q, K, V = X W_Q, X W_K, X W_V: each (B, N, d)
Split heads with view to (B, N, h, d_k), then transpose to (B, h, N, d_k)
Scores Q Kᵀ / √d_k: (B, h, N, N). The mask broadcasts here.
Softmax over the last (key) axis: (B, h, N, N)
Weighted values A V: (B, h, N, d_k)
Merge heads: transpose to (B, N, h, d_k), then reshape to (B, N, d). This needs .contiguous() or reshape.
Output projection W_O: (B, N, d)
Q38.Why do RNNs suffer from vanishing gradients across long sequences whereas Transformers do not?
In an RNN, the gradient from step t to step k is a product of t−k Jacobians, so it shrinks (or explodes) exponentially with distance. In a Transformer, attention links any two positions directly, so gradient path length depends on the number of layers, not on sequence length.
RNN: repeated multiplication through time:
With h_t = tanh(W h_{t-1} + U x_t), the gradient ∂h_t/∂h_k = ∏ diag(tanh′)·W.
Since tanh′ ≤ 1, if W's largest singular value is below 1 the gradient decays geometrically with distance. If above 1, it can explode.
As a result, early tokens get almost no learning signal from distant losses.
LSTM and GRU only mitigate this: An additive, gated cell state gives a near-identity path. The path is still O(N) long, and gates below 1 still cause decay.
Transformer: direct connections:
Each output is a weighted sum over all positions, so the gradient flows from any token to any other in one attention step.
There is no product over time steps, and depth equals the number of layers (for example 12 to 100), not N.
Residual connections across depth: x + f(x) adds an identity term to each layer's Jacobian. Gradients therefore reach early layers undiminished, with LayerNorm helping stabilize scale.
Caveats:
Transformers can still have depth-related instability: Post-LN models need learning-rate warmup.
A saturated softmax gives tiny gradients, which is one reason scores are scaled by √d_k.
Over very long contexts, attention spread across many tokens can dilute the signal.
Q39.How does self-attention achieve a constant maximum path length between arbitrary tokens in a sequence?
In a single self-attention layer, every token computes a weighted sum over every other token directly. So information travels from any position to any other in one step: an O(1) path length, regardless of how far apart the tokens are.
What "path length" means: It is the number of computation steps a signal (forward) or gradient (backward) must pass through between two positions. Shorter paths make long-range dependencies easier to learn.
How self-attention gets O(1):
Each query is scored against all keys at once (softmax(QK^T / sqrt(d_k)) V), so token i has a direct weighted edge to every token j.
There is no intermediate state to relay through, unlike recurrence.
Comparison (Vaswani et al., Table 1):
RNN: O(n) path, since information hops one step per token.
CNN: O(n/k) path with contiguous kernels, or O(log_k n) with dilated convolutions.
Self-attention: O(1) path, with O(1) sequential operations, so it is fully parallel.
The price: Per-layer cost is O(n²·d) in compute and O(n²) in attention memory, which is why long-context work focuses on efficient attention.
Caveat: A short path makes dependencies learnable, but it does not guarantee they are learned. With a causal mask, the O(1) path still holds, but only to earlier tokens.
Q40.How does a SwiGLU feed-forward layer differ from a standard two-layer MLP?
SwiGLU feed-forward layer differ from a standard two-layer MLP?A standard MLP is two linear layers with a pointwise nonlinearity between them. SwiGLU adds a third projection that acts as a learned, input-dependent gate: one branch goes through SiLU (Swish), and it is multiplied elementwise with a second linear branch before the down-projection.
Standard FFN (original Transformer):
FFN(x) = W2 · ReLU(W1 x + b1) + b2: two matrices, d → 4d → d.
The nonlinearity only decides, per unit, whether a value passes or gets zeroed.
SwiGLU FFN (Shazeer 2020, used in LLaMA, PaLM, Mistral):
FFN(x) = W2 · (SiLU(W1 x) ⊙ W3 x): three matrices (gate, up, down), usually with no biases.
The gate branch scales the up branch multiplicatively. This gives the layer multiplicative interactions between features, which a plain MLP lacks.
SiLU is smooth and non-monotonic, so gradients are better behaved than with ReLU's hard cutoff.
Practical consequences:
There are three weight matrices instead of two, so the hidden size is shrunk to about 8/3·d to keep parameters and FLOPs equal.
At matched compute it gives consistently lower perplexity and better downstream scores. The gain is empirical: the original paper does not offer a theoretical explanation.
Q41.Why is the feed-forward hidden dimension conventionally expanded to four times the model dimension?
It is an empirical convention from the original Transformer (d_model = 512, d_ff = 2048), not a derived optimum. A wider hidden layer gives the per-token FFN enough capacity while keeping the compute balance with attention reasonable, and later models simply kept the ratio.
Capacity:
Attention mixes information across tokens. The FFN is where most per-token transformation and stored knowledge live (it is often viewed as a key-value memory).
Expanding to a higher dimension before the nonlinearity lets the layer represent many more features than d alone would allow.
Parameter and compute budget:
With 4x, the FFN holds 8d² parameters versus 4d² for attention's Q, K, V and O projections. That is roughly two-thirds of each block's parameters.
This was found to be a good trade-off: wider brings diminishing returns per FLOP, narrower hurts quality.
Hardware friendliness: Large, regular matmuls with power-of-two-ish sizes map efficiently to GPUs and TPUs.
It's not sacred:
SwiGLU models use about 8/3 to keep parameters matched.
Some models use other ratios, and MoE layers change the picture entirely. Scaling studies show performance is fairly insensitive to the exact ratio over a wide range.
Q42.Where is dropout applied within a Transformer block?
In the original Transformer, dropout is applied to the output of each sublayer before it is added to the residual, and to the sum of token embeddings plus positional encodings (P_drop = 0.1). Common implementations also add dropout to the attention weights and inside the FFN.
Residual dropout (from the paper):
The pattern is LayerNorm(x + Dropout(Sublayer(x))), or x + Dropout(Sublayer(LN(x))) in pre-norm.
It is applied after both the attention sublayer and the FFN sublayer.
Embedding dropout: It is applied to token embedding plus positional encoding at the input of both the encoder and decoder stacks.
Attention dropout (standard in implementations): It is applied to the softmax attention probabilities before multiplying by V, which randomly removes some token-to-token connections.
FFN activation dropout (some implementations): It is applied after the nonlinearity, between the two linear layers.
Modern LLM pretraining: Dropout is often set to 0 (e.g. LLaMA). With huge datasets and roughly one epoch, overfitting matters less than throughput. It is still used for fine-tuning and for smaller-data settings.
Q43.What is the difference between absolute and relative positional encodings?
Absolute encodings tag each token with its own index ("I am at position 7"). Relative encodings make attention depend on the offset between query and key ("you are 3 tokens before me"), usually by modifying the attention computation itself.
Absolute:
A position vector (sinusoidal or learned) is added to token embeddings once, at the input.
The model must work out relative distance indirectly, by comparing two absolute codes.
Tied to the training length range, so it extrapolates poorly.
Relative:
Injected inside every attention layer, as a function of i - j.
Common variants:
Shaw et al.: learned relative embeddings added to keys and values.
T5: a learned scalar bias per distance bucket.
ALiBi: a fixed linear distance penalty.
RoPE: rotates queries and keys so their dot product depends only on the offset.
Why relative is often preferred:
Translation invariance: a pattern like "adjective right before noun" looks the same anywhere in the sequence.
Better length generalization, and a natural fit with KV caching.
Costs: some variants add per-layer compute, or break fast fused attention kernels when they need a full bias matrix.
Q44.How does a learned relative position bias like T5's inject position information into attention?
T5's inject position information into attention?T5 adds a learned scalar to each attention logit. The scalar is chosen by the bucketed relative distance between query and key. Position affects only how much tokens attend to each other, never the token representations themselves.
Score:
score(i, j) = q_i·k_j + b_h[bucket(j - i)], then softmax.
No positional embeddings are added at the input.
T5 also omits the 1/sqrt(d) scaling, folding it into weight initialization.
Bucketing:
32 buckets by default, split by direction in the bidirectional encoder.
Small offsets get exact buckets; larger offsets share logarithmically spaced buckets.
Everything beyond max_distance (128) falls into the last bucket.
This gives fine resolution nearby, coarse resolution far away, and a defined bias for any length.
Parameters:
One nn.Embedding(num_buckets, n_heads) per stack, giving each head its own distance preferences (local vs. broad).
Computed in the first layer and shared across all layers of that stack, so it is very cheap.
Trade-offs:
Purely relative, which helps generalization.
Requires materializing an L×L bias matrix, which is slower with fused attention kernels.
Far distances are indistinguishable once they share the last bucket.
Q45.When would you choose an encoder-decoder architecture like T5 over a decoder-only model?
T5 over a decoder-only model?Choose an encoder-decoder when the task is a clear input-to-output transformation (translate, summarize, transcribe), the input is long relative to the output, and you fine-tune a moderate-size model for that one task. The bidirectional encoder reads the input fully once, and a lighter decoder generates from it via cross-attention.
Bidirectional understanding of the input:
Every input token attends to every other token, so the input representation is richer than a causal prefix.
This helps when the output depends on the whole source (translation, structured extraction, rewriting).
Efficiency for long input with short output:
The encoder runs once over the input in parallel. The decoder only self-attends over the short output and cross-attends to cached encoder states.
Compute can be split asymmetrically: a big encoder with a small decoder, as in summarization or ASR (e.g. Whisper).
Different input and output modalities or formats: Examples: speech to text, image to caption, code to docstring. Cross-attention is a natural bridge between the two sides.
Strong at fine-tuned, task-specific scale: T5's span-corruption pretraining plus the text-to-text framing makes it a strong base for supervised seq2seq tasks at sub-billion to few-billion sizes.
When to prefer decoder-only instead:
You need open-ended, general-purpose behavior: chat, in-context learning, or many tasks behind one prompt interface.
You want to ride frontier-scale pretrained checkpoints and the inference tooling around them (KV-cache serving, vLLM).
Input and output are interleaved, as in multi-turn dialogue, so there is no clean source/target split.
Q46.When would you choose an encoder-only architecture over a decoder-only architecture?
Choose encoder-only when the task is understanding rather than generating: classification, tagging, embeddings, retrieval, or reranking. Bidirectional context gives strong representations from a small, fast, cheap model.
Bidirectional context:
Each token's representation uses both left and right context.
This matters for token-level tasks (NER, span extraction) where a causal model only sees the prefix.
Natural fit for fixed-output tasks:
Sequence classification uses [CLS] or mean pooling plus a linear head.
Bi-encoders for semantic search and cross-encoders for reranking are mostly encoder-based (e.g. sentence-transformers).
Cost and latency:
A single forward pass, with no autoregressive loop.
Models of 100M to 400M parameters often match much larger LLMs on narrow labeled tasks. That makes them suitable for high-QPS or on-device serving.
Plenty of labeled data:
Fine-tuning a BERT-style model is stable and cheap.
It gives calibrated class probabilities instead of parsing generated text.
When to pick decoder-only instead:
You need generation, few-shot or zero-shot flexibility, or reasoning.
Labels are scarce and prompting a large model is acceptable on cost.
Q47.Which operations in a transformer forward pass scale linearly with sequence length and which scale quadratically?
Everything that processes tokens independently scales linearly in sequence length n. Only the token-to-token interaction inside self-attention, the score matrix and its use, scales quadratically. Per layer, linear work is about 24·n·d² FLOPs and quadratic work about 4·n²·d, so attention dominates once n exceeds roughly 6d.
Linear in n (per-token work, O(n·d²) or O(n·d)):
Token embedding lookup and positional encodings (including RoPE applied to Q/K).
Q, K, V and output projections: 4 matrices of d×d, applied to each token.
FFN: d→4d→d per token. This is the largest linear cost.
LayerNorm/RMSNorm, residual adds and activations.
Final unembedding to vocab logits: n·d·V.
Quadratic in n (pairwise interactions):
Computing scores QKᵀ: an n×n matrix per head, costing O(n²·d).
Masking, scaling and softmax over that n×n matrix.
Weighted sum softmax(·)·V: also O(n²·d).
Memory for the attention matrix in naive implementations: O(n²) per head.
Nuances interviewers probe:
FlashAttention makes attention memory linear by tiling and never materializing n×n. The FLOPs stay quadratic.
For short contexts with large d, the FFN and projections dominate, so the quadratic term matters mainly for long context.
Autoregressive decoding with a KV cache works differently. Each new token does O(n·d) attention work against the cache, and cache memory grows linearly in n. The total over a full generation is still O(n²).
Q48.Can you walk through the forward pass of a sequence through a single decoder-only Transformer block?
A decoder block takes a (B, T, d) tensor and returns the same shape. It runs two residual sub-layers: causal multi-head self-attention, which mixes information across earlier positions, then a position-wise FFN, which transforms each token independently. Each sub-layer is preceded by a normalization layer in the modern pre-norm design.
Normalize: h = LN(x) (LayerNorm or RMSNorm).
Project to Q, K, V:
Compute Q = hW_Q, K = hW_K and V = hW_V, then split into H heads of size d/H.
Apply positional information here if the model uses RoPE (rotate Q and K).
Causal attention per head:
Scores are QKᵀ/√d_k. Add a mask of -inf above the diagonal so token t sees only positions ≤ t.
Take a row-wise softmax, then form a weighted sum of V.
Merge heads: concatenate the heads, apply the output projection W_O, and add the residual: x = x + attn.
FFN sub-layer:
Compute x = x + FFN(LN(x)).
The FFN expands to about 4d, applies a nonlinearity (GELU, or SwiGLU with a gate), and projects back to d.
Output keeps shape (B, T, d) and feeds the next block. After the last block come a final norm and the unembedding to logits.
Why pre-norm: the residual stream stays an unnormalized identity path, which keeps gradients stable in deep stacks. The original post-norm design (normalize after the add) is harder to train without warmup.
Q49.What are the tradeoffs of tying the input and output embeddings?
Tying means the output projection reuses the input embedding matrix: logits = h · Eᵀ.
Benefits:
Parameter savings: removes V·d parameters. For a small model with a 50k–250k vocab, this can be a large share of the total.
Better learning signal for rare tokens
The softmax gradient touches every output row each step. An untied input embedding only updates rows for tokens actually present in the batch.
Regularization: Press & Wolf (2017) found tying improved perplexity in language models.
Costs:
Role mismatch
Input embeddings encode "what this token is". Output rows encode "which contexts predict this token next". Forcing one matrix to serve both constrains its geometry, and the model must spend capacity reconciling the two.
Scale issues: embedding and logit magnitudes want different scales, which is why the original Transformer multiplies embeddings by √d.
Savings vanish at scale: at 70B parameters, V·d is negligible, so many large LLMs untie (e.g. LLaMA). Small models such as GPT-2 and Gemma often tie.
Systems complexity
With pipeline parallelism the first and last stages share a weight, which needs an extra gradient sync. It also complicates per-layer optimizer or initialization schemes (e.g. muP treats input and output layers differently).
Rule of thumb: tie when the vocab is a large fraction of the parameters or data is limited. Untie for large models where the flexibility is worth the memory.
Q50.How do you estimate the number of parameters in a single Transformer layer given hidden size d and an FFN dimension of 4d?
d and an FFN dimension of 4d?Add up the weight matrices. Attention has four d×d projections (4d²) and the FFN has two d×4d matrices (8d²), so a layer has about 12d² parameters. Biases and norms add only O(d).
Attention: W_Q, W_K, W_V, W_O at d² each gives 4d², plus 4d biases.: The head count doesn't matter: H heads of size d/H still total d×d.
FFN: d×4d + 4d×d = 8d², plus 4d + d biases.
Norms: 2 LayerNorms with 2d each (gain and bias) gives 4d.
Total: 12d² + 13d ≈ 12d².: Example: d = 4096 gives about 201M per layer. 32 layers give about 6.4B, plus embeddings V·d.
Common variants:
SwiGLU uses 3 matrices with hidden size about 8d/3, deliberately keeping the FFN at about 8d².
GQA shrinks W_K, W_V to d × (n_kv·d_head), so attention is less than 4d².
Bias-free models with RMSNorm make the small terms even smaller.
Related rule of thumb: training FLOPs are about 6·N·tokens, and the forward pass is about 2·N FLOPs per token (excluding attention-score terms).
Q51.How does grouped-query attention differ from multi-head attention and multi-query attention?
All three keep H query heads. They differ only in how many key/value heads exist:
MHA: H KV heads.
MQA: 1 shared KV head.
GQA: G KV heads, each shared by a group of H/G query heads.
GQA interpolates between the other two: G = H is MHA and G = 1 is MQA.
Multi-head attention (MHA):
Every head has its own K and V, giving the most expressiveness.
The KV cache is the largest: proportional to H·d_head per token per layer.
Multi-query attention (MQA, Shazeer 2019):
One K/V head shared by all query heads, so the KV cache is H× smaller and decoding is much faster.
Can lose quality and can be less stable in training.
Grouped-query attention (GQA, Ainslie et al. 2023):
Shrinks the KV cache by H/G with quality close to MHA.
Used in Llama 2 70B, Llama 3 and Mistral (e.g. 32 query heads, 8 KV heads).
An MHA checkpoint can be "uptrained" to GQA by mean-pooling K/V heads within each group and continuing training for about 5% of the original compute.
What it does and doesn't save:
Attention FLOPs are roughly unchanged, since queries still attend per head.
The win is KV cache size and memory bandwidth during decoding, enabling larger batches and longer contexts. There is also a small reduction in K/V projection parameters.
Under tensor parallelism with more shards than KV heads, KV heads must be replicated.
Q52.What is the difference between exact efficient attention like FlashAttention and approximate attention like sparse or linear attention?
FlashAttention and approximate attention like sparse or linear attention?Exact efficient attention such as FlashAttention computes the same function as standard attention and only reorganizes the computation to reduce memory traffic. Approximate attention changes the function itself so that fewer scores are computed, trading accuracy for lower asymptotic cost.
Exact (FlashAttention):
Output matches standard attention up to floating-point rounding, so it is a drop-in replacement with no retraining.
FLOPs stay O(N²d); the gains come from O(N) memory and far fewer HBM reads and writes.
Wall-clock time improves, but very long contexts remain fundamentally quadratic.
Approximate: sparse:
Only selected pairs are scored (local windows, strided patterns, global tokens), as in Longformer and BigBird.
Cost falls to roughly O(N·w) or O(N√N).
Interactions outside the pattern are dropped.
Approximate: linear / low-rank:
Kernel feature maps or projections (Performer, Linformer) give O(N) cost.
Attention patterns become softer and recall weakens.
Practical differences:
Approximate methods usually must be trained with the approximation in place and can lose quality.
At moderate N they are often not faster in wall-clock terms, because their memory access is irregular and less GPU-friendly.
The two ideas combine: block-sparse or sliding-window variants can run inside FlashAttention kernels.
Q53.How does sliding-window attention trade global context for reduced computational cost?
Each token attends only to the previous w tokens instead of the whole sequence. This cuts compute from O(N²) to O(N·w) and caps the KV cache at w entries. The cost is that distant information can only reach a token indirectly, by hopping through layers.
Cost savings:
Compute and memory grow linearly with sequence length for a fixed w.
The KV cache becomes a rolling buffer of size w, so decoding memory stays constant regardless of context length.
How global context is partly recovered:
Stacking layers widens the receptive field by about w per layer, giving roughly L·w in total.
Example: Mistral 7B uses w = 4096 and 32 layers, for a theoretical reach of about 131k tokens.
What is lost:
Multi-hop propagation is lossy and compressed, so there is no direct token-to-token lookup beyond w.
Exact long-range retrieval suffers (needle-in-a-haystack tests, copying a far-back fact).
Common mitigations:
Interleave full global-attention layers with local ones (Gemma 2/3).
Add designated global tokens that attend everywhere (Longformer, BigBird).
Keep attention-sink tokens for stable streaming generation (StreamingLLM).
Q54.How would you verify that a from-scratch multi-head attention implementation is correct?
Combine three checks: compare numerically against a trusted reference using identical weights, test the invariants attention must satisfy (shapes, normalization, masking with no leakage), and run gradient and training sanity checks.
Reference comparison (strongest test):
Copy your Q/K/V/O weights into torch.nn.MultiheadAttention, or call F.scaled_dot_product_attention on your projected heads.
Assert torch.allclose(out, ref, atol=1e-5) with and without masks, and for several batch sizes, sequence lengths and head counts.
Also compare against a naive per-head Python loop. This catches reshape and transpose bugs when splitting or merging heads.
Invariant tests:
Output shape matches the input shape (B, T, d_model).
Attention weights are ≥ 0 and each row sums to 1.
Without positional encodings, self-attention is permutation-equivariant: permuting the input tokens permutes the output the same way.
With one head and identity projections, the result equals the plain formula softmax(QKᵀ/√d)V.
Masking and leakage tests:
Causal mask: perturb token t+1 onward. Outputs at positions ≤ t must not change. Equivalently, the gradient of output t with respect to future inputs must be exactly 0.
Padding: changing the contents of padded positions must not change the outputs at real tokens.
Fully masked rows must not produce NaN.
Gradient and training checks:
Run torch.autograd.gradcheck in float64 on small inputs (only needed for custom backward passes or kernels).
Overfit a tiny batch (e.g. a copy or reverse task). The loss should go to about 0.
In fp16/bf16, compare to an fp32 run with a looser tolerance.
Q55.What kinds of patterns do different attention heads tend to specialize in?
Probing studies show heads often specialize in recognizable roles. Common ones are positional (previous or next token), syntactic relations, "no-op" attention to special tokens, and algorithmic behaviors such as copying via induction heads.
Positional heads: These attend to the previous or next token, or to a fixed offset. They are common in early layers.
Syntactic heads:
Examples: verb to its object, determiner to noun, a modifier to its head word, coreference.
Clark et al. (2019, "What Does BERT Look At?") and Voita et al. (2019) found heads tracking specific dependency relations.
Delimiter and sink heads:
These put most weight on [SEP], [CLS], BOS, or punctuation.
This often acts as a "no-op" when the head has nothing useful to do, an effect related to "attention sinks".
Rare-word and broad heads: Some focus on rare or informative tokens. Others spread attention almost uniformly, effectively acting like bag-of-words pooling.
Algorithmic and circuit heads (decoder LMs):
Induction heads find an earlier occurrence of the current token and copy what followed it. They are a key mechanism for in-context learning (Olsson et al., 2022).
Others include duplicate-token heads and name-mover heads, as in the indirect-object-identification circuit in GPT-2.
Rough layer trend: lower layers are local and positional, middle layers syntactic, upper layers more semantic and task-specific.
Caveats:
Attention weights are not a full explanation, since value vectors and W_O also matter.
Many heads are redundant or polysemantic and can be pruned.
Q56.Why does pre-norm train more stably than post-norm in deep transformers?
Pre-norm keeps the residual path a pure identity from the output back to the input, so gradients flow cleanly through any depth. Post-norm puts LayerNorm on the residual path itself, which distorts gradients layer after layer and makes them large near the output at initialization. That is why post-norm needs careful learning-rate warmup and often diverges when the model is deep.
The two forms:
Post-norm (original Transformer): x_{l+1} = LN(x_l + F(x_l))
Pre-norm (GPT-2 and most LLMs): x_{l+1} = x_l + F(LN(x_l)), with a final LN before the output head.
Why post-norm is fragile:
Every gradient passes through every LayerNorm on its way down, so there is no clean shortcut.
Xiong et al. (2020) showed that at initialization, post-norm's expected gradients for parameters near the output are large, so a big learning rate early on is unstable. Warmup is needed to compensate.
The effect compounds with depth.
Why pre-norm is stable:
The un-normalized residual stream gives an identity gradient path (∂x_L/∂x_l includes an identity term).
Each sublayer sees normalized input, so its output scale is controlled.
Gradients stay well-scaled across layers, so it often trains with little or no warmup and at higher learning rates.
Trade-offs:
In pre-norm, the residual stream norm grows with depth, so later layers contribute relatively less. Deep layers can become less effective.
When post-norm trains successfully, it can reach slightly better quality. Hybrids try to get both stability and quality: DeepNorm (scaled residuals with post-norm), sandwich-norm, and QK-norm.
Q57.Why is the hidden dimension of a SwiGLU block typically reduced to about 8/3 of the model dimension instead of 4 times?
SwiGLU block typically reduced to about 8/3 of the model dimension instead of 4 times?Q58.Why is an additional final LayerNorm needed at the output of a pre-norm Transformer stack?
LayerNorm needed at the output of a pre-norm Transformer stack?Q59.How does Rotary Position Embedding (RoPE) encode relative position information?
Q60.Why does ALiBi extrapolate to longer sequences better than absolute positional embeddings?
ALiBi extrapolate to longer sequences better than absolute positional embeddings?Q61.Why do relative positional methods extrapolate better to unseen sequence lengths than absolute positional encodings?
Q62.Why is RoPE applied to queries and keys rather than to the input embeddings?
RoPE applied to queries and keys rather than to the input embeddings?Q63.Why are decoder-only architectures dominant even for tasks that do not strictly require generation?
Q64.At what sequence lengths does attention compute begin to dominate feed-forward compute?
Q65.How do width, depth and number of attention heads trade off when scaling a transformer under a fixed parameter budget?
Q66.What inference memory bottleneck motivated multi-query and grouped-query attention?
Q67.What is the quality-versus-memory trade-off among MHA, GQA, and MQA?
MHA, GQA, and MQA?Q68.Why do query heads in the same GQA group produce different representations even though they share key and value heads?
GQA group produce different representations even though they share key and value heads?Q69.How does FlashAttention compute exact attention without materializing the full N by N attention matrix in high-bandwidth memory?
FlashAttention compute exact attention without materializing the full N by N attention matrix in high-bandwidth memory?Q70.How does FlashAttention handle the backward pass without storing the full attention matrix?
FlashAttention handle the backward pass without storing the full attention matrix?Q71.How does linear attention achieve sub-quadratic complexity compared to softmax attention?
Q72.What GPU memory hierarchy bottleneck makes standard self-attention memory-bandwidth bound?
Q73.How do sparse attention patterns that combine local windows with global tokens preserve long-range information?
Q74.Why have linear attention methods often underperformed softmax attention in model quality?
Q75.How can you extend a RoPE-based model's context window beyond the length it was trained on?
RoPE-based model's context window beyond the length it was trained on?