1. Home
  2. Explore
  3. Computer Science
  4. Self-Supervised Learning

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Self-Supervised Learning

Self-Supervised Learning: Study Notes

Representation learning and deep unsupervised learning

Representation learning is the process of transforming raw data into features that make important properties easier for a model to use. A useful representation can simplify a later task, such as classification, even when the classifier itself is simple.

For example, imagine two groups of points in a plane arranged in concentric circles. In Cartesian coordinates, separating the groups with a straight line is difficult. In polar coordinates, the groups can be distinguished by their different radii, so a simple linear classifier can separate them. The underlying points have not changed; the representation has.

Deep learning learns representations through successive layers of computation. Early layers tend to capture detailed, lower-level patterns; later layers combine these into more abstract and semantic features. In images, this progression might go from pixels to edges, corners, contours, object parts, and eventually object identities. A high-level representation can therefore support downstream tasks without requiring those tasks to start from raw pixels.

Deep learning is a form of representation learning, which is itself a part of machine learning. Deep unsupervised learning aims to learn useful representations from data without relying on human-provided labels. The term self-supervised learning is often used for methods that create a training signal from the data itself. In practice, the two terms are sometimes used interchangeably in this context.

Key idea: Self-supervised learning uses information already present in unlabeled data to construct a learning task. The model solves that task to acquire representations that can later support other tasks.


Why learn from unlabeled data?

The cost and limits of human labels

Creating a labeled dataset can require substantial human effort and supporting infrastructure. A labeling project may involve defining categories, writing annotation instructions, recruiting annotators, building interfaces, recording annotations, and storing the resulting data. Even with established pipelines, high-quality labels can be expensive and slow to obtain.

The difficulty varies by domain. Common image categories may already have many public labels, but creating useful datasets for areas such as medicine or law can be much harder. In many fields, there is far more unlabeled data than labeled data.

Self-supervised learning aims to use this larger pool of raw data to learn features before labels are collected. A task can then require fewer labels, run more efficiently, or achieve better results with the same number of labels.

Benefits for downstream tasks

A model pretrained on a large dataset can provide a useful starting point for a smaller downstream dataset. For example, a visual backbone pretrained for image classification can be adapted to object detection, instance segmentation, or semantic segmentation. The pretrained features provide a prior that can help the new task:

  • require fewer labeled examples;

  • converge more quickly;

  • achieve better performance, especially when labels are scarce.

Self-supervised learning seeks to obtain similarly useful features without depending on a large human-labeled pretraining dataset.

A cognitive motivation

Humans and animals learn much about the world through observation and interaction, without being explicitly told the label for every object or event. A child can develop useful visual knowledge from experience without repeatedly receiving verbal labels such as “cat.” This motivates the hope that a model trained on the structure of raw data might acquire broadly useful knowledge and generalize beyond the exact labels it has seen.

The “cake” analogy and the quality of supervision

One influential analogy treats self-supervised learning as the cake, supervised learning as the icing, and reinforcement learning as the cherry. The idea is that much useful knowledge might come from learning to predict structure in raw data, with explicit labels and reward signals adding further guidance.

The analogy is motivational rather than a literal measurement of information. A supervised label can be highly informative: “there is a dog here” or “this is the bounding box around a person” is more semantically grounded than a task such as predicting whether an image was flipped. Thus, the quality of the training signal matters, not merely the quantity of bits or prediction targets. Self-supervised learning is valuable because it can exploit abundant data, but its automatically generated signals may be weaker or less directly relevant than careful human labels.


What makes a task self-supervised?

A common pattern is to hide, corrupt, transform, or divide some part of the data, then train a model to predict a withheld part from the remaining information.

Examples include:

  • hiding pixels and reconstructing them from the visible image;

  • masking video frames and predicting the missing content;

  • masking words in a sentence and predicting them from the surrounding words;

  • predicting the future from the past, or the past from the future;

  • predicting one view of an object or scene from another view.

These are called pretext tasks or proxy tasks. The model is trained directly on the pretext task, but the ultimate purpose is usually to obtain features useful for different, downstream tasks.

The pretext task determines what information the model is encouraged to learn. A task that can be solved through a trivial shortcut may produce weak features. For example, filling a short gap in a video might be possible by interpolating pixels using nearby frames, without understanding the objects in the scene. A task should therefore be designed so that success encourages learning useful structure rather than exploiting an easy correlation.


Main families of self-supervised tasks

The methods covered here fall into three broad families:

  • Corrupt and reconstruct: Alter part of the input, then recover the original or missing information.

  • Visual common-sense tasks: Construct tasks such as predicting relative position, solving a jigsaw puzzle, or identifying an image’s rotation.

  • Contrastive prediction: Make representations of related data agree while distinguishing them from representations of unrelated or mismatched data.

These families differ in the supervision they create, but all use information derived from the unlabeled examples themselves.


Corrupting data and reconstructing it

Denoising autoencoders

An autoencoder encodes an input into a latent representation and decodes that representation into a reconstruction. A denoising autoencoder first corrupts the input, then learns to reconstruct the original, clean input.

The pipeline is:

  1. Start with a clean example xxx.

  2. Corrupt it to produce a noisy version x~\tilde{x}x~.

  3. Encode x~\tilde{x}x~ into a latent representation.

  4. Decode that representation into a reconstruction of xxx.

  5. Compare the reconstruction with the original example using a reconstruction loss.

If the input is never corrupted, an autoencoder may simply learn the identity mapping. Adding noise makes the model infer missing or damaged information, which can encourage it to learn regularities in the data. Too much noise, however, can make reconstruction impossible because the remaining signal is insufficient.

Common corruption types

Three forms of corruption are commonly used:

  • Additive isotropic Gaussian noise: Gaussian noise is added to input values, creating small, broadly distributed perturbations.

  • Masking noise: A randomly selected fraction of input elements is set to zero or otherwise hidden.

  • Salt-and-pepper noise: Random elements are set to extreme values, such as the minimum or maximum possible value.

The corruption level affects the difficulty and the representations learned. If corruption is too weak, the model may rely on the unaltered input. If it is too strong, the original content may be too difficult to recover.

Connection to the data manifold

A useful geometric interpretation is that real examples lie near a data manifold: a structured, lower-dimensional set within the full space of possible inputs. Corruption moves an example away from this manifold. The denoising model learns to map perturbed inputs back toward plausible data.

For Gaussian corruption, the perturbations can be pictured as a neighborhood surrounding each example. The model learns how to return points in that neighborhood toward the local structure of the data. Across many examples, this can reveal the shape of the manifold on which realistic data lies.

Reconstruction objectives

A reconstruction loss measures the difference between the model’s output and the original example. Common choices include mean squared error and binary cross-entropy, depending on the data and output representation.

The loss can also emphasize corrupted elements. If only some pixels were hidden, the model can be penalized more strongly for errors on those pixels. This reduces the incentive to copy the visible input and directs learning toward predicting missing content.

Stacked denoising autoencoders

A stacked denoising autoencoder applies denoising at multiple levels:

  1. A first autoencoder processes the raw input and produces hidden features.

  2. Those hidden features become the input to another denoising stage.

  3. Additional stages repeat the process, operating on increasingly abstract representations.

The hope is that deeper layers capture more semantic properties than the raw input. The type of corruption used at each layer matters because hidden features do not have the same interpretation as pixels. Some early implementations used activation functions whose units could be viewed as “on” or “off,” making masking hidden units natural. The best corruption strategy depends on the model architecture and representation.

Once features have been learned, they can be used in a supervised task. One approach is to freeze the pretrained features and train a classifier on top. Such layer-by-layer pretraining was especially useful when directly training deep networks was difficult.

Context encoders and image inpainting

A related task is to mask a region of an image and predict what belongs there. In a context encoder, the model receives an image with a region hidden, encodes the visible context, and decodes a completed image.

The complete image provides the target automatically: because the original image is available, the model knows what content was masked, without requiring a human label.

Possible masks include:

  • a large central rectangular region;

  • many smaller regions distributed over the image;

  • an object-shaped region, if segmentation annotations are available.

The first two versions can be self-supervised using only the image. Masking an object using a human-provided segmentation mask requires labeled information, so that variant is not fully self-supervised.

Reconstruction and adversarial losses

A simple pixel reconstruction objective can produce blurry completions. For example, if several plausible objects could fit a masked region, mean squared error can favor an average of those possibilities, yielding a smooth but unrealistic result.

A discriminator can provide an adversarial loss. It learns to distinguish real images from model-generated completions, encouraging the generator to produce sharper, more realistic-looking content. Combining the adversarial objective with a reconstruction objective can balance two goals:

  • Reconstruction loss: Keep the completion consistent with the actual image.

  • Adversarial loss: Encourage the completion to look realistic and sharp.

An adversarial loss alone can introduce plausible-looking details that do not fit the specific surrounding context. The reconstruction objective helps preserve consistency with the original scene.

Using pretrained encoder features

After training, the encoder can be reused for classification, detection, or segmentation. Context-encoder features showed advantages over ordinary autoencoder features in some transfer settings, though they remained weaker than features pretrained on a large labeled classification dataset. The result illustrates both the promise and the limitation of early reconstruction-based pretraining: self-supervision can produce transferable features, but not every pretext task provides equally strong representations.


Predicting one view from another

Some data can be divided into different, related views. A model can use one view to predict another. The task is most useful when the prediction cannot be completed by a trivial transformation and instead requires understanding meaningful properties of the example.

Image colorization

An image can be represented as a grayscale-like luminance channel plus color channels. In the Lab color space, the LLL channel represents luminance, while the aaa and bbb channels encode color.

A colorization model takes the luminance channel and predicts the missing color information. The luminance-to-color direction is harder than color-to-grayscale conversion: grayscale can be calculated from color, but color cannot generally be recovered uniquely from grayscale. The model must use contextual clues, such as identifying that leaves are often green or that a particular object is likely to have a characteristic color.

Colorization can therefore encourage learning object and scene structure, though the task is ambiguous because many colors may be plausible.

Why classification can work better than regression

A direct regression objective, such as mean squared error on color values, tends to average plausible colors. If a pixel could reasonably be red or blue, the average may be an unlikely, muted color.

One alternative is to quantize possible color values into discrete categories and predict a probability distribution over those categories. A classification-style loss can represent multiple plausible outcomes more effectively than a single averaged color value. This often produces more vivid and perceptually sharper colorizations.

Split-view or split-brain autoencoders

A split-view autoencoder divides an input into two views and trains encoders to predict each view from the other. In the color example, one encoder predicts color from luminance and another predicts luminance from color.

The two predictions can then be combined and compared with the original input. This creates a form of consistency check: the views should work together to explain the same image. The method can be applied beyond color, for example to predicting depth information from a color image or vice versa.

The task is useful when the views have complementary information. It is less informative if one view can be trivially calculated from the other.


Visual common-sense tasks

Visual common-sense tasks create labels from the structure of an image rather than from human annotations. They encourage models to learn spatial relations, object structure, or the orientation of natural scenes.

Relative patch position prediction

In relative position prediction, a model receives two patches from the same image and predicts their relative spatial arrangement.

A typical construction uses a roughly 3×33 \times 33×3 grid. One patch is used as a reference, often the center patch, and a second patch is selected from one of the surrounding positions. The model predicts which of the eight neighboring positions contains the second patch.

This task generates labels automatically: the original image indicates where each patch came from. To succeed, the model may need to recognize meaningful parts and their spatial relationships. For example, if it sees part of a cat’s ear and part of its face, it may need to understand their likely arrangement.

Avoiding shortcuts

Several design choices make the task more meaningful:

  • Prevent patch overlap. If patches overlap, shared boundary pixels can reveal their relative location without requiring visual understanding.

  • Apply spatial jitter. Randomly crop patches within their grid cells so the model cannot rely on fixed boundaries or exact coordinates.

  • Apply color jitter. Alter colors independently across patches so the model cannot match patches using simple color statistics alone.

These measures make it harder for the model to solve the task through low-level shortcuts.

Jigsaw-puzzle solving

A closely related task shuffles a grid of image patches and asks the model to identify their original arrangement. For a grid of nine patches, there are 9!9!9! possible permutations. Instead of predicting a sequence of patch movements, the model can classify the shuffled grid into one of a selected set of permutation categories.

The model processes patches with a shared encoder, combines their representations, and predicts the arrangement category. Solving the puzzle can encourage learning spatial and part-to-whole associations. As in relative position prediction, the patches need to be designed so that overlap or low-level boundary cues do not make the answer trivial.

Rotation prediction

In rotation prediction, an image is rotated by a known angle, and the model predicts which rotation was applied. A common task uses rotations of 0∘0^\circ0∘, 90∘90^\circ90∘, 180∘180^\circ180∘, and 270∘270^\circ270∘.

The task can encourage semantic understanding because recognizing orientation often requires identifying familiar objects. For example, recognizing an upside-down face requires detecting that it is a face and understanding its normal orientation. The task also has a physical interpretation: it asks the model to infer how the scene is oriented relative to the camera.

More rotation categories do not automatically improve the representation. Experiments found that the four right-angle rotations worked better than using only two categories or adding more fine-grained angles. Having both horizontal and vertical orientations was important. The likely reason is that the four-way task offers a useful level of difficulty without making the prediction task unnecessarily fine-grained.

Comparing visual pretext tasks

Early comparisons found that puzzle-like tasks, especially rotation prediction, improved over several alternatives such as colorization and relative patch prediction on feature-evaluation benchmarks. These tasks also transferred to classification, detection, and segmentation.

However, the gap between these self-supervised features and supervised ImageNet features was still substantial in some downstream tasks. For example, reported transfer results showed smaller gaps on detection than on classification or segmentation. The broader lesson is that an effective pretext task can produce useful features, but success at the proxy task does not guarantee supervised-level performance on every application.


Word embeddings and Word2vec

Contrastive prediction has important roots in language modeling. Word embeddings represent words as vectors so that words with similar usage or relationships have related representations.

Count matrices and matrix factorization

A simple approach constructs a word co-occurrence matrix, recording how often words appear near one another. A related approach uses term frequency and inverse document frequency. The matrix can then be factorized, for example with singular value decomposition, to produce lower-dimensional word representations.

This has conceptual similarities to matrix-factorization methods in recommendation systems. A user–item interaction matrix can be factorized into user and item embeddings; a word-context matrix can similarly be factorized into word representations.

Limitations of count-based factorization

  • Sparsity: Many pairs of related words may never occur together in the available data.

  • Computational cost: Factorizing a large matrix can be expensive.

  • Rare words: Infrequent words have too little evidence for reliable representations.

  • Very frequent words: Common function words can dominate counts unless handled with additional weighting or heuristics.

  • Scaling difficulty: Large vocabularies and datasets make the construction and factorization pipeline difficult to manage.

N-gram language models

An n-gram model predicts a word using a limited amount of neighboring context. A unigram model treats word probabilities independently. A bigram model conditions each word on the preceding word. More generally, an n-gram model uses a context of multiple neighboring words.

Word2vec learns word representations through a prediction objective rather than by directly factorizing a count matrix.

CBOW and skip-gram

Word2vec includes two complementary models:

  • Continuous bag of words (CBOW): Use surrounding words to predict the center word.

  • Skip-gram: Use the center word to predict the surrounding words.

In CBOW, each context word is mapped to an embedding. The context embeddings are averaged into a single vector, which is used to score possible center words. The model trains those embeddings so the actual center word receives a high score relative to alternatives.

In skip-gram, the center word’s embedding is used to predict each surrounding word. The method usually makes a simplifying conditional-independence assumption: given the center word, the surrounding words are treated as independent predictions.

Both models learn from ordinary text without manually labeling each word’s meaning. The context in which a word appears provides the training signal.

Efficient training and negative sampling

A full softmax prediction over every word in a large vocabulary can be computationally costly. Word2vec therefore uses efficient approximations, including negative sampling and hierarchical softmax. Negative sampling compares observed word-context pairs with selected non-observed pairs instead of calculating a normalized probability over the entire vocabulary for every example.

These techniques make it practical to learn embeddings from large text collections with relatively simple computation.

Relationships encoded in embeddings

Word embeddings can capture both similarity and relationships. For example, vector differences associated with country–capital pairs can be approximately parallel: the direction from one country to its capital can resemble the direction from another country to its capital.

This motivates vector arithmetic and nearest-neighbor queries. Combinations of word vectors can retrieve related concepts, such as a country plus its capital relation or a country plus a language or airline relation. Embeddings can also group related entities, such as sports teams, companies, executives, newspapers, and airlines.

These results show that predicting words from context can teach a model more than isolated word frequencies. The model learns regularities in how words and entities relate to one another.


Contrastive Predictive Coding

Contrastive Predictive Coding (CPC) generalizes the basic idea of predicting context to different modalities, including audio and images.

Instead of reconstructing the exact future signal, CPC learns representations that make a true future segment identifiable from a context, in contrast with incorrect alternatives. It can be understood as asking:

Given the available context, which of these candidate targets is the correct one?

General structure

CPC typically involves:

  1. An encoder that maps input segments into latent representations.

  2. A context model that combines earlier representations.

  3. A target encoder that represents the candidate future segment.

  4. A contrastive objective that scores the true target above negative alternatives.

The context and target can be compared with a dot product or a more expressive bilinear score. The negative examples are important: they determine what distinctions the model must learn in order to identify the correct target.

This framework relates to word2vec because both methods learn by contrasting an appropriate context–target pair with alternatives. CPC uses neural networks to build representations of richer contexts and targets, rather than relying only on simple averages of word embeddings.

CPC for audio

An audio signal can be divided into short chunks. A shared encoder maps each chunk into a latent vector, and a recurrent or autoregressive context model summarizes the past. The model then predicts which future latent vector corresponds to the actual continuation.

The task need not reconstruct the waveform. Instead, it tries to make the true future representation score higher than negative future representations.

Choosing negative examples

Negative sampling influences what the model learns:

  • Negatives drawn from other speakers can encourage features that distinguish speaker identity.

  • Negatives drawn from the same speaker can emphasize finer-grained speech content, such as phonetic structure.

The right negative samples depend on the downstream task. If speaker identity is irrelevant, sampling negatives from the same speaker can reduce the incentive to rely on speaker differences.

The actual target must also be sufficiently separated from the context. If the context and target overlap heavily, the model may identify the correct target using shared signal rather than learning meaningful structure.

Predicting at multiple time steps

CPC can predict several future steps, using a separate scoring transformation for each prediction distance. This creates a family of prediction tasks within one framework.

However, farther targets are not always more useful. A target too close to the context may be predictable from local continuity, such as overlapping audio. A target too far away may share little information with the context. The model then has insufficient evidence for prediction, and training may focus on weak or noisy relationships.

A useful prediction distance balances:

  • enough separation to prevent trivial copying;

  • enough shared information for the context to predict the target.

Slow, semantic features

Raw audio varies rapidly, but many downstream tasks depend on slower-changing information, such as phonemes or speaker identity. CPC can encourage the model to predict at a latent level where these more stable structures are represented, rather than predicting every high-frequency detail of the waveform.

As context and target are separated in time, the model is pushed toward learning features that persist across that interval. The choice of temporal offset is therefore central to the representation learned.

Evaluating CPC audio features

A common evaluation freezes the learned features and trains a simple classifier on top. This tests whether the information needed for the task is already present in the representation, without fine-tuning the encoder.

Reported results included strong speaker classification and phoneme classification. CPC features substantially outperformed engineered MFCC features on speaker classification, and also improved phoneme classification. A linear classifier did not always match supervised learning, but a small multilayer perceptron could approach supervised performance. This suggests that useful information may be encoded in the features even when it is not linearly separable.

Ablations also showed that negative sampling and prediction distance matter. Changing whether negatives came from the same speaker or mixed speakers affected phoneme performance. Predicting an appropriate number of steps performed better than predicting all the way to more distant targets, supporting the principle that the context and target must share useful information.

CPC for images

CPC can also be applied to images by dividing them into overlapping patches and encoding each patch with a shared convolutional network. The patch embeddings form a two-dimensional grid. A context model summarizes part of the grid and predicts representations of other patches.

Masked convolutions, as used in autoregressive image models, can aggregate context without allowing information from the target region to leak into the prediction. This makes it possible to predict multiple target patches efficiently.

In early ImageNet experiments, CPC produced stronger linear-classification results than several earlier visual pretext methods. The learned features also activated for recognizable structures such as textures, objects, and faces. Nevertheless, the gap between CPC’s early linear-classification performance and supervised performance remained large, motivating further improvements.


CPCv2 and large-scale pretraining

CPCv2 improved the original image version through architectural changes, data augmentation, training scale, and careful prediction design.

Main design changes

The improved system used:

  • a deeper and wider image encoder;

  • a wider context model;

  • larger image crops and patches;

  • a carefully chosen prediction distance;

  • extensive spatial and color augmentation on each patch;

  • more negative examples, including negatives from other patches in the training batch.

The model predicted a selected set of future patches rather than trying to predict every possible offset. This reflects the audio findings: more prediction targets are not automatically better. Prediction should focus on targets that are sufficiently distinct yet still informative given the context.

The contrastive objective used in this style of training is often called InfoNCE. In general, it increases the score of a positive context–target pair relative to scores for negative pairs. For a query representation qqq, a positive key k+k^+k+, negative keys k1−,…,kN−k_1^-, \ldots, k_N^-k1−​,…,kN−​, and temperature τ\tauτ, a typical form is

LInfoNCE=−log⁡exp⁡(s(q,k+)/τ)exp⁡(s(q,k+)/τ)+∑i=1Nexp⁡(s(q,ki−)/τ),\mathcal{L}_{\text{InfoNCE}} = -\log \frac{\exp\left(s(q,k^+)/\tau\right)} {\exp\left(s(q,k^+)/\tau\right) +\sum_{i=1}^{N}\exp\left(s(q,k_i^-)/\tau\right)} ,LInfoNCE​=−logexp(s(q,k+)/τ)+∑i=1N​exp(s(q,ki−​)/τ)exp(s(q,k+)/τ)​,

where sss is a similarity score. Minimizing this loss encourages the query to match its positive more strongly than the negatives.

Evaluation settings

Self-supervised representations can be evaluated in several ways:

  • Linear evaluation: Freeze the encoder and train a linear classifier on its features.

  • Fine-tuning with limited labels: Initialize a supervised model with the pretrained weights and train using only a fraction of the labels.

  • Transfer learning: Use the pretrained backbone for a different dataset or task, such as detection.

Linear evaluation tests the quality of the representation without changing it. Fine-tuning tests whether pretraining provides a useful initialization for a practical supervised task.

Results and data efficiency

CPCv2 substantially improved on the first CPC image results in linear classification. In the reported comparisons, it reached around 71.5% top-1 accuracy, compared with around 48.7% for the earlier version. Improvements accumulated through changes such as stronger encoders, larger patches, bottom-up as well as top-down prediction, and more extensive augmentation.

Its most important practical result was improved label efficiency. Using unlabeled data for pretraining and then fine-tuning with a limited amount of labeled data could outperform training from scratch with that same small label set. The gains were especially pronounced in low-label settings.

The method could achieve strong performance with only a small number of labeled examples per class. In the reported experiments, self-supervised pretraining required substantially fewer labels to reach the accuracy of a supervised model trained from scratch. Even when all labels were available, pretraining followed by fine-tuning could outperform direct supervised training.

Transfer results on object detection also showed that self-supervised features could match or exceed supervised pretrained features in some settings. This was important because it demonstrated that the learned features were useful beyond image classification.


Instance discrimination

CPC predicts relationships between local patches or future segments. A simpler approach, instance discrimination, treats each image as its own class-like identity.

The model receives two different augmentations of the same image and learns to recognize them as related. Other images in the batch or memory act as negatives.

For example, one view of a dog image might be grayscale, while another is flipped and randomly cropped. The model must recognize that both views come from the same source image, despite their differences, and distinguish them from views of other images.

Strong augmentations make this task more demanding. If two views retain nearly identical pixels, the model could match them through low-level details. Random crops, flips, color transformations, and other changes reduce these shortcuts and encourage the model to preserve more robust properties of the image.

The goal is not necessarily to learn an explicit object label. Instead, the model learns features that are stable across transformations of the same instance and distinguish that instance from other examples.


Momentum Contrast

Momentum Contrast (MoCo) formulates contrastive learning as a dictionary lookup problem:

  • The current example representation is a query.

  • Its related representation is a positive key.

  • Other keys act as negatives.

  • The model must identify the positive key among the candidates.

The memory queue

If negatives come only from the current mini-batch, their number is limited by the batch size. MoCo maintains a queue of previously computed key representations, allowing many negatives to be used without requiring an enormous batch.

A queue introduces a consistency challenge: older keys were produced by earlier versions of the encoder. If the encoder changes too quickly, stored keys become stale. MoCo addresses this with a momentum encoder, which changes gradually based on the current query encoder.

The procedure is:

  1. Create two augmentations of each image, one for the query encoder and one for the key encoder.

  2. Encode the query with the query encoder.

  3. Encode the key with the momentum encoder, without backpropagating through that encoder.

  4. Compare each query with its positive key and the negative keys in the queue.

  5. Update the query encoder through gradient descent.

  6. Update the key encoder gradually using the query encoder.

  7. Add the new keys to the queue and remove the oldest keys.

The momentum update can be written as

θk←mθk+(1−m)θq,\theta_k \leftarrow m\theta_k + (1-m)\theta_q,θk​←mθk​+(1−m)θq​,

where θk\theta_kθk​ and θq\theta_qθq​ are the key- and query-encoder parameters, and mmm is a momentum coefficient near one. The queue is typically managed in first-in, first-out order.

Why momentum helps

The momentum encoder produces keys that change slowly enough for the queue to remain useful. This makes it possible to use many negatives without computing and storing gradients for all of them. MoCo therefore combines a large dictionary of negatives with a more manageable batch size.

Its contrastive loss uses normalized representations, similarity scores, and a temperature parameter. Temperature controls how sharply the model distinguishes high-scoring candidates from lower-scoring ones.


SimCLR

SimCLR is a simple instance-discrimination framework that uses two augmented views of each image, a shared encoder, and negatives from the current batch.

Main components

  1. Apply two independent augmentations to every image.

  2. Encode both views with the same backbone, such as a ResNet.

  3. Pass each backbone representation through a small multilayer perceptron, or projection head.

  4. Apply the contrastive loss to the projected representations.

The projection head maps the backbone representation into a space used for contrastive training. This was an important design choice: the contrastive loss acts on the projected features, while the backbone representation itself can remain more useful for downstream tasks.

The two views can be treated in both directions: each view serves once as the anchor and once as the positive for the other. Other views in the batch provide negatives.

Batch size, augmentations, and training

SimCLR uses the batch itself to supply negatives, so large batches provide more negative examples. It also relies on strong data augmentation, including random crops, flips, color transformations, and Gaussian blur. The order of augmentations can also be randomized.

In the reported experiments, large batches and long training runs contributed to strong results. SimCLR achieved a major improvement in ImageNet linear evaluation over earlier methods, and increasing model width further improved accuracy. The results showed that, given enough capacity and carefully chosen augmentation, instance-level contrastive learning could approach supervised performance.

Model capacity

Wider models improved self-supervised results substantially. In the reported comparisons, increasing the model width produced especially strong gains for self-supervised learning. The results suggested that models trained on hard contrastive tasks could benefit greatly from additional capacity, although larger models also change the resource requirements of training.


MoCo v2 and the importance of implementation details

A later version of MoCo incorporated several effective SimCLR choices:

  • an MLP projection head;

  • stronger augmentation, including Gaussian blur;

  • a cosine learning-rate schedule;

  • longer training.

These changes substantially improved MoCo’s linear-evaluation results and transfer performance. The momentum queue remained useful because it allowed many negatives without requiring SimCLR-sized batches.

The comparison between the methods highlights a broader lesson: self-supervised performance depends not only on the basic learning principle, but also on many practical choices, including:

  • encoder depth and width;

  • projection-head design;

  • the number and source of negative examples;

  • augmentation strength and order;

  • batch size or memory-queue strategy;

  • optimizer and learning-rate schedule;

  • training duration;

  • prediction distance and patch design.

As these details improved, self-supervised visual representations rapidly approached supervised performance on classification and transfer benchmarks.


Comparing the main approaches

Reconstruction-based methods

  • Training signal: Recover clean or missing input content.

  • Examples: Denoising autoencoders, context encoders, colorization.

  • Potential strength: The model must capture regularities that allow missing information to be inferred.

  • Potential limitation: Pixel reconstruction can be ambiguous and produce blurry averages; a task may also be solved through local interpolation rather than semantic understanding.

Visual common-sense tasks

  • Training signal: Predict a constructed property such as spatial position, patch order, or rotation.

  • Examples: Relative position prediction, jigsaw puzzles, rotation prediction.

  • Potential strength: These tasks can encourage spatial and object-level reasoning.

  • Potential limitation: A model may exploit color, boundary, or orientation shortcuts unless the task is carefully designed.

Contrastive methods

  • Training signal: Match related contexts and targets or different views of the same example while distinguishing negatives.

  • Examples: Word2vec, CPC, instance discrimination, MoCo, SimCLR.

  • Potential strength: Contrastive objectives apply across modalities and can directly organize representations around useful similarities and distinctions.

  • Potential limitation: The choice of negatives, augmentations, and prediction targets strongly affects what is learned.


Practical principles for designing self-supervised learning

Make the task nontrivial

A model should not be able to solve the pretext task by copying overlapping pixels, matching boundaries, or using fixed positional cues. Spatial and color jitter, non-overlapping patches, and careful target selection can reduce such shortcuts.

Preserve useful information while making views different

For instance discrimination, the two augmented views should differ enough to discourage pixel matching, but should retain the properties intended for the downstream task. If augmentations remove important information, the model may learn the wrong invariances.

Choose informative negatives

Negatives define what the model must distinguish. Their source can determine whether learning emphasizes instance identity, speaker identity, phonetic structure, or other properties. Negative examples should be challenging enough to teach meaningful distinctions without making the task impossible.

Balance prediction distance and information overlap

A target that is too close to the context may be trivially predictable. A target that is too distant may have little information in common with the context. Effective contrastive prediction requires a useful balance between these extremes.

Evaluate features beyond the proxy task

Strong pretext-task performance does not necessarily imply strong downstream performance. Representations should be assessed through linear evaluation, fine-tuning, and transfer to tasks that differ from the pretext task.


Overall significance

Self-supervised learning addresses a central limitation of supervised learning: the scarcity and cost of labeled data compared with the abundance of raw data. Its central strategy is to derive supervision from structure already present in images, audio, text, or other inputs.

The history of methods from denoising autoencoders through visual pretext tasks, CPC, and instance discrimination shows that useful features can be learned without human labels. The strongest results depend on carefully chosen proxy tasks and engineering details, but the potential payoff is substantial: a model can use large unlabeled datasets to build representations, then require fewer labels and less training for downstream applications.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent