ML Fundamentals: Generalization, Contrastive Embeddings, Attention
Machine LearningModel answerLast updated
Explain how to diagnose and curb overfitting, how contrastive pretraining and its loss shape embeddings, and how a transformer block works.
You are in a technical screen for an applied scientist position, and the interviewer works through four theory areas. Answer each one clearly, with intuition and, where it helps, a short formula.
Part 1: Generalization
- Define overfitting and underfitting in the context of supervised learning.
- Describe how you would spot overfitting in a real project (for example with training and validation curves, or with cross-validation).
- Name at least three or four distinct ways to reduce overfitting and explain why each one works.
Part 2: Contrastive representation learning
- Describe the core idea of learning representations contrastively.
- What are positive and negative pairs, and how are they built in practice for images and for text?
- Which downstream tasks tend to benefit from contrastive pretraining?
Part 3: The contrastive objective
- Describe a widely used contrastive loss, such as InfoNCE or NT-Xent.
- Explain intuitively why it draws positive pairs together and pushes negatives apart. A simple formula is welcome, but intuition matters more.
Part 4: Transformers
- Give a high-level description of a transformer architecture for language or vision.
- Explain what self-attention does and how it differs conceptually from recurrent and convolutional models.
- Explain what positional encoding is and why the model needs it.
- List the usual components of a transformer block.
Hints
Hint 1
For Part 1, tie everything to the bias-variance trade-off: each remedy should either shrink model capacity, add information (data), or average out variance.
Hint 2
For Parts 2 and 3, think of the loss as a softmax classification: given an anchor, pick its true partner out of a pool of candidates. Ask what would happen without negatives, and what temperature does.
Hint 3
For Part 4, start from Q, K, V and the scaled dot-product formula, then ask what information is lost if tokens are processed as an unordered set.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Generalization
Definitions
- Overfitting: the model captures noise and quirks of the training set. Training error is low but error on unseen data is much higher (high variance).
- Underfitting: the model is too simple or undertrained to capture the signal. Training and validation error are both high (high bias).
The goal is low generalization error, not low training error.
Detection
- Loss curves over epochs: overfitting looks like training loss still decreasing while validation loss flattens, then rises. Underfitting looks like both curves high and close together.
- Learning curves vs. data size: if the train-validation gap shrinks as data grows, the model is variance-limited and more data will help.
- K-fold cross-validation: a big gap between training and held-out scores, or high spread across folds, signals overfitting.
- Sanity checks: near-perfect training accuracy on noisy labels means memorization. Also check for leakage between splits, which hides overfitting.
Remedies and why they work
| Method | Intuition |
|---|---|
| More data / augmentation | Harder to memorize; augmentation bakes in invariances (crops, flips, paraphrases). |
| L2 / L1 (weight decay) | Penalizes large weights, favoring smoother functions. L1 adds sparsity. |
| Dropout | Prevents co-adaptation of units; approximates averaging many subnetworks. |
| Early stopping | Stops at best validation loss, before the model fits noise. |
| Smaller model / fewer features | Directly lowers capacity and variance. |
| Ensembling / bagging | Averages out uncorrelated errors. |
A common mistake is to tune hyperparameters repeatedly against the test set, which is just overfitting to the evaluation data.
Part 2: Contrastive learning
Idea. Train an encoder f(x) → z without labels so that two views of the same underlying item land close together, while views of different items land far apart. The supervision comes from data structure, so it is self-supervised.
Pairs
- Positives
- Vision: two random augmentations of one image (crop, color jitter, blur, flip).
- Text: the same sentence encoded twice with different dropout masks, a paraphrase, or a query with its relevant passage.
- Multimodal: an image with its caption.
- Negatives: usually other items in the same batch (in-batch negatives) or entries in a memory queue. Hard negatives (similar but wrong, such as a lexically matching non-relevant passage) sharpen the representation.
The choice of augmentation defines what the model learns to be invariant to. Color jitter teaches color invariance; if color matters for your task, that is a harmful choice.
Downstream uses: few-label classification (linear probe or fine-tune), semantic search and retrieval, deduplication, clustering, recommendation, zero-shot and cross-modal retrieval, and transfer to detection or segmentation.
Part 3: InfoNCE / NT-Xent
Take N examples, create two views each (2N embeddings), L2-normalize, and use cosine similarity. For anchor i with positive j:
$$ \mathcal{L}i = -\log \frac{\exp(\mathrm{sim}(z_i,z_j)/\tau)}{\sum{k\ne i}\exp(\mathrm{sim}(z_i,z_k)/\tau)} $$
Average over all anchors.
Intuition
- It is a (2N-1)-way softmax classification: pick the positive among all candidates.
- Numerator pulls: reducing the loss increases sim(z_i, z_j).
- Denominator pushes: every negative's similarity appears there, so its gradient pushes it down, weighted by its softmax probability. The most similar (hardest) negatives get the largest push.
- Temperature τ (typically 0.05 to 0.5): small τ focuses on hard negatives but can be unstable and over-penalize false negatives; large τ treats negatives more uniformly.
- More negatives give a tighter bound, since InfoNCE lower-bounds mutual information roughly as log(N) minus the loss. This is why SimCLR uses large batches and MoCo uses a queue.
- Collapse: without negatives, mapping everything to one point is a trivial solution. Non-contrastive methods (BYOL, SimSiam) avoid it with a predictor and stop-gradient instead.
Part 4: Transformers
Architecture
- Tokenize (subwords for text, e.g. 16x16 patches for ViT) and embed into d dimensions.
- Add positional information.
- Pass through L identical blocks.
- Apply a task head (classifier on a [CLS] token, or a vocabulary softmax for language modeling).
Variants: encoder-only (BERT, ViT; bidirectional), decoder-only (GPT; causal mask), encoder-decoder (T5; decoder cross-attends to the encoder).
Self-attention. Each token produces Q = XW_Q, K = XW_K, V = XW_V, and
$$ \mathrm{Attn}(Q,K,V)=\mathrm{softmax}!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V $$
Each token forms a weighted mix of all other tokens' values, with weights based on query-key similarity. The scaling by sqrt(d_k) keeps the softmax from saturating.
Versus RNNs and CNNs
- RNNs pass information step by step, so long-range dependencies need many steps and training is sequential.
- CNNs see only a local window per layer and need depth to grow the receptive field.
- Self-attention connects any two positions in one layer and parallelizes across the sequence. The cost is O(n^2) time and memory in sequence length.
Positional encoding. Attention is permutation-equivariant: shuffle the tokens and the outputs are shuffled the same way, so word order would be invisible. Position information is added via sinusoidal encodings, learned embeddings, or relative schemes such as RoPE and ALiBi.
Block components
- Multi-head attention (several subspaces attended to in parallel, then concatenated and projected).
- Position-wise feed-forward network (typically 4x expansion with a nonlinearity), which adds per-token capacity.
- Residual connections, which ease gradient flow in deep stacks.
- Layer normalization (pre-norm is common for stability).
- Optional dropout, and a causal mask in decoders.
Common mistakes: forgetting why positions are needed, claiming attention is O(n), confusing the roles of Q, K and V, and describing contrastive loss without mentioning negatives or temperature.