πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Self-Supervised Learning: Pretraining Without Labels

🟒 Free Lesson

Self-Supervised Learning: Pretraining Without Labels

Human children learn language from exposure, not from flashcards. A model that learns the same way β€” from raw text or images with no human labels at all β€” is doing self-supervised learning. The supervisory signal is manufactured from the data itself: hide part of the input and predict it, or force two views of the same input to agree while pushing different inputs apart. Every major representation-learning breakthrough of the last decade, from BERT to GPT to SimCLR to DINO, is a variant of that trick.

The economic argument is decisive. Labelled datasets are expensive and bounded; unlabeled data is cheap and effectively infinite. Self-supervised pretraining spends GPU time on the abundant resource and produces representations that a small labeled fine-tune can then steer to a specific task. Almost every system you build on top of a foundation model inherits its quality from a self-supervised objective chosen years earlier.

This lesson covers the two great families of self-supervised objectives β€” predictive and contrastive β€” walks through masked language modeling and SimCLR with working code, and explains how to evaluate representations honestly so you know whether pretraining actually helped.

The label bottleneck

Supervised learning has a structural ceiling: performance scales with labeled examples, and labeling does not scale. Worse, labels are a channel of human bias β€” whoever wrote the labeling guideline defined what the model can learn. Self-supervised learning removes that channel. The model's target is derived mechanically from the input, so the objective is as clean as the data itself, and the only quality lever is corpus curation.

The trade-off is that a self-supervised objective is a proxy. Predicting masked tokens is not the same as answering questions; agreement between augmented image views is not object detection. The pretraining objective must be close enough to downstream structure that the learned features transfer. This is why the design of pretext tasks is an active research area rather than an afterthought.

Two families: predict and contrast

FamilySignal constructionCanonical modelsStrengthsWeaknesses
Predictive (autoregressive)Predict the next tokenGPT series, LLaMAUnbounded task coverage, simple objectiveLeft-to-right context only
Predictive (masked)Predict hidden tokens from both sidesBERT, RoBERTa, T5Bidirectional context, strong for understandingPretrain–finetune mismatch
ContrastivePull augmented views together, push others apartSimCLR, MoCo, CLIPExcellent representations per computeSensitive to augmentation choice
Non-contrastiveSame as contrastive, no negativesBYOL, DINO, iBOTNo large batches needed, stableRequires momentum or stop-gradient tricks

Predictive objectives teach the model the structure of the data distribution directly: to predict a masked word, it must understand grammar, facts, and discourse around it. Contrastive objectives teach similarity structure: two crops of the same photo are the same object despite different pixels, while a photo of a dog and a photo of a bus are not. The families are complementary β€” many modern systems combine them, using contrastive loss for images and next-token prediction for text.

Masked language modeling from scratch

BERT's objective is almost embarrassingly simple: select 15% of tokens, replace most with a mask token, and train the model to recover them from context. The subtlety is in the details β€” which fraction to mask, and how to perturb the chosen tokens.

python
import torch
import torch.nn as nn
from transformers import AutoModel, AutoTokenizer

class MaskedLMPretrainer:
    def __init__(self, model_name: str, mask_prob: float = 0.15):
        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        self.model = AutoModel.from_pretrained(model_name)
        self.mask_prob = mask_prob

    def make_batch(self, texts):
        enc = self.tokenizer(texts, truncation=True, padding=True,
                             return_tensors="pt")
        input_ids = enc["input_ids"].clone()
        labels = input_ids.clone()

        probability = torch.full(input_ids.shape, self.mask_prob)
        masked = torch.bernoulli(probability).bool()
        labels[~masked] = -100

        chosen = masked & torch.rand(input_ids.shape).lt(0.8)
        input_ids[chosen] = self.tokenizer.mask_token_id

        replace_random = masked & ~chosen & torch.rand(input_ids.shape).lt(0.5)
        random_tokens = torch.randint(
            len(self.tokenizer), input_ids.shape, dtype=torch.long
        )
        input_ids[replace_random] = random_tokens[replace_random]

        return {
            "input_ids": input_ids,
            "attention_mask": enc["attention_mask"],
            "labels": labels,
        }

pretrainer = MaskedLMPretrainer("bert-base-uncased")
batch = pretrainer.make_batch(["The capital of France is Paris"])

The 80/10/10 convention β€” 80% of chosen tokens become the mask, 10% stay unchanged, 10% get a random token β€” prevents a train-time mismatch where the model only ever sees the mask symbol but at fine-tuning time sees ordinary text. Leaving 10% unchanged also forces the model to use context rather than blindly copying, because it cannot know which positions were tampered with. The label value of βˆ’100 is PyTorch's ignore index, so unmasked positions contribute nothing to the loss.

Contrastive learning with SimCLR

Contrastive learning builds its own supervision from augmentation. Take an image, produce two independently augmented views of it, encode both, and optimize an objective that makes the two embeddings close while every other item in the batch serves as a negative. The encoder learns invariances you encode in the augmentation policy: crops, color jitter, and grayscale blur mean "these transformations do not change identity."

python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as T

class SimCLR:
    def __init__(self, encoder: nn.Module, feature_dim: int,
                 projection_dim: int = 128, temperature: float = 0.5):
        self.encoder = encoder
        self.projector = nn.Sequential(
            nn.Linear(feature_dim, 256),
            nn.ReLU(),
            nn.Linear(256, projection_dim),
        )
        self.temperature = temperature
        self.augment = T.Compose([
            T.RandomResizedCrop(224),
            T.RandomHorizontalFlip(),
            T.ColorJitter(0.8, 0.8, 0.8, 0.2),
            T.RandomGrayscale(p=0.2),
            T.ToTensor(),
        ])

    def nt_xent(self, z_a: torch.Tensor, z_b: torch.Tensor) -> torch.Tensor:
        n = z_a.shape[0]
        z = F.normalize(torch.cat([z_a, z_b]), dim=1)
        sim = torch.mm(z, z.t()) / self.temperature
        sim.fill_diagonal_(float("-inf"))
        targets = torch.cat([
            torch.arange(n, 2 * n),
            torch.arange(0, n),
        ]).to(z.device)
        return F.cross_entropy(sim, targets)

    def train_step(self, images: torch.Tensor) -> torch.Tensor:
        view_a = torch.stack([self.augment(img) for img in images])
        view_b = torch.stack([self.augment(img) for img in images])
        h_a, h_b = self.encoder(view_a), self.encoder(view_b)
        return self.nt_xent(self.projector(h_a), self.projector(h_b))

simclr = SimCLR(encoder, feature_dim=512)
loss = simclr.train_step(images)

Batch size is not a convenience parameter here β€” it defines the negative set. SimCLR's original results required batch sizes of 1024–8192 to supply enough negatives; small batches starve the objective and representations collapse. MoCo solved this with a momentum-updated queue of negatives, letting smaller batches work. Temperature controls how hard the loss penalizes confusing negatives with positives: lower temperatures sharpen the distribution and generally improve representation quality but make training less stable.

Text contrastive objectives

The same recipe transfers to text, where the two views come from paraphrase pairs, back-translation, dropout noise, or sentence cropping rather than image augmentation. This is the mechanism behind sentence-transformer models and, in its paired image-text form, behind CLIP:

python
import torch
import torch.nn as nn
import torch.nn.functional as F

class TextContrastiveTrainer:
    def __init__(self, encoder, tokenizer, temperature: float = 0.05):
        self.encoder = encoder
        self.tokenizer = tokenizer
        self.temperature = temperature

    def embed(self, texts):
        enc = self.tokenizer(texts, padding=True, truncation=True,
                             return_tensors="pt")
        with torch.no_grad():
            hidden = self.encoder(**enc).last_hidden_state[:, 0, :]
        return F.normalize(hidden, dim=1)

    def loss(self, pairs_a, pairs_b):
        z_a, z_b = self.embed(pairs_a), self.embed(pairs_b)
        logits = torch.mm(z_a, z_b.t()) / self.temperature
        targets = torch.arange(len(z_a), device=logits.device)
        return (F.cross_entropy(logits, targets)
                + F.cross_entropy(logits.t(), targets)) / 2

trainer = TextContrastiveTrainer(model, tokenizer)
loss = trainer.loss(paraphrases_a, paraphrases_b)

Each row index is its own positive: sentence i in group A is treated as a paraphrase of sentence i in group B. Every other sentence in the batch is a negative. This is precisely why batch composition matters β€” random negatives that are topically unrelated make the task too easy, and hard-negative mining (sampling negatives from the same topic) is often what separates a mediocre sentence encoder from a strong one.

Evaluating representations honestly

The standard protocol is linear evaluation: freeze the pretrained encoder, train a single linear layer on the labeled task, and report the result. A strong representation scores well with a linear probe; a weak one requires a deep classifier to untangle, which would confound representation quality with model capacity. Fine-tuning the whole network gives a second number: the gap between probe and fine-tune indicates how much task-specific structure the representation lacks.

Three practical warnings. First, if your augmentation policy destroys the label β€” color jitter on a color-classification task, aggressive cropping on small objects β€” contrastive pretraining will learn exactly the wrong invariance. Second, pretraining loss going down does not imply downstream quality going up; track the linear probe throughout, not just the pretext loss. Third, when combining objectives, weight them explicitly and monitor each term separately, because one can silently dominate and turn your carefully designed multi-task pretraining into a single-task run.

Common Mistakes

Choosing augmentations that destroy the downstream signal

Fix: Audit each augmentation against the task label; keep invariances that the task actually requires.

Running contrastive learning with a small batch

Fix: Use large batches or a momentum queue β€” negatives are the objective, and few negatives means weak learning.

Judging pretraining only by pretext loss

Fix: Track a linear-probe score on a downstream set throughout pretraining; loss and transfer quality can diverge.

Masking without the 80/10/10 perturbation scheme

Fix: Mix mask, unchanged and random tokens so the model cannot exploit a mask-only artifact at fine-tuning time.

Skipping the frozen-encoder linear probe

Fix: Always report probe accuracy alongside fine-tune accuracy to separate representation quality from head capacity.

Key Takeaways

  • Self-supervised learning manufactures supervision from the data itself, removing the label bottleneck entirely.
  • Predictive objectives (next-token, masked-token) teach distributional structure; contrastive objectives teach similarity structure.
  • Masked language modeling's 80/10/10 perturbation scheme exists to avoid train–finetune mismatch.
  • In contrastive learning, batch size and augmentation policy are objective-level choices, not hyperparameter details.
  • Linear probing is the honest test of a representation; fine-tune accuracy alone conflates features with head capacity.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement