Özer Cem KELAHMETKELAHMET
Articles · Self-supervised learning

Self-supervised learning explained: masked and next-token prediction behind foundation models

Foundation models learn from trillions of tokens that nobody labelled. Self-supervised learning makes that possible by hiding part of the data and predicting it. This guide covers the objectives, the maths of perplexity and compute, and a runnable PyTorch model.

Download Markdown
At a glance
Reading time
14 min
Sections
11
Code examples
3
Tables
1
Sources
8
Published
24 Nov 2026
In 30 seconds
What changed
Hugging Face Transformers 5.24.0 is released
Why it matters
Self-supervised learning turns raw, unlabelled data into a training signal.
What to do
Run the toy model

Every large language model starts life as a guessing machine. It reads text with one piece hidden and tries to predict the missing piece. Nobody labels the data; the data labels itself, because the hidden piece is already there. This trick, called self-supervised learning, is why models can learn from trillions of words of web text, code and books instead of from the few million examples a team of annotators could ever produce.

Self-supervised learning is not limited to text. Vision models predict masked image patches, speech models predict masked audio frames, and tabular models predict masked cells. This article explains the two dominant objectives, next-token prediction and masked prediction, works through the numbers that describe pretraining, runs a tiny language model in PyTorch, and shows where the method breaks.

What happened

Hugging Face Transformers 5.24.0 is released (21 November 2026)

Transformers 5.24.0 reached PyPI on 21 November 2026, a week after 5.23.0 on 13 November. Transformers is the library most teams use to load pretrained causal and masked language models, so its release cadence sets how quickly new pretrained checkpoints become usable in standard code.

PyTorch 2.15 is the current training framework release (28 October 2026)

PyTorch 2.15.0 was uploaded to PyPI on 28 October 2026. The tiny model below uses only stable building blocks, nn.TransformerEncoder with a causal mask and F.cross_entropy, and runs on it unchanged on a laptop CPU in a few seconds.

The idea: let the data supply its own labels

Supervised learning needs pairs of input and answer made by people. Self-supervised learning builds the pairs automatically by hiding part of each example. The model sees the visible part and is trained to reconstruct the hidden part. To do that well across billions of examples, it has to learn grammar, facts, style, the structure of code and much else, because all of it helps predict what comes next.

A good analogy is a crossword. Nobody tells you the theme, but filling in thousands of blanks teaches you vocabulary, spelling and trivia. The blanks are the training signal.

There are two main ways to hide data:

  • Next-token prediction (causal or autoregressive): read tokens left to right and predict each next token from all earlier ones. GPT-style models, Llama, Claude, Gemini and nearly all chat models are pretrained this way.
  • Masked prediction: hide a random subset of positions anywhere in the input and predict them using context on both sides. BERT made this standard for text, and masked autoencoders brought it to images.

A third family, contrastive and joint-embedding learning, predicts representations instead of raw tokens. It is covered in its own article on this site.

The next-token objective and its numbers

Given a sequence of tokens x_1, ..., x_T, a causal model factorises the probability of the whole sequence as a product of conditionals:

p(x_1, ..., x_T) = Π_t p(x_t | x_1, ..., x_{t−1})

Training minimises the average negative log-likelihood, which is the cross-entropy between the model's predicted distribution and the actual next token:

L = −(1/T) Σ_t log p_θ(x_t | x_{<t})

Two numbers make this concrete.

The uniform baseline. A model that knows nothing gives every token in a vocabulary of size V the same probability 1/V, so its loss is ln V. With a 50,000-token vocabulary that is ln 50,000 = 10.82 nats per token. Every bit of learning shows up as a drop below that line.

Perplexity. Perplexity is exp(L). A loss of 2.0 nats per token gives a perplexity of e² = 7.39, which means the model is as uncertain as if it were choosing uniformly among about 7.4 tokens at each step. Lower is better, but perplexities are only comparable between models that use the same tokenizer, because a token means something different in each vocabulary. The tokenisation simulation shows why the same text becomes different token counts.

Causal masking is what makes this work inside a transformer. Every position computes attention over all positions, but a triangular mask blocks attention to later tokens, so position t cannot peek at the answer. One forward pass therefore produces T predictions and T training signals at once, which is why next-token pretraining is so efficient. The attention simulation shows the mask in action.

Masked prediction for text and images

BERT, published by Google in 2018, chose 15 percent of token positions in each input. Of those, 80 percent were replaced with a special [MASK] token, 10 percent with a random token and 10 percent left unchanged. The model predicted the original token at all chosen positions. The random and unchanged cases stop the model from learning that only [MASK] positions matter, since [MASK] never appears when the model is used later.

The loss is the same cross-entropy, but computed only over the masked set M:

L_MLM = −(1/|M|) Σ_{i in M} log p_θ(x_i | x_visible)

Masked models see context on both sides, which makes them strong encoders for classification, retrieval and embeddings. They are not natural text generators, because they were never trained to produce text left to right.

Images carry far more redundancy than text. Masked autoencoders (MAE), from Meta in 2021, hide 75 percent of image patches and reconstruct the missing pixels from the visible quarter. Hiding so much forces the model to learn shapes and objects rather than copying neighbouring pixels. Other vision methods, such as DINOv2 and I-JEPA, predict features of hidden regions instead of pixels, which avoids wasting capacity on texture details.

Table 1. Masked prediction for text and images
Objective Hides Predicts Sees context Typical models Best for
Next-token Everything after t Next token Left only GPT family, Llama, Claude Generation, chat, code
Masked token About 15% of tokens Original tokens Both sides BERT, RoBERTa Encoders, embeddings
Masked image 75% of patches Pixels Visible patches MAE Vision backbones
Feature prediction Image regions Target embeddings Visible regions DINOv2, I-JEPA Vision features

How much data and compute pretraining needs

Self-supervised objectives can absorb almost unlimited data, so the question becomes how to spend a compute budget. A widely used approximation says training a dense transformer costs about C ≈ 6 · N · D floating-point operations, where N is the number of parameters and D the number of training tokens. The factor 6 counts roughly two operations per parameter per token for the forward pass and four for the backward pass.

DeepMind's Chinchilla study in 2022 found that, for a fixed compute budget, parameters and tokens should grow roughly in proportion, at about 20 tokens per parameter. A 7-billion-parameter model would then want about 140 billion tokens, which costs about 6 × 7×10⁹ × 1.4×10¹¹ ≈ 5.9×10²¹ FLOPs. In practice, teams now train far beyond that ratio on purpose. Meta reported pretraining Llama 3 on over 15 trillion tokens, because a smaller model trained longer is cheaper to serve. The scaling laws simulation and the data pipeline simulation let you explore these trade-offs.

Runnable code: a tiny next-token model in PyTorch

The script trains a two-layer causal transformer on characters of a short repeated text. The labels are simply the inputs shifted by one position, which is the whole idea of self-supervision in one line. At the end it shows BERT-style corruption on the same data.

import math, torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)
text = ("the cat sat on the mat. the dog sat on the log. "
        "a cat and a dog sat together on the mat by the log. ") * 40
chars = sorted(set(text)); V = len(chars)
stoi = {c: i for i, c in enumerate(chars)}
data = torch.tensor([stoi[c] for c in text])
split = int(0.9 * len(data)); train, val = data[:split], data[split:]
T, D = 32, 64

class TinyLM(nn.Module):
    def __init__(self):
        super().__init__()
        self.tok = nn.Embedding(V, D); self.pos = nn.Embedding(T, D)
        layer = nn.TransformerEncoderLayer(D, nhead=4, dim_feedforward=128, batch_first=True, dropout=0.0)
        self.body = nn.TransformerEncoder(layer, num_layers=2)
        self.head = nn.Linear(D, V)
    def forward(self, x):
        h = self.tok(x) + self.pos(torch.arange(x.size(1)))
        mask = nn.Transformer.generate_square_subsequent_mask(x.size(1))   # causal: no peeking ahead
        return self.head(self.body(h, mask=mask, is_causal=True))

def batch(src, n=32):
    ix = torch.randint(len(src) - T - 1, (n,))
    x = torch.stack([src[i:i + T] for i in ix]); y = torch.stack([src[i + 1:i + T + 1] for i in ix])
    return x, y                                                   # labels = inputs shifted by one

model = TinyLM(); opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
print(f"vocab {V}, uniform-guess loss ln(V) = {math.log(V):.3f}")
for step in range(301):
    x, y = batch(train)
    loss = F.cross_entropy(model(x).reshape(-1, V), y.reshape(-1))
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 100 == 0:
        with torch.no_grad():
            xv, yv = batch(val)
            vl = F.cross_entropy(model(xv).reshape(-1, V), yv.reshape(-1)).item()
        print(f"step {step:3d} train loss {loss.item():.3f} val loss {vl:.3f} val perplexity {math.exp(vl):.2f}")

x, _ = batch(train, n=1)                                          # BERT-style corruption
sel = torch.rand(x.shape) < 0.15
r = torch.rand(x.shape)
corrupted = x.clone()
corrupted[sel & (r < 0.8)] = V                                    # 80% -> [MASK] id
rand_pos = sel & (r >= 0.8) & (r < 0.9)                           # 10% -> random token
corrupted[rand_pos] = torch.randint(V, (int(rand_pos.sum()),))
print("positions chosen for prediction:", int(sel.sum()), "of", x.numel())

Output on PyTorch 2.15.0 (CPU):

vocab 17, uniform-guess loss ln(V) = 2.833
step   0 train loss 2.999 val loss 2.572 val perplexity 13.10
step 100 train loss 0.126 val loss 0.122 val perplexity 1.13
step 200 train loss 0.089 val loss 0.090 val perplexity 1.09
step 300 train loss 0.075 val loss 0.076 val perplexity 1.08
positions chosen for prediction: 9 of 32

The vocabulary has 17 characters, so a uniform guess scores ln 17 = 2.833. The first step is slightly worse than uniform because the random weights are confidently wrong. After 300 steps validation perplexity is 1.08: the model is almost certain of every next character. That is only possible because the text repeats, so the model can memorise it. Real pretraining data never repeats like this, and real losses stay far above zero because language is genuinely uncertain. The point of the toy is the mechanics: shifted labels, a causal mask and cross-entropy are the entire objective.

What goes wrong in practice

Data quality dominates. The objective rewards predicting whatever is in the data, including spam, boilerplate and toxic text. Pretraining pipelines spend enormous effort on filtering, deduplication and mixing.

Duplicates cause memorisation. Repeated documents get memorised and can be reproduced word for word, which creates privacy and copyright risk and wastes compute. Near-duplicate removal is standard.

Benchmark contamination. If test questions appear in the pretraining data, later evaluation scores are inflated. Teams scan for overlap, but it is hard to rule out fully.

Low perplexity is not usefulness. A pretrained model predicts text well but does not follow instructions reliably. Supervised fine-tuning and preference optimisation turn it into an assistant.

Loss spikes and instability. Large runs can diverge suddenly. Learning-rate warm-up, gradient clipping, careful initialisation and restarting from checkpoints are routine defences.

How it is used in today's models

Every modern foundation model begins with self-supervised pretraining. Chat models use next-token prediction over mixtures of web text, code, books, mathematics and multilingual data, then continue with mid-training on higher-quality or longer documents. Embedding and retrieval models usually start from masked or causal pretraining and are then tuned with contrastive objectives. Vision encoders inside multimodal models are pretrained with masked or feature-prediction objectives, or with image and text contrastive pairs. Speech recognisers pretrain on masked audio. Tabular foundation models use masked cell prediction on large collections of tables.

The objective has stayed remarkably stable. What changes year to year is data curation, tokenizer design, architecture efficiency and how much compute is spent beyond the Chinchilla ratio.

What it means in practice

Self-supervised learning turns raw, unlabelled data into a training signal. For practitioners, it means three things. First, most of a model's knowledge comes from pretraining data, so knowing what that data contains is the best guide to what the model can and cannot do. Second, perplexity and loss are useful for comparing runs with the same tokenizer and data, not for comparing products. Third, continued pretraining on your own unlabelled domain text, with the same objective, is a practical way to adapt an open model before fine-tuning on labelled examples.

What to do now

  1. Run the toy model. Change the text to something non-repeating and watch validation loss stay well above zero.
  2. Measure against ln V. Always compare loss with the uniform baseline for your vocabulary to see how much is learned.
  3. Compare perplexity only within one tokenizer. Never compare perplexities across model families with different vocabularies.
  4. Deduplicate before training. Remove exact and near-duplicate documents to reduce memorisation and contamination.
  5. Estimate compute with 6ND. Use the formula to budget runs and to sanity-check claims about training cost.
  6. Pick the objective for the job. Use causal models for generation and masked or contrastive encoders for embeddings and classification.
  7. Consider continued pretraining. For a narrow domain with lots of unlabelled text, a short self-supervised phase can help before fine-tuning.
  8. Check for contamination. Search your pretraining or fine-tuning data for test-set overlap before trusting benchmark numbers.

Risks and open questions

Data supply is finite. High-quality human text is limited, and researchers debate how long current scaling can continue before data runs short and how much synthetic data can substitute.

Memorisation and rights. Self-supervised models can reproduce training text, which raises copyright and privacy questions that law and practice have not settled.

Objectives may be leaving value on the table. Feature-prediction methods argue that predicting raw tokens or pixels wastes capacity. Whether they will replace next-token prediction for language remains open.

Watch next: how pretraining loss curves are reported and compared across labs, discussed in this article on OpenAI's perplexity curve, and how data curation changes as tokenizers evolve, covered in this BPE explainer.

Frequently asked questions

Is self-supervised learning a kind of unsupervised learning?

It is often grouped with unsupervised learning because no human labels are needed. Technically, it trains with a supervised loss on labels created automatically from the data. That is why it can use the same tools as supervised learning, such as cross-entropy and backpropagation.

Why do chat models use next-token prediction instead of masked prediction?

Next-token prediction trains the model to generate text one token at a time, which is exactly how chat models produce answers. It also gives a training signal at every position in every sequence. Masked models are better encoders but are awkward for open-ended generation.

What does a perplexity of 7 mean?

It means the model is, on average, as uncertain as if it were choosing uniformly among seven equally likely tokens at each step. It equals a loss of ln 7, about 1.95 nats per token. It only means something relative to the same tokenizer and data.

How much data does pretraining need?

The Chinchilla analysis suggests about 20 tokens per parameter for the best loss at a fixed compute budget. Modern models train much longer than that, often on trillions of tokens, because smaller models trained longer are cheaper to run.

Can I use self-supervised learning on my own data?

Yes. Continued pretraining of an open model on your unlabelled domain text with the same next-token objective is common. For tables, images and audio, masked prediction objectives work the same way. Start with a strong pretrained checkpoint rather than training from scratch.

Summary

Self-supervised learning hides part of each example and trains a model to predict it, turning unlabelled data into supervision. Causal models minimise next-token cross-entropy, starting from a uniform loss of ln V (10.82 nats for 50,000 tokens), and perplexity exp(L) tracks progress. Masked models such as BERT predict 15 percent of tokens and MAE reconstructs 75 percent of image patches. Compute follows roughly 6ND, and Chinchilla suggests about 20 tokens per parameter, though today's models train much longer. The tiny PyTorch model showed the whole recipe: shifted labels, a causal mask and cross-entropy. See also self-supervised learning, BERT and masked autoencoders.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 24). Self-supervised learning explained: masked and next-token prediction behind foundation models. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/self-supervised-learning-masked-next-token-pretraining

BibTeX
@online{kelahmet2026self,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{Self-supervised learning explained: masked and next-token prediction behind foundation models}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/self-supervised-learning-masked-next-token-pretraining}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 24, 2026
Type to search.
    ↑↓ navigate↵ open