Generalization, Contrastive Representation Learning, and Transformers
Easy · Machine Learning · Software Engineer · Technical Screen
Prompt
During a machine learning technical screen, the interviewer asks you to walk through four foundational deep learning topics:
-
Generalization in Supervised Models
- Contrast underfitting with overfitting when training a predictive model on labeled examples.
- Explain how engineers diagnose overfitting on real datasets (such as inspecting loss trajectories across epochs or running cross-validation splits).
- Present at least three or four distinct mitigation strategies and explain why each one improves out-of-sample performance.
-
Self-Supervised Contrastive Pretraining
- Summarize the core objective of contrastive representation learning.
- Define anchor, positive, and negative examples, and give concrete examples of how pairs are assembled for image or text encoders.
- Identify practical downstream applications where contrastively pretrained embeddings shine.
-
Contrastive Objective Mechanics
- Walk through a standard softmax-based contrastive objective such as InfoNCE or NT-Xent (an equation is welcome, provided you emphasize the underlying mechanics).
- Explain why minimizing this objective draws matching views together in embedding space while repelling unrelated candidates.
-
Transformer Foundations
- Sketch the end-to-end layout of a Transformer encoder or decoder applied to text tokens or image patches.
- Compare how self-attention routes context across a sequence relative to recurrent networks and convolutions.
- Explain why explicit position representations must be supplied and how they are injected.
- Name the core sub-layers inside a standard Transformer block and state each component's job.
Scope & Expectations
- Concrete diagnostics and intuition over buzzwords: Pair crisp definitions of bias, variance, validation curves, and regularization methods with plain-English explanations of what each mechanism restricts or encourages.
- Practical pair construction and loss geometry: Show how domain-specific augmentations or multimodal pairings create positive and negative examples without manual class labels, and clarify the roles of embedding normalization and temperature scaling in InfoNCE.
- Architectural clarity and trade-offs: Trace how token embeddings, positional signals, multi-head self-attention, position-wise feed-forward layers, residual paths, and layer normalization fit together, including computational scaling versus RNNs and CNNs.
Step-by-step walkthrough
Overfitting and underfitting: memorizing vs. oversimplifying
In supervised learning (training a model on
(input, target)pairs so it can predict targets on unseen inputs), lowering error on the training set is only a proxy. The real goal is generalization: low error on new data drawn from the same underlying distribution.- Underfitting (high bias): The model is too rigid or simple to express the true relationship in the data. Both training error and validation error stay high. (Bias measures error caused by overly restrictive model assumptions, such as fitting a straight line to a wave.)
- Overfitting (high variance): The model has enough flexibility to memorize random noise and quirks in the finite training sample, so training error becomes tiny while validation error shoots up. (Variance measures how wildly the learned curve changes if you retrain on a fresh sample from the same source.)
See all three regimes on
12noisy training points generated fromy = sin(3x) + noise, where the random noise has standard deviation0.2. Because irreducibly random noise has variance0.2^2 = 0.04, no model can beat a mean squared error (MSE)—the average of(prediction - target)^2—of about0.04on fresh data:import numpy as np rng = np.random.default_rng(1) def sample_curve(n_points): x = rng.uniform(-1, 1, n_points) y = np.sin(3 * x) + rng.normal(0, 0.2, n_points) return x, y x_train, y_train = sample_curve(12) x_val, y_val = sample_curve(500) for degree in [1, 3, 9]: coefs = np.polyfit(x_train, y_train, degree) train_mse = np.mean((np.polyval(coefs, x_train) - y_train) ** 2) val_mse = np.mean((np.polyval(coefs, x_val) - y_val) ** 2) print(degree, round(float(train_mse), 3), round(float(val_mse), 3))Degree Parameters Train MSE Val MSE Diagnosis ------ ---------- --------- ------- ------------------------------------------------ 1 2 0.169 0.203 Underfit: straight line misses the sine wave 3 4 0.018 0.051 Good fit: close to the 0.04 irreducible floor 9 10 0.004 1.354 Overfit: 10 weights bend through 12 noisy points and swing wildly in the gaps (26x worse val MSE)Spotting overfitting on real datasets
Because overfitting means memorizing training examples instead of learning transferable structure, you detect it by comparing training performance against held-out data the optimizer never saw:
Loss ^ | \ Validation loss (falls, bottoms out at epoch E*, then climbs!) | \ /-------- | \____*_____/ | : \ | : \___________ Training loss (keeps falling toward 0) +--------+-----------------> Training epochs E* (memorization overtakes generalization)- Training vs. validation curves over epochs (an epoch is one full pass through the training set): while both curves drop, the model is learning shared signal; once validation loss turns upward while training loss keeps falling, the model is memorizing training noise.
- Learning curves over dataset size: train on
10%,25%,50%, and100%of the training rows. Overfitting shows up as low training error and a wide validation gap that narrows as you add data; underfitting shows two high, nearly touching curves that more rows alone cannot fix. - k-fold cross-validation: split the data into
kequal folds, train onk - 1folds, validate on the held-out fold, and rotatektimes. If training scores beat the mean fold score by a wide margin—or fold scores swing dramatically—variance is high. - Statistical sanity check and look-alikes: check standard error (how much a metric wobbles purely from finite validation size: at
80%accuracy onn = 200items,sqrt(0.8 * 0.2 / 200) = 0.028, so a2%gap can be luck while a15%gap is real). Also rule out data leakage (target hints sneaking into training features), broken splits (putting the same user or future timestamps on both sides), and distribution shift (production inputs differing systematically from training data).
Practical remedies for overfitting and why they work
Every anti-overfitting tool either restricts how sharply the model can bend or forces patterns to work across variations:
- More training data or data augmentation: Random noise cancels out across more examples, while data augmentation (label-preserving edits like random crops, horizontal flips, or color jitter on images, and synonym replacement or back-translation on text) teaches the model which surface changes do not alter the answer.
- L2 / L1 regularization and weight decay: Adding
lambda * sum(w_j^2)(L2 / ridge) orlambda * sum(|w_j|)(L1 / lasso) to the training loss penalizes huge weights. Wild oscillations between nearby inputs require large canceling coefficients; shrinking weights forces smoother predictions, andL1pushes unneeded weights all the way to0. Applying anL2penalty to our degree-9 polynomial (with standardized powersx^1 .. x^9and unpenalized intercept) tames the explosion:
text lambda Train MSE Val MSE Weight norm ||w||_2 Effect ------ --------- ------- ------------------- ------------------------------ 0.00 0.004 1.354 64.6 Unregularized overfit 0.01 0.008 0.077 2.8 Wild swings suppressed 0.10 0.023 0.051 1.5 Matches degree-3 validation MSE 1.00 0.065 0.096 0.8 Penalty too heavy -> underfitsIn deep learning with adaptive optimizers like Adam, decoupled **weight decay** (`AdamW`, shrinking weights directly each step) works better than adding `||w||^2` to the gradient because Adam rescales gradients per parameter.- Early stopping: Save checkpoints and stop when validation loss stops improving (
E*in the curve above). Because neural network weights start near zero and grow gradually, stopping early bounds how far parameters travel into noise-memorizing territory. - Dropout: On each training forward pass, randomly set each hidden activation to
0with probabilitypand multiply kept activations by1 / (1 - p)so expected sums stay unchanged; at inference time, turn dropout off. Because no neuron can count on a specific neighbor showing up, layers learn redundant, independently useful features. - Capacity reduction and ensembling: Using fewer parameters (shallower trees, smaller hidden width) directly removes excess flexibility, while ensembling (averaging models trained on different bootstrap samples—random draws with replacement—as in Random Forests) cancels out independent high-variance mistakes. Always tune regularization hyperparameters on validation data, never the test set.
Contrastive learning: learning representations by comparison
Labels are expensive, while raw images, articles, and audio are abundant. Contrastive learning is a self-supervised method for representation learning (training an encoder
f(x)to map raw inputs into fixed-length numeric vectors called embeddings). Without class labels, it trainsfon a simple comparison game: pull embeddings of semantically matching views close together, and push unrelated views apart.Same dog photo ---> random crop + flip ---> f(.) ---> z_i \ +-- Positive pair (pull close) Same dog photo ---> grayscale + blur ---> f(.) ---> z_i+ / | Car photo ---> random crop ---> f(.) ---> z_k +-- Negative pair (push apart)- Positive pair
(x_i, x_i+): two inputs that represent the same underlying concept and should land near each other on the unit sphere. - Negative pair
(x_i, x_k): two unrelated inputs (typically the other items in the mini-batch) whose vectors should stay separated so the encoder cannot cheat by mapping everything to one point.
How teams construct pairs in practice:
- Vision (SimCLR / MoCo): Two random augmentations of the same image form a positive pair; other images in the batch (SimCLR) or a rolling queue encoded by a slow-moving momentum encoder (MoCo) serve as negatives.
- Vision-language (CLIP): An
(image, matching caption)pair is positive; pairing that image with the otherB - 1captions in a batch ofBpairs givesB - 1negatives. - Text and retrieval (SimCSE / Dense Passage Retrieval): Passing the same sentence twice through a Transformer with two different random dropout masks produces a clean unsupervised positive pair (SimCSE). In search,
(query, relevant passage)is positive, and look-alike passages that do not answer the query act as hard negatives (tricky distractors that sharpen boundaries).
Downstream tasks that benefit: Few-shot classification (fitting a lightweight linear probe—a single linear classifier on frozen embeddings—or fine-tuning with few labels), semantic search and retrieval-augmented generation (nearest-neighbor lookup), zero-shot image classification (comparing an image vector against
"a photo of a <class>"text vectors), deduplication, clustering, and two-tower recommendation.- Positive pair
InfoNCE / NT-Xent contrastive loss and why temperature matters
First L2-normalize every embedding (
z = v / ||v||_2) so its length is1. Then the dot productsim(z_a, z_b) = z_a . z_bequals their cosine similarity (ranging from-1for opposite directions,0for perpendicular, to+1for identical direction). Given an anchorz_i, one positivez_i+, andK - 1negatives (Kcandidates total), InfoNCE divides each similarity by a temperaturetau > 0to form logits (raw scores) and applies softmax (exponentiating scores and dividing by their sum so probabilities add to1):L_i = -log( exp(sim(z_i, z_i+) / tau) / [ exp(sim(z_i, z_i+) / tau) + sum_{neg k} exp(sim(z_i, z_k) / tau) ] )In SimCLR's NT-Xent (Normalized Temperature-scaled Cross-Entropy) setup, a batch of
Bimages produces2Baugmented views, so each anchor compares1positive against2B - 2negatives (K = 2B - 1candidates). Intuitively, InfoNCE is just multi-class cross-entropy for aK-way multiple-choice quiz: "Out of theseKcandidates, pick the one true partnerz_i+."Trace one anchor whose cosine similarity is
0.8with its positive and[0.5, 0.3, -0.1]with three negatives (K = 4):import numpy as np def info_nce(similarities, tau): """similarities[0] is the positive pair; similarities[1:] are negatives.""" logits = np.array(similarities, dtype=float) / tau logits = logits - logits.max() # shift max to 0 so exp() cannot overflow exp_logits = np.exp(logits) probs = exp_logits / exp_logits.sum() return float(-np.log(probs[0])), probs for tau in [1.0, 0.1]: loss, probs = info_nce([0.8, 0.5, 0.3, -0.1], tau) neg_pushes = probs[1:] / tau print(tau, round(loss, 3), np.round(probs, 3), np.round(neg_pushes, 3))tau Softmax probs [pos, neg1, neg2, neg3] Loss Push on [neg1, neg2, neg3] --- ------------------------------------- ----- -------------------------- 1.0 [0.363, 0.269, 0.220, 0.148] 1.013 [0.269, 0.220, 0.148] 0.1 [0.946, 0.047, 0.006, 0.000] 0.055 [0.471, 0.064, 0.001]Looking at the gradient (the derivative telling gradient descent how strongly to move each similarity) explains why InfoNCE learns sharp representations:
dL_i / d sim(z_i, z_i+) = (p_pos - 1) / tau <= 0 -> increases sim(z_i, z_i+) dL_i / d sim(z_i, z_k) = p_k / tau >= 0 -> decreases sim(z_i, z_k)- Automatic hard-negative mining: Negative
kis pushed away in direct proportion to its softmax probabilityp_k. Attau = 0.1, the confusable0.5negative gets a push of0.471, while the easy-0.1negative gets0.001—training automatically focuses on mistakes! - Why
tau < 1is required: Cosine similarities are bounded in[-1, 1], so attau = 1.0logits differ by at most2and even a perfect encoder (+1vs three-1s) has losslog(1 + 3 * exp(-2)) = 0.341. Typical values liketau = 0.07to0.2sharpen the softmax, though settingtautoo tiny causes gradient instability and tears apart false negatives (two different photos that happen to show golden retrievers). InfoNCE also maximizes a lower bound on mutual information (shared informationIbetween views):I >= log(K) - L, which grows with more negativesK.
- Automatic hard-negative mining: Negative
Transformer architecture from input tokens to output head
A Transformer processes a sequence of
ntokens (subword pieces in NLP, or flattened16 x 16image patches in a Vision TransformerViT, where a224 x 224RGB image becomes14 * 14 = 196patch tokens of16 * 16 * 3 = 768numbers) as an(n, d)matrix of width-dvectors stacked throughLidentical blocks:Tokens / Patches -> Embedding (n x d) -> + Positional Info | +---------------------------v---------------------------+ | Transformer Block (repeated L times, Pre-LN layout) | | 1. h = x + MultiHeadAttention(LayerNorm(x)) | | 2. x = h + FeedForward(LayerNorm(h)) | +---------------------------+---------------------------+ v Final LayerNorm -> Task Head (LM vocab logits / class head)Inside each block, four components cooperate:
- Multi-head self-attention: The only step inside an encoder/decoder block that mixes information across different token positions.
- Position-wise feed-forward network (FFN): Two linear layers separated by a nonlinearity (
GELU,ReLU, or gatedSwiGLU), typically expanding widthd -> 4d -> d, applied independently to each token vector to transform the gathered context. - Residual connections (
x + sublayer(...)): Add a sub-layer's input directly to its output, giving gradients an unbroken highway across dozens of layers so each block only needs to learn an incremental refinement. - Layer normalization (
LayerNorm): Rescales each token'sdfeatures to zero mean and unit variance (with learned gain and bias). Modern models placeLayerNormbefore each sub-layer (Pre-LN, shown above) because it stabilizes gradients from step 1 better than the original 2017 Post-LN (LayerNorm(x + sublayer(x))).
Depending on masking and wiring, you get encoder-only models (
BERT,ViT: bidirectional context for classification/embeddings), decoder-only models (GPT: a causal mask blocks future tokens for left-to-right generation), or encoder-decoder models (T5: decoder blocks add cross-attention over encoder outputs). A standard block holds4 * d^2weights in attention (W_q, W_k, W_v, W_o) plus8 * d^2in thed -> 4d -> dFFN =12 * d^2weights (12 * 768^2 = 7.08Mper block inBERT-base, or~85Macross 12 blocks plus~24Membeddings =~110Mtotal).Self-attention vs. recurrent and convolutional layers
In self-attention, every token
iprojects its vector into three roles using learned matrices: a queryq_i(what I am looking for), a keyk_i(what I contain), and a valuev_i(what information I pass along):Attention(Q, K, V) = softmax( (Q @ K^T) / sqrt(d_k) ) @ VWhy divide by
sqrt(d_k)(whered_kis key dimension)? If entries ofq_iandk_jhave unit variance, summingd_kproducts givesq_i . k_jvarianced_kand standard deviationsqrt(d_k). Without dividing bysqrt(d_k), large dot products push softmax into0.9999 / 0.0001saturation where gradients vanish! Multi-head attention splits widthdintohsmaller heads of widthd_k = d / h(for example12heads of64inBERT-base) so one head can attend to the previous word while another links a pronoun to a noun40words back.Trace
3tokens of widthd_k = 2with identity projections (Q = K = V = X):import numpy as np def scaled_dot_attention(Q, K, V): d_k = Q.shape[1] scores = (Q @ K.T) / np.sqrt(d_k) shifted = scores - scores.max(axis=1, keepdims=True) weights = np.exp(shifted) / np.exp(shifted).sum(axis=1, keepdims=True) return weights @ V, scores, weights X = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]) out, scores, weights = scaled_dot_attention(X, X, X) print(np.round(weights, 3)) print(np.round(out, 3))Token Raw X Scores (X X^T / sqrt(2)) Attention weights Output (weights @ X) ----- --------- ------------------------ ---------------------- -------------------- 0 [1.0, 0.0] [0.707, 0.000, 0.707] [0.401, 0.198, 0.401] [0.802, 0.599] 1 [0.0, 1.0] [0.000, 0.707, 0.707] [0.198, 0.401, 0.401] [0.599, 0.802] 2 [1.0, 1.0] [0.707, 0.707, 1.414] [0.248, 0.248, 0.503] [0.752, 0.752]Compare how the three sequence-modeling families route information across
ntokens of widthd(with convolution kernel widthk):Architecture Compute per layer Sequential ops Max path between distant tokens -------------- ----------------- -------------- ------------------------------- Self-attention O(n^2 * d + n*d^2) O(1) parallel O(1): direct 1-hop interaction Recurrent (RNN) O(n * d^2) O(n) serial O(n): compressed step-by-step Convolution O(k * n * d^2) O(1) parallel O(n / k) stacked (O(log_k n) dilated)RNNs process one token after another—blocking GPU sequence parallelism and forcing distant context through a fixed-size bottleneck—while CNNs only see local
k-token neighborhoods per layer (giving helpful spatial locality for small image datasets, which is whyViTneeds heavier regularization or larger pretraining sets than ResNets). Self-attention connects any two tokens in one content-dependent hop and trains fully in parallel across positions, paying anO(n^2 * d)cost that dominates once sequence lengthngrows past model widthd(atd = 768, attention's2 * n^2 * dmultiply-adds are0.40Bvs3.62Bfor linear layers atn = 512, flipping to103.1Bvs58.0Batn = 8192).Positional encoding: giving attention a sense of order
Without position hints, unmasked self-attention is permutation-equivariant: if you shuffle the input tokens, every dot product
q_i . k_jmoves to the new index unchanged, so the output vectors are identical—just shuffled in the exact same order! To unmasked self-attention,"dog bites man"and"man bites dog"are indistinguishable bags of vectors:import numpy as np rng = np.random.default_rng(0) X = rng.normal(size=(5, 8)) W_q, W_k, W_v = (rng.normal(size=(8, 8)) for _ in range(3)) def unmasked_self_attention(tokens): Q, K, V = tokens @ W_q, tokens @ W_k, tokens @ W_v scores = (Q @ K.T) / np.sqrt(Q.shape[1]) scores = scores - scores.max(axis=1, keepdims=True) weights = np.exp(scores) / np.exp(scores).sum(axis=1, keepdims=True) return weights @ V perm = np.array([3, 0, 4, 1, 2]) print(bool(np.allclose(unmasked_self_attention(X[perm]), unmasked_self_attention(X)[perm]))) # TrueBecause order changes meaning (who bit whom, or which patch is top-left vs. bottom-right), Transformers inject position information explicitly:
- Sinusoidal encodings (original 2017 Transformer): Add a deterministic vector of alternating sines and cosines across geometric wavelengths (
PE(pos, 2i) = sin(pos / 10000^(2i / d)),PE(pos, 2i + 1) = cos(...)) directly to each token embedding. Just like the hands of a clock (fast second hand, slow hour hand), low dimensions tick rapidly for nearby offsets while high dimensions drift slowly, and a fixed offsetpos + deltais a linear rotation ofPE(pos). - Learned absolute embeddings (
BERT,GPT-2,ViT): Lookup table ofmax_lentrainable vectors (512inBERT,197inViT) added to token embeddings—simple and flexible, but undefined pastmax_lenwithout interpolation. - Relative position schemes (
RoPE,ALiBi): Modern LLMs inject position directly inside attention scores instead of only at layer 0. RoPE (Rotary Position Embedding) rotatesq_iandk_jin 2D planes by angles proportional toiandjso their dot productq_i . k_jdepends cleanly on relative distancei - j(extended past training length via position interpolation). ALiBi subtracts a linear distance penalty-m * |i - j|directly from attention logits, letting models extrapolate smoothly to longer sequences.
- Sinusoidal encodings (original 2017 Transformer): Add a deterministic vector of alternating sines and cosines across geometric wavelengths (
Intuition & how it works
Think of preparing a student for an unseen reading exam in three stages:
- Generalization (avoiding overfitting): A student who memorizes the exact wording and typos of 12 practice questions aces practice quizzes (
train loss -> 0) but panics on exam day (overfitting, high variance—oversensitivity to training-set quirks), while a student who only skims a one-line summary misses both (underfitting, high bias—an overly rigid model). Good study habits—practicing more varied exercises, penalizing wild guesses, and checking progress on held-out mock exams—force real understanding. - Contrastive learning & InfoNCE: Before seeing any graded exam questions, the student builds intuition by sorting flashcards into matching pairs: two crops of the same photo or a headline and its own summary go in the positive pile, while unrelated cards in the batch act as negatives. InfoNCE turns each card into a multiple-choice test using cosine similarity (the dot product of unit-length embeddings, numeric vectors encoding meaning) scaled by a sharpness dial
tau(temperature), pulling true partners together and pushing look-alike distractors apart. - Transformers: When reading a sentence, instead of reading strictly word-by-word through one tiny memory notepad (like a recurrent neural network), self-attention lets every word simultaneously look back and forward across the whole page to gather context in one hop, using positional encodings as page-and-word coordinates so
"dog bites man"is never confused with"man bites dog".
Naive designs fail at each stage: optimizing training loss alone memorizes noise; pulling positive embeddings together without negatives (or architecture tricks) suffers representation collapse (mapping every input to the exact same constant vector for a trivial zero loss); and leaving out sqrt(d_k) scaling or position encodings makes self-attention saturate its gradients and treat sentences as unordered bags of words.
Three small numeric snapshots make each mechanism concrete:
- Overfitting vs. regularization: On
12points fromy = sin(3x) + noise(noise floor mean squared error0.04, the average squared prediction error), polynomial degrees1,3, and9achieve validation MSEs of0.203(underfit),0.051(well-fit), and1.354(severe overfit with weight norm64.6), which L2 regularization (lambda = 0.1) pulls right back down to0.051(weight norm1.5). - InfoNCE temperature: With positive cosine similarity
0.8and three negatives[0.5, 0.3, -0.1], softmax (turningsimilarity / tauscores into probabilities summing to1) assigns probabilities[0.363, 0.269, 0.220, 0.148]attau = 1.0(loss1.013), versus[0.946, 0.047, 0.006, 0.000]attau = 0.1(loss0.055), concentrating almost the entire repulsive gradient (0.471vs0.001) onto the hardest0.5negative. - Self-attention: For
3tokens[[1, 0], [0, 1], [1, 1]](d_k = 2), dividingX @ X^Tbysqrt(2)and applying row-wise softmax gives token0weights[0.401, 0.198, 0.401], blending compatible tokens0and2while down-weighting perpendicular token1.
Key points
- Overfitting vs. underfitting: Overfitting shows low training loss alongside rising or much higher validation loss (high variance); underfitting shows high loss on both sets (high bias).
- Practical detection: Plot per-epoch (full-dataset pass) train/validation loss curves, plot learning curves across dataset fractions (
10%..100%), run k-fold cross-validation (rotating which1/kslice is held out), verify the gap exceeds validation standard error (sqrt(p * (1 - p) / n)), and rule out data leakage (future/label hints in features) or distribution shift (test data differing from training data). - Distinct remedies and why they work: More data or data augmentation (teaches label-preserving invariances), L2/L1 regularization or decoupled
AdamWweight decay (penalizes large weights so curves stay smooth), early stopping (halts before weights drift into memorizing noise), dropout (randomly zeros fractionpof hidden units during training and scales survivors by1 / (1 - p)so neurons cannot co-adapt), simpler architectures, and ensembling (averaging models to cancel variance). - Contrastive pairs and downstream wins: Positives come from two augmentations of one image (
SimCLR), an image and its caption (CLIP), two dropout passes of one sentence (SimCSE), or(query, answer passage)pairs; negatives come from other in-batch items, momentum queues (MoCo), or mined hard distractors. Pretrained encoders boost few-shot classification, semantic retrieval, zero-shot transfer, clustering, and deduplication. - InfoNCE / NT-Xent mechanics: Softmax cross-entropy over L2-normalized cosine similarities divided by
taupulls the positive with gradient magnitude(1 - p_pos) / tauand pushes each negativekwithp_k / tau, automatically up-weighting hard negatives while maximizing alog(K) - Llower bound on mutual information (shared information across views, forKtotal candidates). - Transformer block & parameter budget: Token/patch embeddings + positional information feed
Lblocks of multi-head self-attention (cross-token mixing) and position-wise feed-forward networks (d -> 4d -> dper-token compute), wrapped in residual connections (x + sublayer(...)gradient highways) and layer normalization (typically Pre-LN), totaling~12 * d^2weights per block (~110MinBERT-base). - Self-attention vs. RNNs & CNNs, plus positions: Attention connects distant tokens in
O(1)hops andO(1)sequential steps atO(n^2 * d)compute, whereas RNNs requireO(n)serial steps and CNNs stack localk-wide windows. Because raw attention is permutation-equivariant (shuffling inputs merely shuffles outputs), sinusoidal, learned absolute, or relative (RoPE,ALiBi) position encodings are essential.
Common mistakes
- Diagnosing every train-validation gap as overfitting: Data leakage, random splits on time-series or grouped user data, and train-to-production distribution shift look like validation gaps too, and regularization will not fix them.
- Tuning hyperparameters on the test set: Picking
lambda, dropout ratep, or the early-stopping epoch on the final test split leaks test information and inflates reported metrics. - Forgetting train-vs-inference dropout behavior or
AdamW: Dropout must be disabled during evaluation (with1 / (1 - p)inverted scaling applied during training), andL2gradient penalties are not equivalent to decoupled weight decay under adaptive optimizers like Adam. - Omitting L2 normalization or temperature
tauin InfoNCE: Without L2-normalizing embeddings, the network lowers loss simply by blowing up vector norms||z||instead of aligning directions; withouttau < 1, bounded cosine similarities[-1, 1]leave softmax too flat to separate hard negatives. - Claiming contrastive learning requires human labels (or never suffers false negatives): Self-supervised methods create pairs via augmentations without labels, though large random batches inevitably treat other same-class examples as negatives unless mitigated.
- Saying Transformers are cheaper than RNNs at all sequence lengths: Transformers win on GPU parallelism and
O(1)path length, not asymptotic FLOPs—self-attention scales quadratically (O(n^2 * d)) in sequence lengthn. - Leaving out
1 / sqrt(d_k)scaling or claiming standard position encodings are concatenated: Unscaled dot products have varianced_kand saturate softmax gradients, and standard sinusoidal/BERT position encodings are added to token embeddings (or applied as rotations/biases inRoPE/ALiBi).
Follow-up questions
- Why do contrastive frameworks like SimCLR train with a nonlinear projection head and then discard it before downstream tasks? The contrastive loss forces the final output space to become completely invariant to training augmentations like color jitter or cropping, throwing away details such as object color or orientation. Keeping a small MLP projection head
g(.)during pretraining letsg(f(x))absorb that aggressive invariance while the earlier encoder outputf(x)retains richer visual features—improving downstream linear probe (a single linear classifier trained on frozenf(x)features) accuracy by over 10 percentage points in the original SimCLR study. - How can self-supervised representation learning avoid collapsing to a constant vector when no negative pairs are used? You must still block representation collapse (every input mapping to the exact same constant vector) through architectural asymmetry or explicit variance constraints. Methods like
BYOLandSimSiamremove negatives by passing one view through an extra predictor head and blocking gradients (stop-gradient) on the target branch (plus an exponential moving-average target encoder inBYOLandDINO), whereasBarlow TwinsandVICRegenforce per-dimension variance and cross-dimension decorrelation directly in the loss. - What techniques let modern Transformers scale to 32k-1M+ token contexts despite the quadratic cost of standard self-attention? First, FlashAttention computes exact scaled dot-product attention in SRAM tiles without ever materializing the
n x nattention matrix in GPU HBM, keeping exact math while cutting extra memory fromO(n^2)toO(n)and speeding up wall-clock runtime several-fold. Second, architectures reduce compute and KV-cache (stored past key/value tensors during autoregressive decoding) overhead via grouped-query attention (GQA) (sharing key/value heads across query heads), sliding-window or block-sparse attention (O(n * w * d)), or linear-time state-space hybrids (Mamba).
Follow-up questions
- Why do contrastive frameworks like SimCLR train with a nonlinear projection head and then discard it before downstream tasks?
- How can self-supervised representation learning avoid collapsing to a constant vector when no negative pairs are used?
- What techniques let modern Transformers scale to 32k-1M+ token contexts despite the quadratic cost of standard self-attention?
Similar questions
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning
- Correlation Bounds, Equicorrelated Variables, and Box-Muller Sampling
- Feed Click-Through Rate Feature Engineering and Modeling