Generalization Gaps and the Mechanics of Transformer Attention
Machine LearningModel answerLast updated
Diagnose and fix overfitting in linear and deep models, then explain self-attention (queries, keys, values, softmax weights) and why and how Transformers inject position information.
You are preparing for a machine learning engineering screen. Answer the five fundamentals questions below. Be precise, justify why each technique works, and point out trade-offs.
- Diagnosis. Define overfitting. Which training and validation metrics or plots would you inspect to tell whether a model is overfitting, as opposed to underfitting?
- Linear models. Suppose a linear or logistic regression model generalizes poorly. What would you change to reduce overfitting?
- Deep networks. Suppose a deep neural network generalizes poorly. What techniques would you apply, and how does your approach differ from the linear case?
- Self-attention. Walk through how a Transformer self-attention layer works. What are queries, keys, and values, and how are the attention weights computed and used?
- Position. Why does a Transformer need explicit positional information? Describe at least two ways to supply it.
Structure your answer by question number. Use formulas where they clarify, and mention common pitfalls.
Hints
Hint 1
For question 1, think about what happens to the two loss curves over epochs, and what a small gap with both errors high would indicate instead. Also consider whether your validation split could hide the problem (leakage, time ordering).
Hint 2
For questions 2 and 3, group techniques by what they limit: model capacity, weight magnitude, the amount of effective data, or training duration. Then ask which of these groups are explicit penalties and which are implicit.
Hint 3
For question 4, write the formula softmax(QK^T / sqrt(d_k)) V and explain each piece: what each projection is for, why the scaling is there, what the softmax is normalized over, and what the output for one token is.
Hint 4
For question 5, ask what happens to the output if you permute the input tokens. Then list schemes that add position to the embeddings versus schemes that modify the attention scores.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. What overfitting is and how to detect it
Definition. A model overfits when it learns noise and quirks of the training sample rather than the underlying signal. Training error is low, error on unseen data is much higher, and the generalization gap is large. In bias-variance terms this is a high-variance regime.
Detection.
- Loss curves over epochs. Training loss keeps falling while validation loss flattens and then rises. The minimum of validation loss marks the best stopping point.
- Gap at convergence. For example, 99% training accuracy against 80% validation accuracy. If both are poor and close together, the model is underfitting (high bias), and the fix is more capacity or better features, not regularization.
- Learning curves versus dataset size. If validation error keeps improving as data grows and the gap narrows, the model is variance-limited and more data helps.
- Cross-validation. Large variation in fold scores is another sign.
Pitfalls.
- The validation set must resemble deployment. For time-dependent data, split by time rather than randomly.
- Leakage (duplicate users or near-duplicate samples across splits) hides overfitting.
- Heavy tuning on the validation set overfits it, so keep an untouched test set for the final number.
2. Reducing overfitting in a linear model
Linear models overfit mainly when there are many features relative to samples, or when features are noisy or collinear.
- L2 (ridge): minimize loss + λ‖w‖². It shrinks weights and stabilizes the fit under collinearity. It is equivalent to a Gaussian prior on the weights.
- L1 (lasso): penalty λ‖w‖₁. It sets some weights exactly to zero, giving feature selection. It is equivalent to a Laplace prior.
- Elastic net: a mix of both. Useful for groups of correlated features, where lasso would arbitrarily keep one.
- Fewer or better features: drop noisy or redundant ones, use PCA, and restrict polynomial or interaction expansions.
- Choose λ by cross-validation, and standardize features first, otherwise the penalty treats features unequally depending on scale.
- More data, if available.
3. Reducing overfitting in a deep network
Deep nets have far more capacity than needed, so several complementary tools are combined.
- Data: more data, augmentation (crops, flips, color jitter for images; token dropout or back-translation for text), mixup or CutMix.
- Explicit regularization: weight decay (decoupled in AdamW) and dropout, which prevents co-adaptation and behaves like an implicit ensemble.
- Early stopping on validation loss. It is cheap and very effective.
- Capacity and inductive bias: a smaller model, parameter sharing, or architectures matched to the data (convolutions for images).
- Normalization and output smoothing: batch or layer norm adds mild noise; label smoothing curbs overconfident logits.
- Transfer learning: start from pretrained weights, freeze early layers or use a small learning rate, so fewer parameters are learned from scarce data.
- Ensembling or checkpoint averaging for a final boost.
Contrast with linear models. In linear models you mostly control weight magnitude and feature count. In deep nets much of the regularization is implicit (SGD noise, early stopping, augmentation, architecture). Heavily overparameterized networks can fit the training data perfectly and still generalize (related to double descent), so the observed train-validation gap, not the raw parameter count, is the real diagnostic.
4. Transformer self-attention
Input. A sequence of n token vectors, X ∈ ℝ^(n×d).
Projections. Three learned matrices produce Q = X·W_Q, K = X·W_K, V = X·W_V.
- Query q_i: what token i is looking for.
- Key k_j: how token j advertises itself for matching.
- Value v_j: the information token j contributes if attended to.
Scores and weights.
Attention(Q, K, V) = softmax(QKᵀ / √d_k + M) · V
- q_i · k_j measures relevance of token j to token i.
- Dividing by √d_k keeps score variance roughly constant as dimension grows. Without it, large dot products push the softmax into saturation and gradients vanish.
- The softmax is applied row-wise, so each token gets non-negative weights over all positions that sum to 1.
- The output for token i is the weighted average of the value vectors.
- M is a mask: −∞ on future positions for causal decoders and on padding tokens.
Multi-head attention. Run h heads in parallel, each with its own projections of size d/h, concatenate the results, and apply an output projection W_O. Different heads can specialize in different relations (local context, syntax, coreference).
Surrounding block. Attention, then residual + LayerNorm, then a position-wise feed-forward network, then residual + LayerNorm. Many modern models use pre-norm.
Cost. O(n²·d) time and O(n²) memory for the score matrix. This motivates sparse and linear attention and FlashAttention (which reduces memory traffic, not FLOPs).
Cross-attention. Queries come from the decoder, keys and values from the encoder output.
5. Why position is needed and how to add it
Why. Self-attention is permutation-equivariant: shuffle the input tokens and the outputs shuffle identically, because scores depend only on content. Without position, "dog bites man" and "man bites dog" are the same bag of tokens. RNNs and CNNs encode order structurally; attention does not.
Approaches.
- Sinusoidal absolute encodings (original Transformer). Fixed sine and cosine values at geometrically spaced frequencies are added to the embeddings. No parameters, and it can extrapolate somewhat to longer sequences.
- Learned absolute embeddings. A trainable vector per position index, added to token embeddings. Simple and common, but limited to the maximum trained length.
- Relative position methods. Add a learned bias to the attention scores based on the offset i − j (T5-style), or use ALiBi, which adds a linear distance penalty. These generalize better to longer contexts.
- Rotary embeddings (RoPE). Rotate queries and keys by position-dependent angles so that the dot product depends on relative offset. Widely used in current LLMs.
Trade-offs. Absolute schemes are simple but tie the model to training lengths. Relative and rotary schemes extrapolate better and match the intuition that relations depend on distance.
Common mistakes
- Calling any train-validation gap "overfitting" without checking for leakage or distribution shift.
- Applying regularization to an underfitting model.
- Forgetting to standardize features before L1/L2.
- Explaining attention only by analogy and omitting the √d_k scaling, the row-wise softmax, or masking.
- Saying positional encodings are needed "because attention is slow" rather than because it is order-agnostic.