- Introduced by
- Gao, Yao & Chen (SimCSE, 2021); Khosla et al. (Supervised Contrastive, 2020)
- Year
- 2020–2021
- Type
- Self-supervised / supervised representation learning
What does it do?
Contrastive learning for NLP is a representation-learning approach that trains a text encoder by pulling together the embeddings of similar text pairs and pushing apart those of dissimilar pairs.
SimCSE (Gao et al., 2021) is the reference method in this family for sentence embeddings, and Supervised Contrastive Learning (Khosla et al., 2020) is a related formulation that uses label information. The unsupervised variant needs no labels, which makes it useful when annotated data are scarce.
The intuition behind the method
Imagine showing a model many pairs of sentences and telling it which ones mean the same thing and which do not. Similar pairs are pulled together in the embedding space and dissimilar pairs are pushed apart. The model does not learn a fixed set of categories; it learns from the relationships between pairs. After training, sentences with similar meanings tend to lie near one another, including sentences that did not appear in training. How well this works depends heavily on which pairs the model is shown as similar.
History
Contrastive objectives were applied to visual representation learning before they reached NLP; MoCo and SimCLR are commonly cited examples in computer vision. Khosla et al. (2020) introduced Supervised Contrastive Learning at NeurIPS, a formulation that uses label information. Gao et al. (2021) introduced SimCSE at EMNLP, showing that dropout-based positives can yield strong sentence embeddings on STS benchmarks. SimCSE and its supervised variant became influential reference points for later sentence-embedding work.
When to use it
Contrastive learning is a reasonable choice when you need sentence or document embeddings for similarity-based tasks and have a corpus of raw text but few or no labels, in which case the unsupervised SimCSE variant applies. It is also suitable when labelled sentence pairs such as NLI data are available, favouring the supervised variant. Typical uses are semantic search, paraphrase detection and clustering. Useful corpus size depends on the task and domain; check embedding quality on a held-out STS-style evaluation before relying on a small corpus. A GPU is strongly recommended. Do not use it when no meaningful positive-pair signal can be defined, either through augmentation or labelled entailment. If your task is a standard classification problem with labelled examples, a supervised classifier on top of a pretrained encoder may be more direct. Key assumptions: the unsupervised variant assumes that dropout noise leaves sentence meaning unchanged, so the similarity it learns is mainly invariance to surface perturbation. The quality of the result is bounded by how well the pretrained encoder already represents meaning. STS Spearman correlation measures agreement with human similarity judgements; it is a proxy for, not a guarantee of, performance on a specific downstream task, which should be evaluated directly.
Limitations and considerations
- GPU hardware is strongly recommended, and training on CPU becomes impractical for corpora of even moderate size.
- In the unsupervised variant, the only positive signal is dropout noise on a single sentence, so the learned similarity reflects surface-level invariance more than paraphrase-level meaning. Its benefit therefore depends on how the pretrained encoder already represents meaning.
- In-batch negatives tie the strength of the contrastive signal to batch size: small batches provide few negatives, which can weaken the signal and slow convergence.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- The unsupervised variant needs no labelled data: positive pairs are created by applying dropout twice to the same sentence, so any raw text collection can serve as training data.
- Because negatives come from the other sentences in the same batch, the method needs no separate negative-mining step, which keeps the training pipeline simple.
- Embeddings learned this way can be evaluated directly on STS benchmarks, giving a standard intrinsic check before use in a downstream task.
Applications
- Semantic search and information retrieval, where documents and queries are embedded in a shared space for nearest-neighbour retrieval.
- Paraphrase and duplicate detection, identifying semantically equivalent sentences across large text collections.
- Text clustering and topic discovery, grouping documents by semantic proximity without predefined labels.
- Retrieval-augmented generation (RAG), supplying passage embeddings for the retrieval component of generative systems.
- Cross-lingual transfer, where multilingual contrastive models are used to align embeddings across languages for retrieval.
How it works
How it works
Training data are assembled as pairs. In the unsupervised SimCSE setting, one sentence is passed through the encoder twice with different dropout masks, and the two resulting vectors form a positive pair. In the supervised SimCSE setting, natural language inference data supply entailment pairs as positives and contradiction pairs as hard negatives. The choice of pairs determines what the encoder is trained to treat as similar, so it has a large effect on the final embeddings.
Each sentence in a pair is fed through a pretrained transformer encoder, typically BERT or a variant. A fixed-length vector is read from the [CLS] token or obtained by mean pooling over token representations. Both sentences in a batch share the same encoder weights, so the model must produce embeddings that reflect meaning rather than surface form. A projection head may be added during training and removed at inference.
The NT-Xent (normalised temperature-scaled cross-entropy) loss is computed over all pairs in a mini-batch. For each anchor sentence, the loss raises the cosine similarity to its positive counterpart and lowers it to the other sentences in the batch, which serve as in-batch negatives. The temperature hyperparameter controls how strongly the loss penalises nearby negatives. In the supervised SimCSE variant, labelled contradiction pairs are added as explicit hard negatives. The full objective, with the temperature term and the batch-level negative set written out, is given in Gao et al. (2021).
The trained encoder is benchmarked on semantic textual similarity (STS) tasks by computing the Spearman correlation between embedding cosine similarities and human similarity judgements. STS-B and SICK-R are the standard benchmarks. Downstream tasks such as natural language inference or information retrieval can be used as complementary checks. A higher Spearman correlation indicates closer agreement with human judgements of sentence similarity.
Common pitfalls
- Treating every other sentence in a batch as a true negative can introduce false negatives, because two semantically similar sentences may land in the same batch and be pushed apart. Deduplication and careful batch construction reduce this risk.
- Applying an encoder trained on one domain (for example news text) directly to a very different domain (for example clinical notes) without fine-tuning often yields weaker embeddings.
- Setting the temperature without checking it: a high temperature makes the loss too uniform across negatives, while a low one concentrates training on the hardest negatives. It should be tuned against a held-out STS benchmark.
- Keeping the projection head at inference time. It is a training artefact and should be discarded before the embeddings are used downstream.
Frequently asked questions
What is the difference between the unsupervised and supervised SimCSE variants?
In the unsupervised variant, a sentence is passed through the encoder twice with different dropout masks to form a positive pair, so no labels are needed. In the supervised variant, natural language inference entailment pairs serve as positives and contradiction pairs as hard negatives. In the SimCSE work, the supervised variant performs better on STS benchmarks, which is consistent with the stronger training signal from hard negatives.
How many examples do I need to train a contrastive model?
No fixed minimum applies to this method; a workable corpus size depends on the task and domain, and useful embedding quality generally requires substantial training text. The unsupervised approach can use any raw text, so data collection is simpler; the supervised approach needs labelled sentence pairs, which are more costly to obtain.
Do I need to train from scratch or can I fine-tune an existing model?
Fine-tuning a pretrained transformer, such as BERT or a sentence-transformer checkpoint, with a contrastive loss is usually faster than training from scratch. The pretrained encoder already captures much of the language structure, and contrastive training mainly reshapes the geometry of the embedding space.
How do I evaluate whether my embeddings are good?
Spearman correlation on semantic textual similarity benchmarks (STS-B, SICK-R) is the standard intrinsic evaluation. For application quality, measure performance on your actual task, for example retrieval precision at k, clustering silhouette score, or accuracy of a linear probe trained on frozen embeddings.
Related methods
Sources
Gao, T., Yao, X., & Chen, D. (2021). SimCSE: Simple Contrastive Learning of Sentence Embeddings. Proceedings of EMNLP 2021.
Open publication referenceKhosla, P., et al. (2020). Supervised Contrastive Learning. Advances in Neural Information Processing Systems (NeurIPS) 33.
Open publication reference