AI State of the Art
Fundamentals/LLM: Understanding Large Language Models/29 min
Section 50

Pre-training: Data, Objectives (CLM, MLM, Span Corruption)

Listen as a podcast →

A Child Who Reads the Entire Internet

Imagine a child given access to an infinite library (billions of books, articles, conversations, code) and told: "Read all of this, and every time we hide a word, guess it." After years of reading, this child has seen so many patterns that they can finish any sentence, in any style. They don't know why "the Earth revolves around the Sun" is true, but they know it's the most likely continuation after certain phrases. And by accumulating these predictions, they end up developing something that strangely resembles understanding.

This is exactly what pre-training an LLM is. It's the first phase of a model's life, the longest (weeks, sometimes months) and the most expensive (millions of dollars). The model ingests astronomical amounts of raw text (Wikipedia pages, GitHub code, books, forums, scientific papers) without being told "this sentence is good" or "this answer is wrong." It simply learns to guess the next word. This is called self-supervised learning: the signal that enables learning comes directly from the text itself, not from a human annotating the data.

Self-supervised, what does that mean?

In traditional supervised learning, someone labels the data by hand: "this photo is a cat," "this email is spam." It's slow, expensive, and doesn't scale to billions of examples. Self-supervised learning is clever: it creates its own labels from the text. If a sentence says "The capital of France is ___," the answer "Paris" is already there, hidden in the data. It's an elegant trick: you have an infinite dataset of (context, next word) pairs without ever asking a human to annotate anything.

The Big Question: How Exactly Does It Learn?

OK, we know the model has to "guess words." But the precise way you frame this guessing game changes everything. The training objective is the rule of the game: which words you hide, in which direction you read the sentence, and how you measure whether the model guessed correctly. There are three main types, and each produces a fundamentally different kind of model, much like a musician who trains by ear, by sight-reading, or by improvisation.

Objective 1: Causal Language Modeling, Guessing the Next Word

Causal language modeling, almost always abbreviated CLM, is the approach behind GPT, LLaMA, Mistral, Claude, virtually all of today's large models. The rule is simple: predict the next word, only looking to the left.

Sequence: "The cat eats a ___"

  • The model sees: "The", "cat", "eats", "a"
  • It must predict: "mouse" (or "treat", or "apple"...)

The word "causal" comes from the fact that information flows in only one direction: from past to future. The token at position 5 cannot see the token at position 6. This is a natural constraint: when you write a sentence, you don't yet know what comes next. This is exactly the constraint the model learns to respect.

In practice, this restriction is implemented via a causal attention mask: a triangular matrix that blocks connections to future tokens. The model literally "looks" in only one direction.

A 5 by 5 causal attention mask matrix. Rows are the querying tokens T0 to T4, columns are the tokens being attended to. The lower triangle and the diagonal hold the value 0 (attention allowed, green cells), the upper triangle holds minus infinity (attention blocked, red cells). A note points out that token T2 can only attend to T0, T1 and T2.
The causal mask in practice: each row is a token looking for information, each column a token it could consult. The red cells (minus infinity) become zero after the softmax, so token T2 only sees T0, T1 and itself. This is exactly the triangular matrix described above.Source : Modular, Build an LLM from scratch with MAX
Ilya Sutskever's Argument

The co-founder of OpenAI has often said: to perfectly predict the next word of an article about quantum physics, you need to understand quantum physics. Predicting the next token seems trivial, but pushed to the extreme with enough data, it forces the model to build an internal model of the world. Knowing that after "water boils at" comes "100 degrees" is encoding a physical fact. At the scale of trillions of tokens, the model ends up encoding phenomenal amounts of knowledge, just by playing the prediction game.

In practice, training works as follows:

  1. Raw text is split into chunks of fixed length (e.g., 4,096 tokens per chunk, sometimes 8,192 or more)
  2. Thousands of chunks are processed in parallel (this is a batch)
  3. For every position in each chunk, the model predicts the next token, a single 4,096-token chunk thus provides 4,096 training signals
  4. The error is measured (the cross-entropy loss: how far the predicted distribution is from the correct token) and weights are adjusted via backpropagation
  5. This is repeated billions of times, over trillions of tokens, for weeks

Objective 2: Masked Language Modeling, Filling in the Blanks

Masked language modeling, abbreviated MLM, is the approach behind BERT and its variants. Here, 15% of the words in a sentence are randomly hidden (that is the proportion the BERT authors settled on) and the model is asked to recover them. But this time it can look in both directions, before and after the gap.

Input: "The [MASK] eats a mouse in the [MASK]." To predict: "cat" and "attic"

The advantage is clear: seeing the full context (what comes before AND after the gap) makes the model very good at understanding the meaning of a text. To guess that the first [MASK] is "cat," it uses both "eats" (to the right) and "mouse" (even further right). This is an advantage CLM is structurally denied.

The major downside: this model cannot generate text naturally. It knows how to fill gaps, not write a story from beginning to end. Why? Because it was trained to predict missing words in a complete sentence, not to produce the next word in an unfinished sequence. The architecture itself (bidirectional attention) is not designed for sequential generation.

Why BERT Disappeared from AI Assistants

BERT (2018) dominated NLP (Natural Language Processing) for years in classification, semantic search, and text analysis. But when the goal shifted to chatbots, generation was needed, and BERT is powerless there. You can't ask it to "write a poem" because it doesn't know how to produce text token by token. That's why assistants like ChatGPT or Claude all use causal language modeling. BERT does remain widely used in production for understanding tasks: sentence embeddings, classification, and NER (Named Entity Recognition, spotting the names of people, places and organizations in a text).

Objective 3: Span Corruption, Hiding Entire Chunks

Span corruption is the approach behind T5 (Text-To-Text Transfer Transformer, the name already announces the programme, more on that below) and BART. It goes further than hiding a single word: entire spans, contiguous stretches of 3 to 5 tokens, are hidden and replaced with a single sentinel token, that is, an artificial marker saying "something is missing here" without saying what or how much. The encoder-decoder model must then regenerate the missing sequences.

Input: "The cat <X> in the garden <Y> mouse." Target: "<X> was sleeping peacefully <Y> while chasing a"

This is a significantly harder exercise than MLM: the model must not only guess which words are missing, but also how many there are (the length of the hidden span is unknown). The encoder reads the corrupted text with bidirectional attention and understands it despite the gaps. The decoder regenerates the missing spans token by token.

A four-panel comparison. Top row, BERT: the input The quick MASK MASK jumps, and two tokens predicted independently of each other, marked by two question marks. Bottom row, T5: the input The quick id_0 jumps where a whole span has been replaced by a single sentinel token, and the output id_0 brown fox generated autoregressively.
The difference between the two objectives is immediately visible. On top, BERT replaces each hidden word with a [MASK] and predicts every gap separately. Below, T5 replaces an entire span with a single sentinel token id_0: the span length disappears from the input, and the decoder has to regenerate brown fox word after word.Source : Michael Brenndoerfer, T5 Pre-training: Span Corruption and Denoising Objectives

This hybrid approach thus combines bidirectional understanding (encoder) and sequential generation (decoder). T5 pioneered the idea of unifying all NLP tasks under a single "text-to-text" format: translation, summarization, classification, everything becomes "convert this text into this result."

Why Causal Language Modeling Won

ObjectiveArchitectureDirectionGood for
CLM (next token)Decoder-onlyLeft to rightGeneration, conversation
MLM (masked)Encoder-onlyBidirectionalUnderstanding, classification
Span corruptionEncoder-decoderBothText-to-text tasks
Why CLM won: three reasons, of unequal solidity

The first is market demand: CLM lends itself naturally to text generation, and that is what users want.

The second is economic, and probably decisive: CLM needs no paired data. Any raw text is a training example, and every position in that text is one more. MLM, which predicts only 15% of tokens, mechanically extracts six to seven times less signal from the same corpus.

The third is a widely shared intuition: decoder-only models are said to have more favourable scaling curves. A caveat, though: this is not a result of the Kaplan paper, which does not compare CLM with MLM. This page attributed it there for a long time, wrongly. The comparison has since been made in other work, but it is not part of the scaling laws described here.

The Technical Tricks That Make It Work

Pre-training a modern LLM is as much an engineering feat as a research one. Here are the key techniques that make it possible.

The Learning Rate Schedule

The learning rate is the size of the step taken at each weight correction: large, and you move fast but risk overshooting the target; small, and you move surely but slowly. It is not held constant from start to finish, it follows a schedule.

You don't start at full throttle. Training uses a warmup (gradual ramp-up): during the first few thousand steps, the learning rate progressively rises from a near-zero value. Why? Because at the very beginning, gradients are unstable and overly aggressive updates can cause the model to diverge. Once the warmup is complete, the rate gradually decreases following a cosine curve until the end of training. It's like starting a car in first gear before hitting the highway, then gradually easing off the gas as you approach your destination.

Gigantic Batches

You don't process texts one by one, that would be hopelessly slow. You process millions of tokens at a time. The best-documented case is Llama 3: Meta describes an initial batch of 4 million tokens, doubled to 8 million after the first 252 billion tokens, then doubled again to 16 million after 2,900 billion.

Why grow the batch part-way through? A small batch gives a noisier signal, which helps explore the parameter space early on; a large batch gives a steadier signal, useful for fine-tuning the weights at the end.

Mixed Precision: Memory Comes at a Price

GPUs (Graphics Processing Units) have limited memory: 40 to 80 GB on the cards used for training. To fit billions of parameters, mixed precision is used: a reference copy of the weights is kept in FP32 (32 bits per number) but the forward and backward pass computations are done in BF16 (16 bits, half).

So what gets halved is not the space taken by the reference weights (that does not change) but the space taken by everything else: the intermediate activations and the gradients, which are by far the largest item during training.

Why BF16 rather than FP16? A floating-point number is described by two quantities: its range (the smallest and largest number representable) and its precision (the number of significant digits). BF16 keeps exactly the range of FP32 and gives up precision; FP16 does the opposite. In training, a tiny gradient that falls outside the range becomes zero and the information is lost, so it is better to keep the range.

Splitting the Model Across Hundreds of GPUs

A 70-billion-parameter model doesn't fit on a single GPU. The arithmetic is easy: 2 bytes per parameter at 16 bits × 70 billion = 140 GB, nearly double the 80 GB of one card, and that is before counting gradients and optimizer states. So it has to be split up, and this is a major engineering challenge:

  • Tensor parallelism: a single layer is split across multiple GPUs, each computing part of the matrices
  • Data parallelism: the whole model is replicated across multiple GPUs, each processing a different batch, then gradients are averaged
  • Pipeline parallelism: layers are distributed sequentially, like an assembly line, while one GPU processes layer 10, another processes layer 11 on the previous batch
The Astronomical Cost of Pre-training

Meta reports roughly 30.8 million H100 GPU hours for pre-training Llama 3.1 405B. Turning that into money requires an assumption about price, and this is where the figures quoted everywhere become vague: at $2 per rented H100-hour you get about $60 million; at $4, double that. The order of magnitude is therefore tens of millions, but any more precise figure depends entirely on the assumed price, and Meta, which owns its machines, does not pay that price.

That's why only a handful of organizations in the world (OpenAI, Google, Meta, Anthropic, Mistral...) pre-train a model from scratch. Everyone else starts from an existing model and adapts it via fine-tuning.

Data Quality: The Best-Kept Secret

An often underestimated aspect: the quality of pre-training data is at least as important as model size. You don't just dump "all of the Internet" into the model without filtering. Pre-training teams invest enormously in data curation: deduplication (removing duplicate texts), quality filtering (keeping well-written texts), decontamination (removing benchmarks to prevent cheating), and balancing (the right proportion of code, science, conversation, etc.). LLaMA-3 was trained on 15 trillion carefully selected tokens, that's less than what's available, but quality comes first.

What You Get, and What's Still Missing

At the end of pre-training, you have a base model (also called a "foundation model"). It's impressive at completing text coherently. Give it the beginning of a physics article, and it will continue with sentences that look like physics. Give it Python code, and it will complete it with syntactically correct code.

But if you ask it a question, it might... continue with more questions. "What is the capital of Germany?" could be followed by "What is the capital of Italy? What is the capital of Japan?" Because in its training data, lists of questions were common, and the model is just completing the most likely pattern.

The base model doesn't know how to have a conversation, follow instructions, or refuse dangerous requests. It's like a living encyclopedia that doesn't understand it's being spoken to. It's fine-tuning (and particularly alignment techniques like RLHF (Reinforcement Learning from Human Feedback) and DPO (Direct Preference Optimization)) that turns this raw encyclopedia into a useful and safe assistant.

A three-block diagram connected by arrows. Block 1, Pre-Training: an unlabeled text corpus from Common Crawl and Wikipedia feeds a decoder-only language model. Block 2, SFT: a prompt is sampled from a dataset, a human labeler writes the desired answer, and these pairs are used to fine-tune the model with supervised learning. Block 3, RLHF: a labeler ranks several model outputs, the ranking trains a reward model, and the reward model updates the policy with PPO. A bracket groups the SFT and RLHF blocks under the label Alignment.
Pre-training is only the first box in the chain. Next comes SFT, where humans write the expected answers, then alignment (RLHF), where humans rank the model outputs to train a reward model. Those last two stages are what turn a text completer into an assistant.Source : Cameron R. Wolfe, Deep (Learning) Focus
Check your understanding0 / 4

1. Why is pre-training described as self-supervised?

2. Among the reasons CLM beat MLM, which one was probably decisive?

3. Why does modern training prefer BF16 over FP16?

4. Why are evaluation benchmarks removed from the pre-training data, the decontamination step?