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:

  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. 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 12 noisy training points generated from y = sin(3x) + noise, where the random noise has standard deviation 0.2. Because irreducibly random noise has variance 0.2^2 = 0.04, no model can beat a mean squared error (MSE)—the average of (prediction - target)^2—of about 0.04 on 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)
    
  2. 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%, and 100% 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 k equal folds, train on k - 1 folds, validate on the held-out fold, and rotate k times. 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 on n = 200 items, sqrt(0.8 * 0.2 / 200) = 0.028, so a 2% gap can be luck while a 15% 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).
  3. 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:

    1. 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.
    2. L2 / L1 regularization and weight decay: Adding lambda * sum(w_j^2) (L2 / ridge) or lambda * 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, and L1 pushes unneeded weights all the way to 0. Applying an L2 penalty to our degree-9 polynomial (with standardized powers x^1 .. x^9 and 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 -> underfits

    In 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.
    
    1. 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.
    2. Dropout: On each training forward pass, randomly set each hidden activation to 0 with probability p and multiply kept activations by 1 / (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.
    3. 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.
  4. 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 trains f on 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 other B - 1 captions in a batch of B pairs gives B - 1 negatives.
    • 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.

  5. InfoNCE / NT-Xent contrastive loss and why temperature matters

    First L2-normalize every embedding (z = v / ||v||_2) so its length is 1. Then the dot product sim(z_a, z_b) = z_a . z_b equals their cosine similarity (ranging from -1 for opposite directions, 0 for perpendicular, to +1 for identical direction). Given an anchor z_i, one positive z_i+, and K - 1 negatives (K candidates total), InfoNCE divides each similarity by a temperature tau > 0 to form logits (raw scores) and applies softmax (exponentiating scores and dividing by their sum so probabilities add to 1):

    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 B images produces 2B augmented views, so each anchor compares 1 positive against 2B - 2 negatives (K = 2B - 1 candidates). Intuitively, InfoNCE is just multi-class cross-entropy for a K-way multiple-choice quiz: "Out of these K candidates, pick the one true partner z_i+."

    Trace one anchor whose cosine similarity is 0.8 with 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 k is pushed away in direct proportion to its softmax probability p_k. At tau = 0.1, the confusable 0.5 negative gets a push of 0.471, while the easy -0.1 negative gets 0.001—training automatically focuses on mistakes!
    • Why tau < 1 is required: Cosine similarities are bounded in [-1, 1], so at tau = 1.0 logits differ by at most 2 and even a perfect encoder (+1 vs three -1s) has loss log(1 + 3 * exp(-2)) = 0.341. Typical values like tau = 0.07 to 0.2 sharpen the softmax, though setting tau too 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 information I between views): I >= log(K) - L, which grows with more negatives K.
  6. Transformer architecture from input tokens to output head

    A Transformer processes a sequence of n tokens (subword pieces in NLP, or flattened 16 x 16 image patches in a Vision Transformer ViT, where a 224 x 224 RGB image becomes 14 * 14 = 196 patch tokens of 16 * 16 * 3 = 768 numbers) as an (n, d) matrix of width-d vectors stacked through L identical 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:

    1. Multi-head self-attention: The only step inside an encoder/decoder block that mixes information across different token positions.
    2. Position-wise feed-forward network (FFN): Two linear layers separated by a nonlinearity (GELU, ReLU, or gated SwiGLU), typically expanding width d -> 4d -> d, applied independently to each token vector to transform the gathered context.
    3. 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.
    4. Layer normalization (LayerNorm): Rescales each token's d features to zero mean and unit variance (with learned gain and bias). Modern models place LayerNorm before 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 holds 4 * d^2 weights in attention (W_q, W_k, W_v, W_o) plus 8 * d^2 in the d -> 4d -> d FFN = 12 * d^2 weights (12 * 768^2 = 7.08M per block in BERT-base, or ~85M across 12 blocks plus ~24M embeddings = ~110M total).

  7. Self-attention vs. recurrent and convolutional layers

    In self-attention, every token i projects its vector into three roles using learned matrices: a query q_i (what I am looking for), a key k_i (what I contain), and a value v_i (what information I pass along):

    Attention(Q, K, V) = softmax( (Q @ K^T) / sqrt(d_k) ) @ V
    

    Why divide by sqrt(d_k) (where d_k is key dimension)? If entries of q_i and k_j have unit variance, summing d_k products gives q_i . k_j variance d_k and standard deviation sqrt(d_k). Without dividing by sqrt(d_k), large dot products push softmax into 0.9999 / 0.0001 saturation where gradients vanish! Multi-head attention splits width d into h smaller heads of width d_k = d / h (for example 12 heads of 64 in BERT-base) so one head can attend to the previous word while another links a pronoun to a noun 40 words back.

    Trace 3 tokens of width d_k = 2 with 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 n tokens of width d (with convolution kernel width k):

    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 why ViT needs 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 an O(n^2 * d) cost that dominates once sequence length n grows past model width d (at d = 768, attention's 2 * n^2 * d multiply-adds are 0.40B vs 3.62B for linear layers at n = 512, flipping to 103.1B vs 58.0B at n = 8192).

  8. 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_j moves 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])))  # True
    

    Because 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 offset pos + delta is a linear rotation of PE(pos).
    • Learned absolute embeddings (BERT, GPT-2, ViT): Lookup table of max_len trainable vectors (512 in BERT, 197 in ViT) added to token embeddings—simple and flexible, but undefined past max_len without interpolation.
    • Relative position schemes (RoPE, ALiBi): Modern LLMs inject position directly inside attention scores instead of only at layer 0. RoPE (Rotary Position Embedding) rotates q_i and k_j in 2D planes by angles proportional to i and j so their dot product q_i . k_j depends cleanly on relative distance i - 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.

Intuition & how it works

Think of preparing a student for an unseen reading exam in three stages:

  1. 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.
  2. 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.
  3. 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 12 points from y = sin(3x) + noise (noise floor mean squared error 0.04, the average squared prediction error), polynomial degrees 1, 3, and 9 achieve validation MSEs of 0.203 (underfit), 0.051 (well-fit), and 1.354 (severe overfit with weight norm 64.6), which L2 regularization (lambda = 0.1) pulls right back down to 0.051 (weight norm 1.5).
  • InfoNCE temperature: With positive cosine similarity 0.8 and three negatives [0.5, 0.3, -0.1], softmax (turning similarity / tau scores into probabilities summing to 1) assigns probabilities [0.363, 0.269, 0.220, 0.148] at tau = 1.0 (loss 1.013), versus [0.946, 0.047, 0.006, 0.000] at tau = 0.1 (loss 0.055), concentrating almost the entire repulsive gradient (0.471 vs 0.001) onto the hardest 0.5 negative.
  • Self-attention: For 3 tokens [[1, 0], [0, 1], [1, 1]] (d_k = 2), dividing X @ X^T by sqrt(2) and applying row-wise softmax gives token 0 weights [0.401, 0.198, 0.401], blending compatible tokens 0 and 2 while down-weighting perpendicular token 1.

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 which 1/k slice 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 AdamW weight decay (penalizes large weights so curves stay smooth), early stopping (halts before weights drift into memorizing noise), dropout (randomly zeros fraction p of hidden units during training and scales survivors by 1 / (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 tau pulls the positive with gradient magnitude (1 - p_pos) / tau and pushes each negative k with p_k / tau, automatically up-weighting hard negatives while maximizing a log(K) - L lower bound on mutual information (shared information across views, for K total candidates).
  • Transformer block & parameter budget: Token/patch embeddings + positional information feed L blocks of multi-head self-attention (cross-token mixing) and position-wise feed-forward networks (d -> 4d -> d per-token compute), wrapped in residual connections (x + sublayer(...) gradient highways) and layer normalization (typically Pre-LN), totaling ~12 * d^2 weights per block (~110M in BERT-base).
  • Self-attention vs. RNNs & CNNs, plus positions: Attention connects distant tokens in O(1) hops and O(1) sequential steps at O(n^2 * d) compute, whereas RNNs require O(n) serial steps and CNNs stack local k-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 rate p, 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 (with 1 / (1 - p) inverted scaling applied during training), and L2 gradient penalties are not equivalent to decoupled weight decay under adaptive optimizers like Adam.
  • Omitting L2 normalization or temperature tau in InfoNCE: Without L2-normalizing embeddings, the network lowers loss simply by blowing up vector norms ||z|| instead of aligning directions; without tau < 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 length n.
  • Leaving out 1 / sqrt(d_k) scaling or claiming standard position encodings are concatenated: Unscaled dot products have variance d_k and saturate softmax gradients, and standard sinusoidal/BERT position encodings are added to token embeddings (or applied as rotations/biases in RoPE/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 lets g(f(x)) absorb that aggressive invariance while the earlier encoder output f(x) retains richer visual features—improving downstream linear probe (a single linear classifier trained on frozen f(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 BYOL and SimSiam remove 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 in BYOL and DINO), whereas Barlow Twins and VICReg enforce 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 n attention matrix in GPU HBM, keeping exact math while cutting extra memory from O(n^2) to O(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

Similar questions

More Reuters interview questions

All 1 Reuters questions →