LLM Fundamentals · Module 02 · 8 topics

Pre-Training

Take a blank model and trillions of tokens of raw text, and grind one objective — predict the next token — until knowledge falls out. This is where almost all the capability is built and almost all the compute is spent.

01

Overview

Pre-training is one giant loop: pull a batch of text, ask the model to predict each next token, measure how wrong it was, nudge every weight to be a little less wrong. Repeat for months across thousands of GPUs. Click each stage.

Pre-training is where a model goes from random noise to something that knows physics, poetry, Python and the plot of Hamlet. It's also where ~99% of the total compute and cost is spent — post-training (Module 03) is comparatively cheap polish on top. Understanding this phase is understanding where capability actually comes from.

The astonishing part is the lack of human labels. There is no army of annotators tagging "correct answers." The supervision is the text itself: for every position, the real next token is the label, and the model is graded on how much probability it assigned to it. This is called self-supervised learning, and it's the unlock — because the entire internet becomes free training data. The loop you see below runs for hundreds of thousands of steps, each step processing millions of tokens, slowly carving knowledge into billions of weights via gradient descent.

The pre-training loop

Web text15T tokens
Batchmillions of tokens
Forwardpredict next
Losscross-entropy
Backpropupdate weights
Hover any stage. The loop runs for hundreds of thousands of steps — there is no labelled data, the text is the supervision (the next word is the answer).
02

Training Objectives & Architectural Details

The objective is cross-entropy loss on the next token: loss = −log(p), where p is the probability the model assigned to the correct word. Confident and right → tiny loss. Confident and wrong → huge loss. Drag the probability.

Every training run needs a single number to minimize, and for language models that number is cross-entropy loss. Its shape is deliberate. Because loss is −log(p), being right with high confidence costs almost nothing, while being confidently wrong is punished savagely — as p for the correct token approaches zero, the loss shoots to infinity. This asymmetry teaches the model to be calibrated: to hedge when unsure rather than bet everything on a wrong answer.

The architectural details are tuned in service of this objective. Decoder-only, causal masking (so the model can't cheat by seeing the answer), tied input/output embeddings, the AdamW optimizer with a warmup-then-decay learning-rate schedule, gradient clipping for stability — these are the standard furniture of a pretraining run. Loss is averaged over every token in trillions of tokens, so a tiny per-token improvement is an enormous absolute gain. A useful intuition: loss is just the log of perplexity, the model's average "surprise" — a perplexity of 8 means it's effectively choosing between ~8 equally-likely words at each step. Drag the slider to feel the cost curve.

Cross-entropy: the cost of being wrong

Because loss is the average of −log(p) over every token in trillions of tokens, even a tiny per-token improvement is an enormous absolute gain.

03

Scaling Laws & Optimization

Loss falls predictably as you add parameters and data — a power law, not magic. Given a fixed compute budget, the Chinchilla result says: grow model and data together. Set a budget and find the sweet spot.

One of the most important discoveries in modern AI is that this all behaves predictably. Kaplan et al. (OpenAI, 2020) showed that test loss falls as a smooth power law in three quantities — model size, dataset size, and compute — spanning many orders of magnitude. This is why labs can confidently spend tens of millions of dollars on a single run: they can extrapolate from small experiments and know roughly what loss they'll land on before they start.

The Chinchilla paper (DeepMind, 2022) sharpened this into a recipe. Given a fixed compute budget — and since compute ≈ 6 × params × tokens — how should you split it between a bigger model and more data? Chinchilla's answer overturned the prevailing wisdom: most large models of the era (including GPT-3) were badly under-trained. The compute-optimal rule of thumb is to scale parameters and tokens together, roughly 20 tokens per parameter. The curve below is a Chinchilla-style loss surface: pick a compute budget, then slide your allocation and watch how far your loss sits from the optimum. (As the Llama case study shows, you sometimes deliberately ignore this and over-train a small model — because Chinchilla optimizes training cost, not the inference cost of serving the model forever.)

Compute-optimal allocation (Chinchilla-style)

04

Training Data Engineering

Raw web crawl is mostly junk. Quality comes from aggressive filtering: dedup, language ID, quality classifiers, toxicity removal. Each filter throws away a slice. Toggle filters and watch how little survives — and why that little is gold.

"Just train on the internet" is a trap. Raw web crawl (like Common Crawl) is dominated by boilerplate, spam, SEO sludge, adult content, broken markup and endless near-duplicates. Train on it directly and the model wastes capacity learning junk. The single biggest lever on model quality that isn't just "more compute" is data quality — and that means throwing most of the data away.

A modern data pipeline is a brutal funnel of stages: deduplication (exact and fuzzy — duplicated text causes memorization and wastes compute), language identification to hit the target mix, quality classifiers (often a small model trained to recognize "good" pages like Wikipedia or textbooks), heuristic filters (line length, symbol ratios, bad words), and toxicity / PII removal. Teams also tune the mixture — how much code, math, multilingual text — and "anneal" on especially high-quality data near the end of training. Each filter below removes a slice; toggle them and watch how little of the original 100 PB survives, and remember: that surviving sliver is what makes the model smart.

The data funnel — 100 PB of raw crawl in

05

Training Infrastructure & Systems

No single GPU holds a frontier model. You split the work three ways: data parallel (copies of the model on different batches), tensor parallel (one layer sliced across GPUs), and pipeline parallel (different layers on different GPUs). Toggle them.

A 405B-parameter model in 16-bit precision needs ~810 GB just to store its weights — and training needs several times that for gradients and optimizer state. No single GPU (80 GB on an H100) comes close. So frontier training is fundamentally a distributed systems problem: how do you split one model across thousands of chips and keep them all busy without drowning in communication?

The answer is to combine several kinds of parallelism. Data parallel: every GPU holds a full model copy, processes a different slice of the batch, and gradients are averaged — this scales throughput. Tensor parallel: a single layer's matrices are sliced across GPUs that compute one layer together — needed when one layer is too big for one chip. Pipeline parallel: different layers live on different GPUs, and activations flow down like an assembly line. Llama 3 added a fourth, context parallel, to split very long sequences. The art is balancing them so expensive inter-GPU communication is hidden behind computation. Toggle the modes below to see how the same 16-GPU cluster gets carved up; real runs use all of these at once.

3-D parallelism on a 16-GPU cluster

06

Advanced Pretraining Objectives

Next-token prediction (causal LM) is the default, but it isn't the only game. Masked LM hides random tokens; span corruption drops whole chunks; prefix-LM sees a clean prefix then generates. Pick an objective to see what the model is asked to recover.

The choice of what to predict shapes what the model is good at. Causal LM (GPT, Llama) predicts each next token left-to-right — perfect for generation, since that's exactly what generation is. Masked LM (BERT) instead hides ~15% of tokens and predicts them using context from both sides; this builds rich bidirectional understanding but can't generate text fluently, which is why BERT-style models power search and classification rather than chatbots.

In between sit hybrids. Span corruption (T5) drops whole contiguous chunks and asks the model to regenerate them, framing everything as text-to-text. Prefix-LM lets the model see a clean prefix bidirectionally, then generates the rest autoregressively. The field has largely converged on causal LM for general-purpose models — it's simple, it scales, and it directly matches the generation task — but knowing the alternatives explains why different model families behave so differently. Pick an objective below to see exactly which tokens get hidden and what the model must recover.

What does each objective hide?

07

Evaluation During Pretraining

You can't wait until the end to know if training is working. Teams watch loss and perplexity curves live, plus periodic benchmark probes. Scrub through training and watch the loss fall — and the sample text sharpen.

A pretraining run takes weeks to months and costs millions; you cannot afford to discover at the end that something was broken. So teams instrument everything and watch it live. The primary signal is the training and validation loss curve — it should fall fast then flatten into a smooth power-law decay. A sudden spike means trouble (a bad data shard, numerical instability, a hardware fault); a validation loss that diverges from training loss means overfitting. Perplexity (just exp(loss)) gives the same information in more intuitive units.

Loss alone doesn't tell you if the model is becoming useful, so runs also fire periodic benchmark probes — MMLU for knowledge, GSM8K for math, HumanEval for code — to catch capabilities emerging. Some abilities appear suddenly at scale ("emergent" behaviours), which downstream benchmarks reveal but the smooth loss curve hides. Teams also eyeball raw sample generations, which is genuinely informative: early in training the text is gibberish, then locally grammatical, then globally coherent. Scrub the slider below to watch loss fall, perplexity drop, and the sample text sharpen from noise into prose.

Training progress

Train loss
Perplexity
Tokens seen
08

Case Study — Llama 3

If GPT-2 proved scaling works, Meta's Llama 3 is the clearest public demonstration of doing it at frontier scale. It's a textbook application of everything in this module — a dense decoder-only Transformer with RoPE, grouped-query attention and SwiGLU, trained on ~15 trillion tokens — and, uniquely, Meta published both the weights and a 90-page paper explaining exactly how. This is the most transparent frontier-model recipe we have.

The open-weights bet

Meta's defining choice is to release the weights publicly (under a community license) rather than serve a model only behind an API — a deliberate contrast with OpenAI, Anthropic and Google. The Llama family is the spine of the open-LLM ecosystem:

Feb 24, 2023

Llama 1 — 7B–65B, research-only. Its weights leaked via torrent days later, accidentally seeding the entire open-LLM movement.

Jul 18, 2023

Llama 2 — 7B/13B/70B on 2T tokens, with the first commercial license.

Apr 18, 2024

Llama 3 — 8B and 70B, ~15T tokens, new 128K-token tokenizer. A 400B+ model announced as "still training."

Jul 23, 2024

Llama 3.1 — adds the 405B flagship, the first openly released frontier-class model; context extended to 128K across all sizes. The "Herd of Models" paper documents everything.

Architecture — boringly standard, on purpose

All three sizes are dense, decoder-only Transformers — explicitly not mixture-of-experts. The paper says this plainly: a standard dense architecture was chosen "to maximize training stability," favouring engineering simplicity at 16,000-GPU scale over the theoretical efficiency of fancier designs. The pieces are all things you've now seen:

  • RoPE rotary positions, with the base frequency cranked to 500,000 so the model can extrapolate from an 8K to a 128K context.
  • Grouped-Query Attention (GQA) with just 8 KV heads on every size (even 8B) — this shrinks the key/value cache during decoding, the thing that dominates long-context serving cost.
  • SwiGLU activations, RMSNorm, and no bias terms — the modern efficiency stack.
  • A 128,256-token tokenizer (tiktoken-based) replacing Llama 2's 32K SentencePiece one — ~15% fewer tokens per text, so cheaper training and inference.

The data: ~15 trillion tokens, heavily filtered

Pretraining used about 15T tokens (15.6T in the 3.1 paper) — roughly 7× Llama 2 and ~4× more code. All from publicly available sources, with a final mix of roughly 50% general knowledge, 25% math & reasoning, 17% code, 8% multilingual (30+ languages). The curation pipeline is the §4 funnel made real: heuristic + NSFW filters, semantic dedup, and model-based quality classifiers trained on labels from Llama 2 — using the previous model to grade the next model's diet. Near the end they anneal: upsample a small amount of very-high-quality math/code, which alone lifted the 8B's GSM8K score by 24%.

Llama 3 family

relative training compute
All three share the same recipe and the same ~15T-token diet — the only knobs that change are width, depth, and how many GPU-hours you can afford. Architecture highlights: RoPE positions, GQA attention, SwiGLU FFN, 128K vocab.

Training at the bleeding edge of hardware

The 405B was trained on up to 16,000 NVIDIA H100 GPUs, drawn from two custom 24K-GPU clusters, burning 3.8×10²⁵ FLOPs — nearly 50× the largest Llama 2 run — for a herd total of 39.3 million GPU-hours. To fit a 405B model across that many chips, Meta used 4-D parallelism: tensor + pipeline + context + data parallel, all at once (the §5 ideas, combined).

The reality of frontier-scale training

Over one 54-day stretch, the run hit 466 interruptions — 419 of them unexpected, ~78% traced to hardware (GPUs and HBM3 memory failing). That's roughly one failure every 3 hours. Training a frontier model is as much a feat of fault-tolerant systems engineering — checkpointing, auto-recovery — as it is of machine learning.

Past Chinchilla, on purpose

Recall the scaling laws in §3: the compute-optimal recipe puts ~20 tokens per parameter, so an 8B model "should" see ~200B tokens. Meta trained the 8B on ~15T — almost 75× past compute-optimal. Why deliberately "waste" training compute? Because they optimized for inference cost over the model's whole lifetime: a smaller model trained far too long is cheaper to serve forever, and Meta found the 8B kept improving log-linearly even past 15T tokens. The 405B's own size/data budget, by contrast, was set to be compute-optimal for Meta's training envelope.

Post-training: SFT → rejection sampling → DPO

After pretraining and a six-stage extension of context out to 128K, alignment runs over multiple iterative rounds of supervised fine-tuning (much of it on synthetic, rejection-sampled data) and Direct Preference Optimization. Notably Meta chose DPO over PPO-style RLHF — it needed less compute at this scale and performed better on instruction-following. (That whole pipeline is Module 03.)

Why Llama 3 is a landmark

The 405B was the first time a model in the GPT-4 / Claude-3.5-Sonnet quality tier shipped with open weights — and with a paper detailing the data mix, the parallelism, even the failure rates. For anyone learning how frontier models are actually made, it's the single most complete public document that exists.