Representation Learning, Self-Supervised Learning, And Contrastive Learning
Asked of: Machine Learning Engineer
Last updated
What's being tested
These prompts test whether you can explain how representation learning turns raw inputs into reusable embeddings, then connect training objectives to geometry, evaluation, and production behavior. The interviewer is probing more than vocabulary: you should distinguish pretext tasks, masked prediction, and contrastive learning, and explain when each creates useful signal. For a Machine Learning Engineer, this matters because representation quality affects training cost, serving latency, model reuse, online/offline parity, and robustness when labels are scarce or data distributions change.
Core knowledge
-
Representation learning learns a mapping such that the embedding preserves information useful for downstream tasks. It replaces manually engineered features with learned features, but “useful” must be demonstrated through transfer performance, retrieval quality, robustness, and serving constraints.
-
A pretext task creates supervision from unlabeled data rather than human annotations. Examples include predicting image rotation, reconstructing masked text, matching two augmented views, or predicting temporal order; the task is only valuable if solving it forces features relevant to downstream behavior rather than superficial shortcuts.
-
Self-supervised learning derives targets from the input itself, whereas unsupervised learning is the broader category of discovering structure without labels. Self-supervised objectives can still use domain assumptions, augmentations, or metadata, so “no human labels” does not mean “no supervision design.”
-
Masked prediction hides part of an input and predicts the missing content: tokens in
BERT, image patches inMAEorBEiT, and spans or frames in speech models. Masking too little makes the task trivial; masking too much removes context. Text often uses high masking ratios because redundancy is strong, while images and speech require preserving enough spatial or temporal context. -
Contrastive learning trains embeddings so positive pairs have high similarity and negatives have lower similarity. A common InfoNCE objective is
Here is temperature, usually with cosine similarity after L2 normalization. -
Positive pairs represent the same semantic instance under permitted transformations: two image augmentations in
SimCLR, two views or modalities inCLIP, or neighboring context windows in language. The augmentation policy defines invariances; cropping out the object, changing sentiment, or removing identity cues can create false positives and damage the representation. -
Negative samples supply competing alternatives, but false negatives occur when two examples share the same class or meaning. In-batch negatives are cheap and parallelizable, while memory queues such as
MoCoincrease negative diversity; larger batches can improve contrastive learning but raise GPU memory and communication cost. -
Embedding collapse occurs when many inputs map to the same vector, making similarity uninformative. Contrastive denominators, variance/covariance regularization, stop-gradient designs such as
BYOL, and predictor asymmetry inSimSiamare different ways to prevent collapse; monitoring embedding variance and pairwise cosine distributions catches it. -
A margin specifies how much separation is required. For a triplet ,
Once the negative is farther than the positive by , that triplet has zero gradient. Too-small margins permit poor separation; too-large margins create excessive active triplets and unstable or slow training. -
Hard negatives are highly similar but incorrect examples and can accelerate learning, yet they may be mislabeled or semantically valid alternatives. Semi-hard negatives are farther from the anchor than the positive but still within the margin, often offering a safer training signal than aggressively mined hardest examples.
-
Evaluate representations separately from the pretraining loss. Use a frozen linear probe, fine-tuning, nearest-neighbor or retrieval metrics such as
Recall@K, clustering diagnostics, calibration, and slice-level robustness. A low contrastive loss does not guarantee downstream quality; leakage, shortcut features, and a mismatched augmentation policy can all produce misleading results. -
Productionizing embeddings requires versioned preprocessing, deterministic checkpointing, reproducible sampling, and offline/online parity. Monitor embedding norms, dimensionality, nearest-neighbor distributions, drift, retrieval latency, and downstream metrics; an embedding model can remain numerically healthy while semantic quality degrades after a data or product shift.
Worked example: What is a pretext task in self-supervised learning?
A strong candidate first clarifies the modality, the unlabeled data available, the downstream task, and whether the goal is a general-purpose encoder or one optimized for a single application. I would define a pretext task as an automatically constructed objective whose labels come from the input, then explain that its value is measured by the transferable information in the learned representation. I would organize the answer around four pillars: task construction, representative examples, the relationship to contrastive or masked objectives, and downstream evaluation. For vision, I might contrast rotation prediction with matching augmented views; for language, I would use masked-token prediction; for multimodal data, I would mention CLIP-style image-text alignment. I would explicitly flag the tradeoff between a task that is easy to optimize and one that is semantically useful, because shortcut learning can produce excellent pretext accuracy but weak transfer. I would also state that augmentations and negative definitions encode assumptions about which differences should be ignored. Finally, I would close by saying that with more time I would design an ablation plan covering augmentation strength, label-efficiency curves, frozen versus fine-tuned transfer, and robustness across important data slices.
A second angle: What is the goal of contrastive loss in representation learning?
For contrastive loss, the framing shifts from “how are targets generated?” to “what geometry should the embedding space have?” I would clarify the similarity function, positive-pair semantics, negative source, batch size, and whether retrieval or classification is the downstream use case. The answer should cover attraction between positives, repulsion from negatives, temperature or margin, and collapse prevention. A key production tradeoff is that larger batches and memory queues provide more negatives but increase memory, synchronization, and the risk of false negatives. I would close by connecting the training objective to Recall@K, nearest-neighbor behavior, and monitoring rather than treating loss alone as the success criterion.
Common pitfalls
Pitfall: Saying that a pretext task is simply “training without labels” is incomplete. The important point is that targets are algorithmically derived from the input and must encourage features that transfer to the intended downstream tasks.
Pitfall: Claiming that contrastive learning always makes “similar examples close” ignores the definition of similarity. Augmentations, metadata, and negative sampling determine which invariances are learned, and false negatives can actively distort the space.
Pitfall: Quoting InfoNCE or a margin formula without discussing evaluation and failure modes sounds memorized. A stronger answer mentions collapse, hard-negative quality, temperature or margin tuning, frozen-versus-fine-tuned transfer, and production monitoring.
Connections
An interviewer may pivot to metric learning, triplet loss, nearest-neighbor retrieval, and approximate nearest-neighbor indexes such as FAISS. They may also ask about transformer pretraining, data augmentation, transfer learning, embedding drift, or the offline/online consistency of a deployed encoder.
Further reading
- A Simple Framework for Contrastive Learning of Visual Representations —
SimCLRand the effects of augmentations, projection heads, and batch size. - Momentum Contrast for Unsupervised Visual Representation Learning — memory queues and dynamic dictionaries for contrastive training.
- Masked Autoencoders Are Scalable Vision Learners — masked prediction for image representations and the role of high masking ratios.
Practice questions
- What is the purpose of the margin parameter in contrastive and triplet losses?General · Machine Learning Engineer · Other · medium
- What is the goal of contrastive loss in representation learning?General · Machine Learning Engineer · Other · easy
- What is masked prediction in self-supervised learning?General · Machine Learning Engineer · Other · medium
- What is a pretext task in self-supervised learning?General · Machine Learning Engineer · Other · medium
- What is the reconstruction loss in an autoencoder measuring conceptually?General · Machine Learning Engineer · Other · easy
- Why are negative pairs critical to prevent representation collapse in contrastive methods?General · Machine Learning Engineer · Other · hard
- What is representation learning?General · Machine Learning Engineer · Other · easy
Related concepts
- Supervised ML, Imbalance, Overfitting, And OptimizationMachine Learning
- Transformer Self-Attention and BackpropagationMachine Learning
- Large Language ModelsML System Design
- Transformer Architectures And AttentionMachine Learning
- LLM Foundations, Embeddings, Prompts, And Fine-Tuning
- Applied Machine Learning Modeling And EvaluationMachine Learning