Contrastive Learning Explained: Uses in Computer Vision, NLP & More

Title: Contrastive learning teaches models to distinguish similar from dissimilar data by pulling positive pairs together and pushing negative pairs apart in embedding space.
Source: AIML.com Research
Title: Contrastive learning teaches models to distinguish similar from dissimilar data by pulling positive pairs together and pushing negative pairs apart in embedding space.
Source: AIML.com Research

Introduction

Training machine learning models traditionally requires large amounts of labeled data, a significant bottleneck since manual annotation is expensive and time-consuming. Contrastive learning offers a compelling alternative: it enables models to learn meaningful representations from unlabeled data by comparing samples against each other.

The core idea is straightforward. Given a data point, create two different “views” of it (for example, two augmented versions of an image). Train the model to recognize that these views belong together while distinguishing them from views of other samples. Through this comparison process, the model learns features that capture the underlying structure of the data.

This approach has achieved remarkable results across domains. In computer vision, SimCLR [1] and MoCo [2] match or exceed supervised pre-training performance. In natural language processing, SimCSE [3] produces state-of-the-art sentence embeddings with minimal changes to existing models. AndiIn multimodal learning, CLIP [4] enables zero-shot image classification by aligning images and text in a shared space.

This article explains how contrastive learning works, surveys the key methods across computer vision, NLP, and multimodal applications, and discusses why this approach succeeds.

How Does Contrastive Learning Work?

Contrastive learning relies on three key components: positive and negative pairs, an encoder network, and a contrastive loss function.

Positive and Negative Pairs

A positive pair consists of two views of the same underlying data point. In computer vision, these are typically two augmented versions of the same image (different crops, color adjustments, or blurs). In NLP, SimCSE creates positive pairs by passing the same sentence through a transformer twice with different dropout masks. The key insight is that despite surface differences, these views share the same semantic content.

A negative pair consists of views from different data points. During training, all other samples in a batch typically serve as negatives. The model learns to distinguish the positive pair from these negatives.

Encoder Network

The encoder maps input data to a lower-dimensional embedding space where similarity comparisons occur. For images, this is typically a convolutional neural network or a vision transformer. For text, it is usually a transformer like BERT or its variants.

Most contrastive methods add a projection head on top of the encoder, a small MLP that maps features to a space specifically optimized for the contrastive objective. Interestingly, this projection head is discarded after pre-training. The encoder features (before the projection) transfer better to downstream tasks.

Contrastive Loss Function

The most widely used loss function is InfoNCE (also called NT-Xent in SimCLR). Given a positive pair with embeddings z_i and z_j, the loss is:

\[ \mathcal{L}_{\text{InfoNCE}} = – \log \frac{ \exp\left(\frac{\operatorname{sim}(z_i, z_j)}{\tau}\right) }{ \sum_{k=1}^{2N} \mathbf{1}_{[k \neq i]} \exp\left(\frac{\operatorname{sim}(z_i, z_k)}{\tau}\right) } \]

where 

sim(u, v) = uTv denotes cosine similarity (dot product of normalised vectors), 

= temperature parameter that controls the sharpness of the distribution (higher value gives peaky distribution, lower value gives smoother distribution)

The numerator measures similarity between the positive pair. The denominator sums over all other samples in the batch (negatives).

The intuition is that this loss functions like a softmax classification problem where the correct class is the positive pair. The model must assign high similarity to the positive pair relative to all negatives. If we look at the loss equation, we see that if the positive pair (numerator) has a high similarity and/or the negative pairs (denominator) has low similarities, the loss will be lower, thus pushing the neural network optimization to create similar embeddings for positive pairs and different embeddings for the negative pairs.

Python
import torch
import torch.nn.functional as F

def contrastive_loss(z_i, z_j, temperature=0.5):
    """
    NT-Xent loss for contrastive learning.
    z_i, z_j: embeddings of positive pairs [batch_size, feature_dim]
    """
    batch_size = z_i.shape[0]

    # Normalize embeddings
    z_i = F.normalize(z_i, dim=1)
    z_j = F.normalize(z_j, dim=1)

    # Concatenate to get all 2N samples
    z = torch.cat([z_i, z_j], dim=0)

    # Compute similarity matrix [2N, 2N]
    similarity = torch.mm(z, z.T) / temperature

    # Labels: positive pair for sample i is at index i + batch_size
    labels = torch.cat([
        torch.arange(batch_size) + batch_size,
        torch.arange(batch_size)
    ])

    # Mask out self-similarity
    mask = torch.eye(2 * batch_size, dtype=torch.bool)
    similarity = similarity.masked_fill(mask, -1e9)

    return F.cross_entropy(similarity, labels)

This code implements the NT-Xent loss used in SimCLR. The function first normalizes both embedding sets so that dot products become cosine similarities. It then concatenates the embeddings and computes a full similarity matrix. The key step is creating labels that identify positive pairs: for sample i in the first half, its positive is at index i + batch_size in the second half. The diagonal is masked to prevent self-matching. Finally, cross-entropy loss encourages the model to assign the highest similarity score to the correct positive pair.

Key Contrastive Learning Methods Across Domains

Computer Vision

MethodYearKey InnovationPositive PairsNegatives Source
SimCLR [1] (Google)2020Strong augmentations, large batchesTwo augmented viewsOther images in batch
MoCo [2] (Meta)2020Momentum encoder, dynamic queueTwo augmented viewsQueue of past embeddings
BYOL [5] (DeepMind)2020No negatives neededTwo augmented viewsNone (predictor network)
SwAV [6] (Meta)2020Cluster assignmentMulti-crop viewsCluster prototypes
Title: Methods in Contrastive Learning for Computer Vision
Source: AIML.com research

SimCLR demonstrated that the composition of data augmentations is critical. Random cropping combined with color distortion provides a strong learning signal. The method requires large batch sizes (4096+) to provide sufficient negatives, which demands significant GPU memory.

MoCo addresses the batch size limitation by maintaining a momentum-updated encoder and a queue of negative embeddings. This decouples the number of negatives from batch size, enabling effective training on standard hardware. The momentum encoder updates slowly, ensuring consistent representations in the queue.

BYOL surprised the field by achieving strong results without any negative samples. Instead, it uses a predictor network that prevents the model from collapsing to trivial solutions. This suggests that the role of negatives may be more subtle than initially understood.

Natural Language Processing

MethodYearKey InnovationPositive PairsNegatives Source
SimCSE [3] (Princeton)2021Dropout as augmentationSame sentence, different dropoutOther sentences in batch
DeCLUTR [7] (U of Toronto)2020Span samplingOverlapping text spansNon-overlapping spans
E5 [8] (Microsoft)2022Multi-task contrastiveWeak supervision pairsBatch negatives
Title: Methods in contrastive learning for natural language processing
Source: AIML.com research

SimCSE revealed a remarkably simple insight: passing the same sentence through a transformer twice with different dropout masks creates effective positive pairs. The dropout acts as minimal data augmentation, producing slightly different representations of semantically identical content. The unsupervised version achieves 76.3% Spearman correlation on semantic textual similarity benchmarks, competitive with supervised methods.

Title: Diagram from the SimCSE paper showing the methodology of using dropout masks to create positive pairs.
Source: Gao et. al.
Title: Diagram from the SimCSE paper showing the methodology of using dropout masks to create positive pairs.
Source: Gao et. al.

This simplicity is significant. Unlike computer vision, where augmentations like cropping and color changes have clear semantic justification, text augmentations (back-translation, word deletion) often degrade meaning. SimCSE sidesteps this problem entirely by using the model’s own stochasticity.

DeCLUTR (Deep Contrastive Learning for Unsupervised Textual Representations) introduced a span-sampling approach where positive pairs are created by taking two overlapping, but not identical, text spans from the same document. This method leverages the natural structure of documents: nearby sentences and paragraphs tend to share semantic content. By contrasting these positive span pairs against non-overlapping spans from the document, DeCLUTR effectively learns local and global context, resulting in highly effective general-purpose text embeddings.

E5 (EmbEddings from bidirEctional Encoder rEpresentations) is a family of highly performant text embedding models. While based on contrastive learning, E5 differs by incorporating weak supervision from naturally occurring text pairs found in publicly available datasets (like question-answer pairs or product title-description pairs). The model is trained using a multi-task objective that combines the standard InfoNCE loss with other objectives, leading to state-of-the-art results across a wide range of text retrieval and semantic similarity benchmarks.

Multimodal Learning

MethodYearKey InnovationPositive PairsApplication
CLIP [4] (OpenAI)2021Image-text alignmentImage-caption pairsZero-shot classification
ALIGN [9] (Google)2021Scale (1B+ pairs)Noisy image-text pairsRetrieval
SigLIP [10] (Google)2023Sigmoid lossImage-text pairsEfficient training
Title: Methods in multimodal (vision-language) learning
Source: AIML.com research

CLIP learns to align images and text in a shared embedding space by training on 400 million image-text pairs from the internet. Given an image and a set of text descriptions, CLIP computes similarity scores and selects the best match.

Title: Diagram from the CLIP paper showcasing the approach of training an image encoder and a text encoder
Source: Alec Radford et. al.
Title: Diagram from the CLIP paper showcasing the approach of training an image encoder and a text encoder
Source: Alec Radford et. al.

This enables zero-shot image classification: to classify an image, construct text prompts for each class (“a photo of a dog”, “a photo of a cat”) and select the class with highest similarity to the image. CLIP achieves strong performance on many datasets without ever training on their specific labels. CLIP also powers text-to-image generation. Models like DALL-E and Stable Diffusion originally used CLIP to guide image generation toward matching text descriptions.

ALIGN (A Large-scale ImaGe-Nose-Text) demonstrated the power of scale in multimodal contrastive learning. Like CLIP, it aligns image and text embeddings but was trained on an unprecedented dataset of over 1 billion noisy image-text pairs. The study found that sheer data volume, even with less stringent data filtering, could compensate for complex modeling choices, achieving high performance on retrieval tasks and emphasizing the data-centric aspect of self-supervised learning.

SigLIP (Sigmoid Loss for Language-Image Pre-Training) introduced an alternative to the standard InfoNCE/NT-Xent loss function, opting instead for a simpler pairwise sigmoid loss. This change eliminated the need for temperature scaling and large batch sizes typically required by the softmax-based contrastive loss, resulting in more stable and efficient training while achieving competitive performance on vision-language tasks.

Applications of Contrastive Learning

Contrastive learning has found applications across machine learning.

In image classification, models pre-trained with SimCLR or MoCo match ImageNet-supervised pre-training when fine-tuned on downstream tasks. This is significant because it eliminates the need for large labeled datasets during pre-training.

In semantic search, contrastive embeddings enable finding similar documents, images, or products. Given a query, compute its embedding and retrieve items with high cosine similarity. SimCSE and E5 embeddings power search systems across many domains.

In recommendation systems, contrastively learned user and item embeddings enable similarity-based recommendations. The approach naturally handles cold-start problems since new items can be embedded without retraining.

In text-to-image generation, CLIP guides diffusion models by scoring how well generated images match text prompts. This enables models like Stable Diffusion to produce images from arbitrary text descriptions.

Summary

Contrastive learning is a self-supervised approach that teaches models to build robust, generalized representations by comparing different views of the same data (positives) against views of other data points (negatives), ensuring that similar data clusters together in the embedding space.

Contrastive learning succeeds for several interconnected reasons. Firstly, it learns invariances. By treating augmented views as positive pairs, the model learns features that remain stable across transformations. An image representation that survives cropping, color shifting, and blurring captures semantic content rather than superficial details. It also captures semantic similarity. The contrastive objective naturally clusters semantically related items together in embedding space. Images of dogs end up near other dog images, separate from cats, without explicit labels.

Importantly, contrastive learning scales with data and produces transferable representations. Unlike supervised learning, contrastive methods can leverage vast amounts of unlabeled data. CLIP trained on 400 million image-text pairs; this scale would be prohibitively expensive to label manually. Pre-trained contrastive models fine-tune effectively on downstream tasks with limited labeled data, beating models trained exclusively on task-specific, labeled data. The learned features generalize because they capture fundamental structure rather than task-specific patterns, thus enabling applications in image classification, semantic search, recommendation systems and image generation.

Video Explanations

  • This video, “Can Contrastive Learning Work? –  SimCLR Explained” by Boris Meinardus takes a look at the SimCLR paper and the details needed to actually make it work. (Runtime: 9 mins)
YouTube video
“Can Contrastive Learning Work? –  SimCLR Explained” by Boris Meinardus
  • This video, “OpenAI CLIP: Connecting Text and Images (Paper Explained)” by Yannik Kilcher thoroughly goes through the CLIP paper by OpenAI. (Runtime: 48 mins)
YouTube video
“OpenAI CLIP: Connecting Text and Images (Paper Explained)” by Yannik Kilcher

References

  1. Chen, T., Kornblith, S., Norouzi, M., & Hinton, G. (2020). “A Simple Framework for Contrastive Learning of Visual Representations.” ICML 2020. arXiv:2002.05709
  2. He, K., Fan, H., Wu, Y., Xie, S., & Girshick, R. (2020). “Momentum Contrast for Unsupervised Visual Representation Learning.” CVPR 2020. arXiv:1911.05722
  3. Gao, T., Yao, X., & Chen, D. (2021). “SimCSE: Simple Contrastive Learning of Sentence Embeddings.” EMNLP 2021. arXiv:2104.08821
  4. Radford, A., et al. (2021). “Learning Transferable Visual Models From Natural Language Supervision.” ICML 2021. arXiv:2103.00020
  5. Grill, J.-B., et al. (2020). “Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning.” NeurIPS 2020. arXiv:2006.07733
  6. Caron, M. et. al. (2020). “Unsupervised Learning of Visual Features by Contrasting Cluster Assignments.” NeurIPS 2020. arXiv:2006.09882
  7. Giorgi, J., et al. (2020). “DeCLUTR: Deep Contrastive Learning for Unsupervised Textual Representations.” ACL2021. arXiv:2006.03659
  8. Wang, L., et. al. (2021). “Text Embeddings by Weakly-Supervised Contrastive Pre-training.” ArXiv:2212.03533
  9. Jia, C., et al. (2021). “Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision.” ICML 2021. arXiv:2102.05918
  10. Zhai, X., et al. (2023). “Sigmoid Loss for Language-Image Pre-Training.” NeurIPS 2023. arXiv:2310.05730
  11. Lilian Weng. “Contrastive Representation Learning” Lil’Log, 2021.

Author

Help us improve this post by suggesting in comments below:

– modifications to the text, and infographics
– video resources that offer clear explanations for this question
– code snippets and case studies relevant to this concept
– online blogs, and research publications that are a “must read” on this topic

Leave the first comment

Partner Ad
Find out all the ways that you can
Contribute