Generalization, Regularization, and Transformer Self-Attention
Medium · Machine Learning · Machine Learning Engineer · Technical Screen
Prompt
In a machine learning engineering technical screen, walk through the five foundational topics below clearly and contrast how different model families behave:
- Define overfitting and explain how you diagnose it by tracking training metrics alongside held-out validation metrics.
- What practical techniques curb overfitting when fitting a linear model?
- What practical techniques curb overfitting when training a deep neural network, and how does this toolkit differ from the linear setting?
- Describe the architecture of Transformer self-attention, including the roles of queries, keys, and values and the exact formula used to turn them into attention weights and context vectors.
- Why does a bare self-attention stack lack awareness of token order, and what are at least two distinct mechanisms for supplying positional structure?
Scope & Expectations
- Bias-variance and learning-curve diagnostics: Distinguish memorization from underfitting, explain how diverging training and validation loss curves expose high variance, and note pitfalls such as validation leakage.
- Linear vs. deep regularization trade-offs: Compare penalty- and feature-space controls in convex linear models (such as L2/L1 shrinkage and feature scaling) against optimization-, data-, and architecture-level defenses in overparameterized neural networks.
- Self-attention math and intuition: Specify matrix shapes and projections for
Q,K, andV, row-wise softmax normalization, and the statistical reason for scaling dot products by1 / sqrt(d_k). - Permutation equivariance and position representations: Show why unpositioned attention treats inputs as an unordered set and contrast at least two positional schemes (for example, sinusoidal or learned absolute embeddings versus relative biases or rotary embeddings).
Step-by-step walkthrough
Part 1: Defining overfitting and spotting it on held-out curves
A model overfits when it memorizes quirks and random noise specific to its training sample rather than learning the underlying pattern, causing its generalization (performance on unseen data drawn from the same distribution) to be much worse than its training performance. In terms of the bias-variance trade-off, an overfit model has high variance (fitting it on a slightly different training sample produces a wildly different model), whereas the opposite problem — underfitting, or high bias — happens when a model is too simple to capture the signal even on the training data.
For example, imagine 10 noisy points sampled around a straight line. A degree-1 line has a small non-zero training error and predicts new points accurately. A degree-9 polynomial has enough flexibility to pass through all 10 training points with
0training error, yet it swings violently between them and makes large errors on new points.To detect overfitting, hold out a separate validation set that is never used for parameter updates (or use
k-fold cross-validation when data is small) and track training and validation metrics side by side across epochs or model sizes:epoch train loss val loss diagnosis ----- ---------- -------- ---------------------------------------- 1 0.62 0.64 underfitting (both losses still high) 5 0.31 0.38 healthy learning (both losses falling) 10 0.18 0.35 sweet spot <- lowest validation loss 20 0.06 0.47 overfitting begins (val loss turns up) 40 0.01 0.71 severe overfitting (huge, growing gap)Three diagnostic checks confirm what is happening:
- Diverging curves: training loss keeps falling (
0.18 -> 0.01) while validation loss stalls and rises (0.35 -> 0.71). A tiny, stable gap is normal; a growing gap paired with worsening validation loss is the true signature of overfitting. - Dataset-size learning curves: plotting error against training-set size shows whether adding data helps — if validation error is still trending down toward a low training error, the model is variance-limited and more data will narrow the gap.
- Leakage check: if validation metrics look suspiciously good while real-world tests fail, check for data leakage (accidental overlap of duplicate records, user sessions, or future information between training and validation splits), which masks overfitting.
- Diverging curves: training loss keeps falling (
Part 2: Regularization and feature control in linear models
A linear model overfits when the number of features
pis large relative to the number of training examplesn(whenp >= n, ordinary least squares (OLS) — choosing weights to minimize summed squared errors alone — can usually fit noisy targets with zero training error), or when engineered polynomial/interaction features suffer from collinearity (two or more features carrying nearly duplicate information, so huge positive and negative weights cancel on training data and blow up on new data).Key levers for curbing variance in linear models:
- Penalize large weights (regularization):
- Ridge (L2 regularization): minimizes
sum((y_i - X_i w)^2) + lambda * sum(w_j^2), with closed-form solutionw = (X^T X + lambda * I)^(-1) X^T y. It shrinks weights smoothly toward0and stabilizes collinear features. - Lasso (L1 regularization): adds
lambda * sum(|w_j|). Because absolute value has a sharp corner at0, Lasso drives weak weights exactly to0, performing automatic feature selection. - Elastic Net: combines L1 and L2 penalties, keeping correlated feature groups stable while still zeroing irrelevant features.
- Best practices: standardize every feature to zero mean and unit variance first (otherwise a feature measured in millimeters gets penalized 1,000x differently than one in meters), never penalize the intercept/bias term, and tune
lambdavia cross-validation.
- Ridge (L2 regularization): minimizes
- Simplify the feature space: drop low-signal interaction/polynomial terms, use domain-driven feature selection, or project features onto top directions with PCA (principal component analysis, which keeps only the highest-variance linear combinations of inputs).
- Collect more training examples: coefficient variance in linear models shrinks roughly in proportion to
1 / n.
Worked numeric example for 1D centered Ridge (
sum(x^2) = 10,sum(x * y) = 20, no intercept):OLS (lambda = 0): w = sum(x * y) / sum(x^2) = 20 / 10 = 2.0 Ridge (lambda = 10): w = sum(x * y) / (sum(x^2) + lambda) = 20 / (10 + 10) = 1.0In general, along any principal direction of
XwhereX^T Xhas spread (eigenvalue)d^2, Ridge multiplies the OLS weight byd^2 / (d^2 + lambda). Well-supported high-spread directions (d^2 >> lambda) barely change, whereas noisy near-collinear directions (d^2 << lambda) are shrunk strongly toward0.- Penalize large weights (regularization):
Part 3: Regularizing high-capacity deep neural networks
Comparing the two modeling settings highlights why the toolkit expands:
Setting Optimization & capacity Primary anti-overfitting levers -------------- -------------------------------------- ---------------------------------------------- Linear model Convex loss; capacity = feature count L1/L2 weight penalty, fewer features, more rows Deep network Non-convex SGD; millions of parameters Data augmentation, early stopping, weight decay, often exceed training sample count dropout, architecture / transfer learningIn a deep neural network trained by stochastic gradient descent (SGD) (updating weights using noisy mini-batches), we control both what the network can represent and how training explores parameter space:
- More data and data augmentation: apply label-preserving transforms (random crops/flips/color jitter for vision, time-masking for audio, token dropout or back-translation for text) to teach invariances directly.
- Early stopping: monitor validation loss every epoch, keep a checkpoint at the best score (epoch 10 in our table), and stop once validation loss fails to improve for
k"patience" epochs. - Weight decay: penalize squared weights during gradient updates; with adaptive optimizers like Adam, use AdamW (decoupled weight decay, which shrinks weights directly rather than mixing the penalty into adaptive gradient moments).
- Inverted dropout: during each training step, randomly zero each hidden activation with probability
pand scale kept activations by1 / (1 - p)so their expected magnitude stays constant; at inference time, keep all units active with no scaling:
activations: [2, 4, 6, 8], drop rate p = 0.5 -> scale = 1 / (1 - 0.5) = 2.0 train step (mask [1, 0, 1, 0]): [2*1*2, 4*0*2, 6*1*2, 8*0*2] = [4, 0, 12, 0] inference (no mask, no scale): [2, 4, 6, 8] (same expected sum: 16 vs 20 in expectation)- Better inductive bias and transfer learning: pick an architecture whose inductive bias (built-in structural assumptions about the input, such as translation equivariance in convolutions) matches the domain, or fine-tune a pretrained foundation model so few parameters are learned from scratch on a small dataset.
- Output/sample regularizers: label smoothing (replacing hard
0/1targets withepsilon / (C - 1)and1 - epsilonso logits do not grow unboundedly), mixup, stochastic depth, or model ensembling.
Part 4: Scaled dot-product self-attention (Q, K, V, and softmax)
Self-attention lets every token in a sequence gather context directly from every other token in one hop. Given
ninput token embeddings stacked intoXof shape(n, d_model), three learned weight matrices project each token into three roles — much like searching a reference library:- Query (
Q = X W_Q, shape(n, d_k)): what tokeniis currently looking for. - Key (
K = X W_K, shape(n, d_k)): the label advertising what tokenjcontains so queries can match against it. - Value (
V = X W_V, shape(n, d_v)): the actual content vector tokenjcontributes once matched.
X (n, d_model) |-- x W_Q --> Q (n, d_k) --\ |-- x W_K --> K (n, d_k) ---> scores = (Q K^T) / sqrt(d_k) shape: (n, n) | | | weights = row_softmax(scores) shape: (n, n), each row sums to 1 |-- x W_V --> V (n, d_v) ----------> output = weights V shape: (n, d_v)Key mechanics inside and around attention:
- Row-wise softmax: softmax converts a row of raw scores
sinto non-negative probabilitiesexp(s_j) / sum_m exp(s_m)that sum to1, so output rowiis a weighted average of allnvalue vectors. - Why divide by
sqrt(d_k): if entries ofqandkare independent with mean0and variance1, each productq_m * k_mhas variance1, so their sumq . khas varianced_k(standard deviationsqrt(d_k)). For larged_k(say64or128), unscaled dot products grow large, pushing softmax toward[1, 0, ..., 0]where gradients nearly vanish. Dividing bysqrt(d_k)restores unit variance (1). - Causal masking (decoders): setting
score[i][j] = -infinityfor future positionsj > ibefore softmax turns their weights intoexp(-infinity) = 0, preventing tokens from peeking ahead. - Multi-head attention & Transformer block: running
hsmaller heads (d_k = d_model / h) in parallel lets different heads focus on different relationships (syntax, coreference, nearby words) before concatenating and projecting viaW_O. Each attention sublayer is wrapped with a residual connection (adding the sublayer's inputxback to its outputx + sublayer(x)so gradients flow cleanly) and layer normalization (normalizing each token vector across itsd_modelfeatures), followed by a per-token feed-forward network.
- Query (
Worked numeric walkthrough of self-attention
Take
n = 3tokens of dimensiond_k = 2with identity projections (W_Q = W_K = W_V = I), soQ = K = V = X = [[1, 0], [0, 1], [1, 1]]:1) Dot products Q K^T: 2) Scale by 1 / sqrt(2) = 0.7071: [[1, 0, 1], [[0.707, 0.000, 0.707], [0, 1, 1], [0.000, 0.707, 0.707], [1, 1, 2]] [0.707, 0.707, 1.414]] 3) Row 1 softmax: [exp(0.707), exp(0), exp(0.707)] = [2.028, 1.000, 2.028], sum = 5.056 weights[0] = [2.028, 1.000, 2.028] / 5.056 = [0.401, 0.198, 0.401] 4) Output row 1: 0.401 * [1, 0] + 0.198 * [0, 1] + 0.401 * [1, 1] = [0.802, 0.599]Token 1 (
[1, 0]) splits most of its1.0attention budget equally (0.401each) between itself and token 3 ([1, 1]), the two keys sharing its active first coordinate:import numpy as np def softmax_rows(scores: np.ndarray) -> np.ndarray: # Subtract row max before exp() to prevent floating-point overflow shifted = scores - scores.max(axis=1, keepdims=True) exp_scores = np.exp(shifted) return exp_scores / exp_scores.sum(axis=1, keepdims=True) def scaled_dot_product_attention(Q: np.ndarray, K: np.ndarray, V: np.ndarray): d_k = Q.shape[1] scores = (Q @ K.T) / np.sqrt(d_k) weights = softmax_rows(scores) return weights @ V, weights X = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]) output, weights = scaled_dot_product_attention(X, X, X) assert np.allclose(weights[0], [0.4011, 0.1978, 0.4011], atol=1e-3) assert np.allclose(output[0], [0.8022, 0.5989], atol=1e-3)Part 5: Permutation equivariance and why sequence order disappears
Unlike recurrent networks (which step token by token) or convolutions (which slide local windows), pure self-attention has no built-in sense of order. It is permutation-equivariant (if you reorder the input rows, the output vectors stay completely identical and simply reorder in the exact same way), and the per-token feed-forward layers and layer norm also act on each position independently:
Input A: ["dog", "bites", "man"] --> ["dog" -> v_dog, "bites" -> v_bites, "man" -> v_man] Input B: ["man", "bites", "dog"] --> ["man" -> v_man, "bites" -> v_bites, "dog" -> v_dog] (exact same vectors per word — meaning of who bit whom is lost!)perm = [2, 0, 1] permuted_output, _ = scaled_dot_product_attention(X[perm], X[perm], X[perm]) assert np.allclose(permuted_output, output[perm])Because order changes meaning in language, time series, and user event logs, positional information must be injected explicitly.
Ways to inject positional information (absolute vs relative)
Positional methods fall into two main families — absolute encodings added to input embeddings vs relative signals injected inside attention scores:
- Sinusoidal absolute encodings (original Transformer): add a fixed deterministic vector
PE(pos)of dimensiond_modelto each token embedding using geometric frequencies:PE(pos, 2m) = sin(pos / 10000^(2m / d_model))andPE(pos, 2m + 1) = cos(pos / 10000^(2m / d_model)). It requires zero learned parameters, and becausesin(a + b)andcos(a + b)expand linearly insin(a), cos(a), any fixed offsetPE(pos + k)is a linear rotation ofPE(pos). Ford_model = 4,PE(0) = [0, 1, 0, 1]andPE(1) = [0.8415, 0.5403, 0.0100, 1.0000]. - Learned absolute position embeddings (BERT, GPT-2): learn a lookup table of shape
(max_len, d_model)and add rowposto tokenpos. Flexible and simple, but undefined for sequence lengths exceedingmax_lenat test time. - Relative attention biases (T5, ALiBi): add an offset-dependent term directly to
score[i][j]before softmax. T5 learns scalar biases per distance bucket; ALiBi subtracts a fixed linear distance penaltym_h * |i - j|(with head-specific slopem_h), enabling strong length extrapolation. - Rotary Position Embedding — RoPE (LLaMA and modern LLMs): group
qandkcoordinates into 2D pairs and rotate tokenposby anglepos * theta_m. Because rotating both vectors shifts their angle difference to(pos_q - pos_k) * theta_m, the dot productq . kdepends purely on relative distancepos_q - pos_kwhile preserving vector norms:
def sinusoidal_pe(num_positions: int, d_model: int) -> np.ndarray: pe = np.zeros((num_positions, d_model)) for pos in range(num_positions): for even_dim in range(0, d_model, 2): angle = pos / (10000 ** (even_dim / d_model)) pe[pos, even_dim] = np.sin(angle) pe[pos, even_dim + 1] = np.cos(angle) return pe def rope_rotate_2d(vec: np.ndarray, pos: int, theta: float = 0.5) -> np.ndarray: angle = pos * theta cos_a, sin_a = np.cos(angle), np.sin(angle) return np.array([cos_a * vec[0] - sin_a * vec[1], sin_a * vec[0] + cos_a * vec[1]]) q_vec = np.array([1.0, 2.0]) k_vec = np.array([0.5, -1.0]) # Relative offset is 2 in both pairs (3 - 1 == 7 - 5), so dot products match identically: assert np.isclose(rope_rotate_2d(q_vec, 3) @ rope_rotate_2d(k_vec, 1), rope_rotate_2d(q_vec, 7) @ rope_rotate_2d(k_vec, 5))- Sinusoidal absolute encodings (original Transformer): add a fixed deterministic vector
Intuition & how it works
Overfitting and Transformer self-attention address two core questions in machine learning: how a model generalizes beyond its training examples and how a sequence model routes context between tokens. Imagine overfitting as a student who memorizes the exact answer key to ten practice problems word for word instead of learning the underlying math — they score 100% on the practice sheet and fail the real exam. Self-attention, meanwhile, works like a room of researchers where every word broadcasts a specific question (Query), wears a descriptive name badge (Key), and shares a summary note (Value) in proportion to how closely another word's question matches its badge.
Naive choices fail quickly in both settings. Judging a model by training loss alone rewards pure memorization and hides worsening errors on new users, while applying the same single penalty to linear models and deep networks ignores how differently they optimize. Likewise, computing raw dot products in self-attention without dividing by sqrt(d_k) pushes probabilities to 0 or 1 where gradients vanish, and omitting positional signals treats a sentence as an unordered bag of words where "dog bites man" and "man bites dog" produce the exact same per-word vectors.
A tiny trace shows each mechanism in action: if training loss drops across epochs 1 -> 10 -> 40 (0.62 -> 0.18 -> 0.01) while held-out validation loss curves 0.64 -> 0.35 -> 0.71, stopping at epoch 10 catches the model right before memorization takes over. Inside attention, when three 2D tokens [[1, 0], [0, 1], [1, 1]] attend to one another (d_k = 2), token 1's scaled scores [0.707, 0, 0.707] turn via row-wise softmax into weights [0.401, 0.198, 0.401], blending the three values into [0.802, 0.599].
Key points
- Overfitting diagnosis: Overfitting (high variance — high sensitivity to noise in the specific training sample) appears when training error keeps improving while held-out validation error stalls or worsens, widening the train-validation gap; underfitting (high bias — an overly rigid model) shows high error on both splits.
- Linear-model regularization: Ridge (L2) adds
lambda * sum(w_j^2)to shrink noisy and collinear (nearly duplicate) feature directions smoothly byd^2 / (d^2 + lambda), Lasso (L1) addslambda * sum(|w_j|)to zero out weak features completely, and Elastic Net blends both; always standardize features first and leave the intercept unpenalized. - Deep-network regularization: Because deep networks optimize non-convex losses over millions of parameters, combine data-level defenses (data augmentation, more data), optimization defenses (early stopping, AdamW decoupled weight decay), stochastic noise (inverted dropout, scaling survivors by
1 / (1 - p)during training only), and structural priors (transfer learning, inductive bias, label smoothing). - Scaled dot-product self-attention: Computes
softmax((Q K^T) / sqrt(d_k)) Vrow by row, where softmax turns each query'snkey-match scores into a probability distribution summing to1, and1 / sqrt(d_k)keeps dot-product variance near1so gradients stay healthy. - Positional information: Because pure attention is permutation-equivariant (reordering input tokens merely reorders identical output vectors), models inject order either absolutely at the input (fixed sinusoidal waves or learned position tables) or relatively inside attention (
i - jscore biases like T5/ALiBi, or 2D query/key rotations in RoPE).
Common mistakes
- Labeling any non-zero train/validation gap as overfitting: Models almost always score slightly better on data they trained on; overfitting is specifically when validation performance degrades while training loss keeps dropping.
- Overfitting the validation set itself: Running hundreds of hyperparameter experiments against one validation split leaks information into your choices; always hold out a final untouched test set (or use nested cross-validation) to report unbiased generalization.
- Penalizing unstandardized features or the intercept in Ridge/Lasso: Without zero-mean, unit-variance scaling, changing a feature's unit from kilometers to meters arbitrarily shrinks its weight by
1,000and lets it escape the L1/L2 penalty. - Leaving dropout active at inference or forgetting
1 / (1 - p)scaling: Failing to switch to evaluation mode (model.eval()in PyTorch) injects random noise into production predictions and shifts activation magnitudes if scaling is mismatched. - Applying softmax across the wrong axis or skipping
sqrt(d_k): Attention softmax runs across keys (columns) for each query row independently so every row sums to1, not across the entiren x nmatrix; omittingsqrt(d_k)saturates softmax whend_kis large. - Confusing addition with concatenation for positional encodings: Sinusoidal and learned absolute positional encodings have the same dimension
d_modelas token embeddings and are added element-wise, not concatenated, and learned absolute tables cannot extrapolate past their trainedmax_len.
Follow-up questions
- What are the compute and memory costs of self-attention over sequence length n, and how do long-context Transformers scale them? Computing the
n x nscore and weight matrices across sequence lengthncostsO(n^2 * d_model)time andO(n^2)memory per head, overtaking theO(n * d_model^2)linear projections oncen > d_model. FlashAttention computes exact softmax attention in SRAM tiles without materializing the fulln x nmatrix in GPU memory, cutting attention memory fromO(n^2)toO(n)while keeping exact outputs. To reduce compute as well, models use sliding-window/sparse attention during prefill and a KV cache (storing past tokens' Key and Value vectors during autoregressive decoding so each new token costsO(n * d_model)instead ofO(n^2 * d_model)). - Why do Transformers divide d_model across multiple smaller heads instead of running one full-width attention head? A single attention head produces just one set of softmax weights per token, forcing it to average competing relationships into one blurry blend. Splitting into
hheads of widthd_k = d_model / hkeeps total FLOPs and parameter count nearly identical to one large head, while allowing head 1 to attend sharply to an adjacent verb, head 2 to resolve a distant pronoun, and head 3 to track punctuation beforeW_Ocombines their findings. - If both training and validation metrics look strong offline, why might live production performance still degrade? Offline validation measures generalization only within the training distribution, so strong validation paired with poor production performance usually indicates distribution shift (new user behavior, seasonal trends, or an upstream logging bug) or temporal data leakage (for example, random row splitting that placed future events in training). Diagnose this by comparing feature distributions between validation and live traffic and switching to a time-based validation split that mirrors deployment.
Follow-up questions
- What are the compute and memory costs of self-attention over sequence length n, and how do long-context Transformers scale them?
- Why do Transformers divide d_model across multiple smaller heads instead of running one full-width attention head?
- If both training and validation metrics look strong offline, why might live production performance still degrade?
Similar questions
- Contrasting Batch and Layer Normalization
- Convolutional Networks vs. Transformer Architectures
- Training Stability, Gradient Optimizers, and Weight Penalties in Deep Networks
- CLIP Dual-Encoders, Contrastive Objectives, and Vector Search Limits
- Bias-Variance, Normalization Axes, and Vanishing Gradients
- Imbalanced Training, Calibration, Optimizers, and Transformer Mechanics
More Snapchat interview questions
- Hierarchy Tree Rendering and Two-Hop Reporting Pairs Hard
- Ordinary Least Squares With Cloned Observations Medium
- Mean Front-to-Rear Camera Transitions per Session Medium Pro
- Contrasting Batch and Layer Normalization Hard Pro
- Banner CTR and Session Engagement Analytics Medium Pro
- Count Enclosed Land Islands Medium Pro
- Daily Users Starting With App Launch Medium Pro
- API-Polled News Feed Aggregator Hard Pro
- Time-Series Metrics Monitoring and Alerting Platform Medium Pro
- Vertical Short-Video Feed Vending Backend Medium Pro