AAI, Built

Act III · The Transformer Era

Part 18 of 31

Pretraining at Scale

Master'sstarts at this level56 min of film20 chaptersprerequisites: Part 11, Part 14, Part 16, Part 17

What does it take to train one model on sixteen thousand GPUs for fifty-four days?

The part opens on Llama 3's run: 16,384 GPUs, 54 days, 466 interruptions, 419 of them unplanned, one every three hours. It first follows the data. A sample of Common Crawl goes through extraction, a blocklist and language identification; MinHash is derived (two sets' minimum hashes agree with probability equal to their Jaccard similarity) and banded into an S-curve that finds near-duplicates without comparing every pair; a quality classifier, contamination checks, mixtures and a unigram model of collapse follow. After the objectives and the staging of a run, the part turns to arithmetic: about six operations per parameter per token, sixteen bytes per parameter in mixed-precision Adam. No single chip holds that, so the model is cut five ways, each checked on four processes of the rendering computer: data parallelism on the ring all-reduce, whose bandwidth bound is proved, ZeRO and FSDP, Megatron's tensor split, the pipeline with its bubble, and context and expert parallelism. The last third keeps the run alive: fewer bits with loss scaling and per-tile FP8 scales, QK-norm and the z-loss, a second token predicted ahead, and Young's checkpoint interval against failures. It ends by training the series' model with the 2020 recipe and the 2026 recipe at equal data, steps and seed, for the scoreboard.

What you need. Probability with sets and independence; the optimizers of Part 11 and the hardware terms of Part 17 (FLOP, bandwidth, the alpha-beta model).

Mathematics and history
data pipelines and dedup, data/tensor/pipeline/expert parallelism, ZeRO, FP8 training, stability, multi-token prediction

What you will be able to do

Undergraduate

  • Describe the stages between a web crawl and a pretraining corpus, and say what each one removes.
  • Tell the causal, masked, span-corruption and fill-in-the-middle objectives apart on one sentence.

Master's

  • Prove that two sets' minimum hashes agree with probability equal to their Jaccard similarity, and derive the banding curve.
  • Estimate a run's compute as 6ND and its memory per GPU without ZeRO and at ZeRO stages 1, 2 and 3.
  • Derive the pipeline bubble for GPipe, 1F1B, interleaved 1F1B and ZB-H1, and Young's checkpoint interval.

Research

  • Prove that no all-reduce beats the ring's bandwidth term, by counting the messages one number needs.
  • Derive the bound QK-norm puts on an attention logit and explain what the z-loss constrains instead.

Engineering

  • Choose a layout of data, tensor, pipeline, context and expert parallelism for a given cluster, and compute the run's model FLOPs utilization.
  • Pick a number format and its scaling (BF16, FP16 with loss scaling, FP8 per tile) for training, and a checkpoint interval from the checkpoint cost and the failure rate.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 12 min · Master's 50 min · Research 56 min · Engineering 22 min.

  1. 0Sixteen thousand GPUs, fifty-four daysUndergraduate3 min
  2. 1Anatomy of a frontier runUndergraduate2 min
  3. 2From the web to textUndergraduate3 min
  4. 3Near-duplicates: MinHash and LSHMaster's4 min
  5. 4Quality, and keeping the test cleanEngineering3 min
  6. 5Mixtures, synthetic data and collapseMaster's4 min
  7. 6What the model is asked to predictUndergraduate2 min
  8. 7Annealing, mid-training, long contextMaster's3 min
  9. 8Counting FLOPs and bytesMaster's3 min
  10. 9Data parallelism and the all-reduceResearch3 min
  11. 10ZeRO and FSDPMaster's3 min
  12. 11Tensor parallelismMaster's2 min
  13. 12Pipeline parallelismMaster's3 min
  14. 13Context, experts, and utilizationEngineering3 min
  15. 14Fewer bitsMaster's4 min
  16. 15Keeping the run stableResearch3 min
  17. 16Predicting two tokens aheadMaster's2 min
  18. 17When hardware failsEngineering3 min
  19. 18Our own full recipeEngineering2 min
  20. Recap, problems, and what comes nextAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Sixteen thousand GPUs, fifty-four daysUndergraduate3 min

June 2018. OpenAI's first GPT is pretrained for about a month on eight graphics cards. Here are the chips on one training run since then, on a scale where each step up is ten times more. In 2019, Megatron-LM spreads one model over 512 GPUs. In 2022, Google's PaLM trains on 6,144 TPU chips. In 2024, Meta's Llama 3 uses 16,384 GPUs, and in 2025 Llama 4 Behemoth is pretrained on 32,000 of them. In seven years, from 8 chips to 4,000 times as many. This part is about how that is done.

Take that run of Llama 3. 16,384 H100 GPUs, one dot each. Together they did about four times ten to the twenty-five operations, on fifteen point six trillion tokens of text. And they kept breaking. In one fifty-four-day stretch the job stopped 466 times, 419 of them unplanned: a faulty GPU, a memory chip, a network cable. That is one failure every 3 hours or so, and every one of them stops all sixteen thousand GPUs, because they are all working on the same model.

So the question of this part: how do you turn fifteen trillion tokens of the web into one model, on sixteen thousand GPUs, without the run falling apart? The answer comes in layers: the data, the objective, the arithmetic, the cuts across devices, the bits, the stability, and the failures.

We'll build every layer in miniature, on the computer making this video. 4,310 real web pages from Common Crawl, filtered, deduplicated and scored. Four processes as a tiny cluster. Pipelines and failures, simulated. Training pushed to the edge. And the 2026 recipe against the 2020 one, on the scoreboard.

This is Part 18 of AI, Built, in its third act, the transformer era. In this part: the data, from raw web pages to a clean mixture; the objective and the stages of training; the arithmetic of a run; the ways to cut a model across devices; fewer bits, and stability; and our own model, trained with the full recipe.

1Anatomy of a frontier runUndergraduate2 min

A frontier pretraining run is a pipeline. It starts with a crawl of billions of web pages, filtered for language and quality, deduplicated, mixed with books, code, maths and synthetic text, and cut into tokens. Then the model trains: a long pretraining phase, a short annealing on the best data, often called mid-training, a stage for long context, and the post-training of Part 27. Here are two published runs to scale. Ai2's Olmo 3, seven billion parameters: 5.9 trillion tokens of pretraining, then 100 billion of mid-training and 50 billion for long context. Hugging Face's SmolLM3: three pretraining stages, then long context. The last stages are a few percent of the tokens, chosen with the most care.

Here are six open runs of the last two years, as their reports state them. Llama 3.1 405B: 15.6 trillion tokens on 16,384 H100 GPUs, in sixteen-bit bfloat numbers, with AdamW. DeepSeek-V3: 14.8 trillion tokens on 2,048 H800s, in eight-bit floating point. Kimi K2: 15.5 trillion tokens with MuonClip, a version of the Muon optimizer. Olmo 3, the most open, data included. And in 2026, NVIDIA's Nemotron 3 Super, pretrained in four-bit numbers on 25 trillion tokens, and DeepSeek-V4-Pro, on 33 trillion with Muon. In two years the token counts doubled, the numbers shrank from sixteen bits to eight and four, and the optimizer began to change.

How big is such a run? Part 14 gave the rule: about six operations per parameter per token. For Llama 3.1, six times 405 billion times 15.6 trillion is 3.79 times ten to the twenty-five, just what Meta reports. DeepSeek-V3 is a mixture of experts: only 37 billion of its parameters work on each token, so it needs 3.3 times ten to the twenty-four, about a tenth. Its report also gives the bill: 2.664 million H800 GPU-hours for pretraining; at two dollars an hour, 5.576 million dollars for the whole run. That prices the final run only: not the experiments before it, the data, or the cluster.

2From the web to textUndergraduate3 min

Almost every open pretraining corpus starts in the same place: Common Crawl, a non-profit founded by Gil Elbaz in 2007, which has crawled the web since 2008 and gives the archive away, more than ten petabytes. Each crawl is cut into a hundred thousand files, in two forms that matter here: WARC files hold the raw responses, HTML and all; WET files hold the text Common Crawl extracted itself. For this part we took three WET files of the September 2026 crawl, three slices of each: 4,310 pages, 32 megabytes of text, in 64 languages.

The first step is extraction: turning HTML into text. A web page is mostly not prose. Scripts, styles, menus, footers, buttons. Here is one page from our WARC slices. Its HTML is 47,142 bytes. Trafilatura, the extractor FineWeb uses, keeps 2,484 bytes of it: the article, without the menu around it. Across all 387 HTML pages in our slices, 43 megabytes of HTML became 1.3 megabytes of text: about 3 percent. It matters: FineWeb's authors trained small models on the same crawl extracted two ways, and the Trafilatura text beat Common Crawl's own WET text.

Next: which language is each page in? Before that, a cheap filter on the address alone: a blocklist of adult and gambling sites removes 96 pages. Then a language identifier: fastText's, from Facebook AI Research, a linear model on character pieces that picks among 176 languages, fast enough to run on billions of pages. Here is what our sample holds. English: 1,728 pages, about 41 percent; the rest are spread over 63 other languages. FineWeb keeps a page as English only if the identifier is at least 65 percent sure. That drops 240 more; and we drop pages under fifty words. 1,398 English pages go on to the next step.

3Near-duplicates: MinHash and LSHMaster's4 min

The web repeats itself. These two pages from our sample come from one site: 93 percent of their phrases are the same. Duplicates waste compute, and they get memorized: Lee and colleagues found in 2022 that models trained on deduplicated data reproduce their training text ten times less often. To compare documents, cut each into shingles, its overlapping five-word phrases, as FineWeb does. Two documents are similar if their sets of shingles overlap: the Jaccard similarity, the size of the intersection over the size of the union. But comparing every pair of ten billion pages is five times ten to the nineteen comparisons. We need a shortcut.

The shortcut is a beautiful fact, found by Andrei Broder at AltaVista in 1997. Give every shingle a random number, with a random hash function. Over the union of the two sets, the shingle with the smallest hash is equally likely to be any of them. The two documents' minimum hashes agree exactly when that shingle is in both, in the intersection. So the chance that they agree is the size of the intersection over the size of the union: the Jaccard similarity itself. Keep 112 such minimums per document, as FineWeb does: a signature, and the share of positions where two signatures agree estimates the similarity. We checked it on 3,000 pairs of our pages, one of each pair with some words replaced: the estimate sits on the diagonal, off by 0.026 on average.

One signature per document still leaves every pair to compare. Locality-sensitive hashing avoids that: cut the 112 minhashes into 14 bands of 8. For two documents with similarity s, each minhash agrees with probability s, so a whole band of r agrees with probability s to the r. The chance that no band agrees is one minus s to the r, to the power b. And the chance that at least one does, making the pair a candidate, is one minus that. Now only documents that share a bucket in some band get compared, and the curve is an S: pairs below about 0.5 almost never collide, pairs above 0.8 almost always do, with the halfway point at 0.68. And here are our measured pairs, binned by similarity: they follow the formula, at most 0.11 away in any bin.

What did we find? The thirty Gutenberg files of Part 1 are a clearer test. At web scale, for Olmo 3, removing exact copies cut the pool by percent, MinHash removed another percent, and repeated substrings percent of the remaining bytes: 38.7 billion documents became 9.7 billion. And one surprise. FineWeb first deduplicated all 96 crawls against each other, and the models got worse: in the oldest crawls, what survived was the junk that nobody had copied. Deduplicating each crawl on its own worked better.

4Quality, and keeping the test cleanEngineering3 min

Quality is harder: which pages teach a model the most? In 2024 Hugging Face's FineWeb team gave the recipe that is now standard. Ask a large model to grade pages: Llama 3 70B, with a prompt that adds a point for each of five criteria of educational value, scored 460 thousand pages from zero to five. Then train a small model to imitate the grades: a linear layer on an embedding model, trained on 410 thousand of them, with an F1 of 82 percent at the threshold three. Run it over all fifteen trillion tokens and keep the pages scored three or more: 1.3 trillion tokens. At 1.7 billion parameters, that raised MMLU, a test of knowledge, from 33 to 37 percent, and ARC, a test of reasoning, from 46 to 57.

We can run this recipe ourselves, because FineWeb released Llama 3's annotations. We downloaded of them. percent score three or more, and of ours scored five. For the small model we used fastText, a linear model on words and word pairs that trains in seconds, on pages, with the cut chosen on a thousand others.

Now run it on our crawl sample. Here are the two pages it scores highest, and the two it scores lowest. It keeps 62 of our 1,398 English pages, 4.4 percent; FineWeb-Edu kept about nine percent of FineWeb's tokens. Other recipes aim elsewhere: DCLM trained its fastText filter to find text like instructions and good answers, and a seven-billion-parameter model on 2.6 trillion of its tokens reached 64 percent on MMLU.

One more filter, pointed the other way. If the questions of a benchmark are on the web, a model can pass it by memory. GPT-3's authors looked for any thirteen-word sequence shared between each test and the training text, and flagged what they found. We can check the series' own test. The scoreboard's passage, chapter two of The Maltese Falcon, has thirteen-word sequences; of them occur anywhere in the thirty novels we train on, and of its eight-word sequences. a sequence with the training text, like this one, a sentence that a novel repeats. Labs now run checks like this on every test they report.

5Mixtures, synthetic data and collapseMaster's4 min

A corpus is a mixture: web pages, encyclopedias, code, books, maths, papers. How much of each? In 2020 The Pile set its weights by hand: a quarter web, nine percent Wikipedia, and twenty other sources. In 2023 DoReMi learned them, with a small proxy model that keeps raising the weight of domains with the largest excess loss relative to a reference model; its weights let an eight-billion-parameter model reach the baseline in 2.6 times fewer steps. In 2024 RegMix made it a regression: train 512 tiny models on random mixtures, fit the loss as a function of the mixture, and train the big model on the best one. Its pick beat all 64 mixtures they tried at a billion parameters.

We ran RegMix on the thirty novels, in four groups: American novels, English novels of society, adventure and mystery, and the translations with Ulysses. Our target is the scoreboard's own book, The Maltese Falcon: we tune on its first and third chapters and keep the second, the scoreboard's passage, for the test. tiny models, each on a random mixture. Here is each one's loss on the target against its share of American novels: . A regression on the four weights and their products predicts each run's loss from the other runs with a correlation of . Asked for the best mixture, it : percent of the four groups.

Now the test: does the pick carry over to a larger model? We trained each mixture again, at the larger size, with two seeds. The lesson: a mixture is chosen for a target, so test it on text the choice never saw.

When good text runs short, there are two ways to stretch it. Repeat it: Muennighoff and colleagues found that up to about four passes over the same data are nearly as good as new data; after that the returns fall away. Or rewrite it: WRAP, from Apple and Carnegie Mellon, had a model rephrase web pages as encyclopedia entries or questions and answers, and real and rephrased text together trained about three times faster. Kimi K2's report measured it on knowledge. Text repeated ten times taught a model to answer 23.76 percent of a set of factual questions; rephrased once and repeated ten times, 27.39; rephrased ten different ways and read once each, 28.94.

But training on a model's output has a known failure, model collapse: train each generation on the last one's samples, and the tails of the distribution vanish. We can watch it in the simplest language model there is, the frequencies of the novels' tokens. Fit it to fifty thousand real tokens, sample fifty thousand from it, fit the next generation to those, and repeat: a rare token that once fails to be sampled is gone for good. Over generations, the tokens it can produce fall from to , and the lost ones carried percent of real text. The way out: keep the real data, and add each generation's samples to it instead of replacing it. In this toy experiment, retaining real data protects the distribution's support. It does not establish a universal rule for synthetic-data training.

6What the model is asked to predictUndergraduate2 min

Pretraining needs a question to ask of every piece of text. Here is the first sentence of Pride and Prejudice, cut into our tokenizer's 32 tokens, and the four questions labs have asked of it. GPT's causal objective: predict every token from the ones before it. BERT's masked objective: hide fifteen percent of the tokens and predict only those. T5's span corruption: replace short runs of tokens with markers, and have the model write out what each marker hid. And fill in the middle: in 2022 OpenAI's Bavarian and colleagues cut documents at two random points and moved the middle to the end. The model still predicts the next token, but given a beginning and an end it can now write what goes between: exactly what a code editor needs.

Count the targets. In a sequence of 256 tokens, the causal objective gives 255 predictions to learn from; masking gives about 38, and span corruption about 51, markers included. Fill in the middle keeps all of them: it is still next-token prediction, on rearranged text. Bavarian's team put half their documents in that order and found the ordinary left-to-right perplexity unchanged: infilling for free. DeepSeek-V3 rearranges ten percent of its documents this way. So the 2026 answer is Part 14's: predict every next token, because that model can be sampled, scored and prompted; and teach it to fill gaps by rearranging the data, not by changing the objective.

7Annealing, mid-training, long contextMaster's3 min

The learning rate falls as a run ends, and how it falls matters. Part 11's cosine starts decaying at once, so you must know the length of the run in advance. Since 2024 more runs use warmup, stable, decay: hold the peak learning rate, and cool down only over the last tenth or fifth of the steps. Here is the run of our own 2026 recipe, from chapter eighteen. The payoff: from any checkpoint of the stable phase you can branch off a short cooldown. We branched one at step . So one run can try many lengths of training.

The end of a run is also where the best data goes. What a model reads while its learning rate falls leaves a strong mark, so labs save their best text for the cooldown and call it annealing, or mid-training. SmolLM3 trained in three stages, from 85 percent web text to 63, with code and maths rising from 15 percent to 37. Llama 3 annealed its last forty million tokens to a learning rate of zero on its best sources, and averaged the checkpoints. Qwen3's second stage was five trillion tokens heavy in science, code and reasoning, with a faster decay. And Olmo 2 spends five to ten percent of its compute on mid-training, choosing the data with small annealing runs from a checkpoint: nineteen microanneals to pick its maths.

The last stage teaches length. Attention's cost grows with the square of the context, so models pretrain on four or eight thousand tokens and stretch at the end. Llama 3 went from eight thousand to 128 thousand in six stages, on about 800 billion tokens; DeepSeek-V3 to 32 thousand, then 128 thousand, a thousand steps each; Qwen3 and Olmo 3 stretched once; and DeepSeek-V4 grows its length during pretraining itself, from four thousand to a million. Stretching needs positions to stay distinguishable. Rotary embeddings, from Part 13, turn each pair of dimensions by an angle per token, slower and slower down the pairs. With the usual base of ten thousand, the slowest pair takes 54 thousand tokens to turn once. Raise the base, as Llama 3 did to half a million and Qwen3 to a million, and it takes 2.6 and 5.1 million: room for long documents.

8Counting FLOPs and bytesMaster's3 min

First, arithmetic. Almost all of a transformer's work is matrix products, one per weight matrix. Going forward, each weight multiplies one input and adds it in: two operations, per weight, per token. Going backward, each weight is used twice more. Once to send the error down to the layer below: two operations. And once to compute its own gradient: two more. Six operations per weight per token: the C of six N D, plus attention's own products, which grow with the length of the context.

We can check this on our own model, with PyTorch's FLOP counter, which counts the operations of every matrix product in one training step on 256 tokens. The backward pass costs 2.00 times the forward pass. And the total is six times the weights times the tokens, to within 0.08 percent. Attention's own products, the scores and the weighted sum, add 20 percent more at this length, and they grow with it.

Now memory. Train in mixed precision, the standard recipe since 2018, and every parameter costs sixteen bytes. Two for the weight in bfloat16 and two for its gradient; then the optimizer's state, in thirty-two bits: a master copy of the weight, four bytes, and Adam's two running averages, four each. For Llama 3.1, sixteen bytes times 405 billion is 6.5 terabytes: at least 81 GPUs of eighty gigabytes just to hold the model, before any activations. DeepSeek-V3, for one, keeps Adam's averages in sixteen bits.

The other big consumer of memory is the activations, what the forward pass keeps for the backward pass. We counted the tensors PyTorch saves for our model, at lengths from 64 to 1,024 tokens. With attention fused, the memory grows in a straight line: 23.5 numbers per token per layer, in units of the width. Compute attention the textbook way, and it also keeps a T by T matrix for each head: a parabola, which FlashAttention removes. Or keep only each block's input and recompute the rest during the backward pass: one number per token per layer, for 16 percent more arithmetic here. At Llama 3.1's shape and eight thousand tokens, Korthikanti and colleagues' count gives four and a half gigabytes per layer, more than half a terabyte per sequence.

9Data parallelism and the all-reduceResearch3 min

The simplest way to use many GPUs: give each one a full copy of the model and a slice of the batch. Each computes the gradient of its slice. Then they average the gradients, so that every copy takes exactly the same step, and they stay identical. The averaging is an all-reduce, the operation of Part 17. It is the same step as one big batch on one device. We checked: 4 processes of this computer, each with a quarter of the batch, against one process with all of it, for 6 steps of AdamW: the losses agree to 6 digits, and every parameter to within 0.00002; only the order of the additions differs.

Recall the ring of Part 17. Cut each GPU's gradient into p chunks. At each step every GPU passes one chunk to its neighbour, which adds it to its own; after p minus one steps each GPU holds the full sum of one chunk: a reduce-scatter. Then p minus one more steps pass the finished chunks around: an all-gather. Each GPU sends two times p minus one over p of the gradient's bytes. ZeRO, next, does useful work between the two halves.

Part 17 said that no algorithm beats the ring on bandwidth. Here is why. Follow a single number, whose sum all p GPUs must end up holding; each message carries one fixed-width value. Some GPU is the first to hold the full sum. Every other GPU's value must have reached it: at least p minus one messages. At that moment nobody else has the sum, so each of the other p minus one GPUs needs at least one more message. Two times p minus one values sent per number. For a tensor of n bytes, that is two times p minus one times n bytes in total. The p GPUs receive at the same time, B bytes per second each, so the time is at least two times p minus one, over p, times n over B: exactly the ring's. What's left to win is latency, with trees for small messages, and overlap: sending the last layers' gradients while the backward pass is still computing the first.

10ZeRO and FSDPMaster's3 min

Data parallelism has a waste built in: every GPU keeps the whole model, its gradients and its optimizer state, chapter eight's sixteen bytes per parameter, all identical. In 2019 Samyam Rajbhandari and colleagues at Microsoft proposed ZeRO, the zero-redundancy optimizer: split them. Stage one: each GPU keeps the optimizer state for a quarter of the parameters, and updates only those. Stage two: only the gradients of its quarter, too. Stage three: only its quarter of the weights, fetching the rest from its neighbours just before a layer needs them, and dropping them after. PyTorch's stage three is called FSDP, fully sharded data parallel.

The arithmetic, in the paper's notation: psi parameters, K bytes of optimizer state for each, twelve for mixed-precision Adam, and N GPUs. Plain data parallelism: sixteen bytes per parameter on every GPU. For their example, 7.5 billion parameters on 64 GPUs: 120 gigabytes each. Stage one divides the optimizer's twelve bytes by N: 31.4. Stage two, the gradients as well: 16.6. Stage three divides everything: 1.88 gigabytes per GPU. Sixty-four GPUs together hold the model once, not sixty-four times.

What does sharding cost in communication? Stages one and two cost nothing extra: the all-reduce already was a reduce-scatter and an all-gather, with each GPU's update in between. Stage three keeps only a quarter of each layer's weights: before the layer runs forward, the GPUs all-gather it, and afterwards they drop it. The backward pass needs the weights again: gather once more. And the gradients are reduce-scattered, so each GPU keeps only its quarter. Three passes over the parameters instead of two: half as much traffic again, in exchange for memory divided by N. Meta trained Llama 3 with FSDP across its data-parallel groups; DeepSeek-V3 used stage one.

We built ZeRO stage three ourselves, on four processes: each holds a quarter of every layer's parameters, gradients and Adam moments, gathers a layer just before it runs, forward and backward, and reduce-scatters its gradients. Each process keeps times fewer numbers, plus one layer at a time. And it sends times as much:

11Tensor parallelismMaster's2 min

When a single layer is too big or too slow for one GPU, split the layer itself. NVIDIA's Megatron-LM showed how in 2019. Take the MLP: Z equals X times A, a nonlinearity, then times B. Split A by columns, half on each GPU: each computes its half of Y from the whole input, with no communication. For SwiGLU, each column shard keeps matching gate and value columns together, so the paired product stays local too. Now split B by rows. Each GPU multiplies its half of Y by its half of B and gets a full-size partial result; the answer is their sum, one all-reduce. So the whole MLP costs one all-reduce going forward, called g, and one going backward, f, for the gradient of the input both halves used.

Attention splits even more naturally: its heads are independent. Give each GPU the queries, keys and values of half the heads; each computes its heads alone, and the output projection, split by rows, ends in one all-reduce. So a transformer layer costs two all-reduces forward and two backward, each of a full activation: batch times sequence times width. That happens in every layer for every micro-batch, so tensor parallelism lives where bandwidth is highest, inside one machine's NVLink domain; Llama 3 used eight-way tensor parallelism, the innermost of its four dimensions. Sequence parallelism, from 2022, splits the remaining activations by position too.

We split one block of our own transformer this way, across two and then four processes, with an all-reduce for each f and g. Each process holds a half, or a quarter, of the block's matrices, and the counts are Megatron's: two all-reduces forward, two backward.

12Pipeline parallelismMaster's3 min

Tensor parallelism cuts every layer; pipeline parallelism cuts the model the other way: the first eight layers on one GPU, the next eight on another, each GPU a stage. The trouble: while the first stage works on a batch, the others wait. Google's GPipe cut each batch into micro-batches, so the stages can work on different ones at once. Here is GPipe's schedule, simulated exactly: 4 stages, 8 micro-batches, a backward pass taking twice as long as a forward. The micro-batches fill the pipeline going forward, it drains, and the backward passes fill it again in reverse. The grey corners are GPUs waiting: the pipeline bubble.

How big is the bubble? Each GPU is busy for m micro-batches, a forward and a backward each. But the whole schedule takes longer: the last micro-batch can't start on the last stage until it has passed the p minus one stages before, and the same on the way back. So the share of time wasted is p minus one, over m plus p minus one. For our chart, 27.3 percent. Here is the bubble against the number of micro-batches, the formula as lines and our simulated schedules as dots. Every dot sits exactly on its line. More micro-batches shrink it; GPipe's authors found four per stage enough.

GPipe has a second problem: memory. Each stage keeps the activations of every micro-batch it has run forward until that micro-batch comes back. The 1F1B schedule, from Microsoft's PipeDream work, starts each micro-batch's backward pass as soon as it can, alternating one forward with one backward. The bubble is exactly the same: 27.3 percent. But the first GPU never holds more than 4 micro-batches at once, the number of stages, instead of all 8. Memory no longer grows with the number of micro-batches, so you can use many of them, and the bubble shrinks.

Two more tricks cut the bubble itself. Interleaving: give each GPU two smaller chunks of layers instead of one, so the ramp-up takes half as long, and the bubble falls to 15.8 percent. Llama 3 used this. Zero bubble, from Sea AI Lab in 2023: split the backward pass in two. The gradient for the input is urgent, because the stage before is waiting for it; the gradient for the weights can be postponed into the gaps. With equal times for the three, the idle time falls to a third of 1F1B's, a bubble of 11.1 percent. DeepSeek-V3's DualPipe feeds micro-batches in from both ends at once and overlaps computation with communication, at the price of keeping two copies of the weights.

13Context, experts, and utilizationEngineering3 min

Two more ways to cut. At a million tokens, one sequence's activations no longer fit on a GPU, so split the sequence itself: context parallelism. Each GPU keeps one block of positions. Everything in a transformer is per position, except attention. Ring attention, from Berkeley in 2023: each GPU keeps its queries, and the blocks of keys and values travel round the ring. Each arriving block is folded in with the online softmax, as in FlashAttention, so the answer is exact. We ran it on four processes, 256 tokens in four blocks: the result matches full attention to 0.0000003.

There's a catch with causal attention. A position only looks back, so the first block of queries needs one block of keys, and the last needs all of them. With contiguous blocks, the last GPU touches times as many query-key chunk pairs as the first in this eight-chunk drawing. These are block counts, not measured device timings. The fix: cut the sequence into twice as many chunks, and give GPU i both chunk i and chunk 2p minus one minus i, one from each end. Llama 3 did exactly this for its 128-thousand-token training, with sixteen-way context parallelism.

The second cut is for mixtures of experts, from Part 16: put different experts on different GPUs. Every layer begins with an all-to-all, each GPU sending its tokens to the GPUs that hold their experts, and ends with another, sending the results back. DeepSeek-V3 spread its experts over 64 GPUs in eight machines, and let each token visit at most four machines, because the network between machines is about three times slower than NVLink inside one.

A frontier run uses several cuts at once. Here is Llama 3's own table. On 16,384 GPUs with eight-thousand-token sequences: eight-way tensor parallel, sixteen pipeline stages, and 128 data-parallel groups. Eight times sixteen times 128 is 16,384. For the 128-thousand-token stage, sixteen-way context parallelism took GPUs from the data dimension. The order matters. Tensor parallelism, which talks in every layer, is innermost, inside one machine. Context and pipeline come next. Data parallelism, which talks once a step and can wait, spans the whole cluster.

With all this machinery, how much of the hardware does a run use? PaLM's paper defined the measure: model FLOPs utilization, six N per token times tokens per second, over the hardware's peak. PaLM processed 238 thousand tokens a second on 6,144 TPU chips of 275 teraflops: 45.7 percent. ByteDance's MegaScale reached 55 percent; Llama 3, 38 to 43; Olmo 3, 43. About half of what a cluster could compute is lost to communication, bubbles, memory traffic and failures. Our own training runs, on one core of this computer: 15 and 11 percent of its peak.

14Fewer bitsMaster's4 min

Narrower numbers take less memory and multiply faster: Part 17's tensor cores do twice the work in eight bits as in sixteen. How few bits can training use? Here are the formats, on a scale of powers of two. FP32 and bfloat16 share an eight-bit exponent, so the same enormous range; bfloat16 just keeps fewer digits. FP16 has five exponent bits: nothing below about six times ten to the minus eight, and only low-precision subnormals below two to the minus fourteen. Now the gradients flowing back through our model's matrix products, after sixty steps. Virtually all of them are below FP16's smallest normal number, and 34 percent are so small that FP16 rounds them to zero.

The fix, from Micikevicius and colleagues in 2018, is loss scaling. Multiply the loss by a large number S before the backward pass; the chain rule is linear, so every gradient comes out S times larger. For S of two to the sixteen, the whole distribution slides sixteen places to the right, into FP16's range. Then divide the weights' gradients by S before the update, in thirty-two bits. S is dynamic: on an overflow, halve it and skip the step; after a run of good steps, double it. Bfloat16, with FP32's range, needs none of this, which is why it took over.

Does it matter in practice? We trained the same small model with every matrix product's inputs rounded to a format, forward and backward, and the sums kept in FP32, as the hardware does; two seeds each. FP32, bfloat16, FP16 without and with loss scaling, and two kinds of eight-bit training we'll meet in a moment.

Why, then, does loss scaling matter? A frontier run accumulates each step's gradient over millions of tokens, piece by piece. Here we isolate the scale effect: divide one batch's loss by , then restore its gradients before the update. This is a gradient-scale surrogate, not a run with actual micro-batch accumulation.

Eight bits is harder. E4M3, with four exponent bits, spans only about eighteen powers of two, so every tensor needs a scale to move its values into range, and one scale per tensor is set by the largest value. DeepSeek-V3 trained its 671 billion parameters with a scale for every 128 values of an activation and every 128 by 128 block of a weight, moved its partial sums to FP32 every 128 terms, because its tensor cores kept only about fourteen bits, and stayed within a quarter of a percent of a sixteen-bit run.

The newest chips put the scales into hardware. NVIDIA's Blackwell multiplies microscaled formats, blocks of 32 numbers sharing one scale; in MXFP8, an eight-billion-parameter model trained on fifteen trillion tokens matched bfloat16. Then four bits: NVFP4 packs sixteen four-bit values with one eight-bit scale. NVIDIA pretrained a twelve-billion-parameter model on ten trillion tokens in it, with random rotations to spread the outliers and sixteen percent of the layers kept in bfloat16, and matched its FP8 model. In 2026 Nemotron 3 Super was pretrained in NVFP4 on 25 trillion tokens, and Kimi K3 and DeepSeek-V4 learned four-bit weights in quantization-aware training. Each halving of the bits came with a new way of scaling.

15Keeping the run stableResearch3 min

Large runs have a failure that small ones rarely show: the loss suddenly jumps, and sometimes never comes back. Google's PaLM, at 540 billion parameters, spiked about twenty times, although its gradients were clipped. The fix was blunt: restart about a hundred steps before the spike, and skip the next two to five hundred batches. It wasn't bad data: the same batches were fine from another point in training. The trouble was the model's state, and today's models are built to keep it tame.

One state that goes wrong is attention itself. A query and a key give a logit, their dot product over the square root of the dimension, and nothing stops the weights from growing until the logits are huge. Then the softmax puts all its weight on one position, its gradients vanish, and training can lock up. Wortsman and colleagues reproduced this in small models by raising the learning rate; so did we. At a learning rate of 0.03, our plain model's largest attention logit reaches 172. The fix, used in ViT-22B, Olmo 2, Qwen3 and GLM-4.5, is QK-norm: normalize every query and key before the dot product, and the logit is bounded by the norms' learned gains times the square root of the dimension. With it, our largest logit stays at 9.

Wortsman's test of a fix is a sweep: train at many learning rates and see how far up the loss stays good. Here is ours: learning rates, plain, with QK-norm, and with QK-norm and the z-loss we will see next, two seeds each.

The second fix is for the output layer. A softmax doesn't change if every logit shifts by the same amount. So their log-sum-exp, log Z, is free to drift, and in sixteen-bit arithmetic large logits lose their precision. PaLM added a tiny penalty, ten to the minus four times log Z squared: the z-loss. Its gradient nudges all the logits together toward a normalizer of one, without changing what the model predicts.

The newest source of trouble is the optimizer. Part 11's Muon went to scale in 2025: Moonshot's Moonlight study found it about twice as compute-efficient as AdamW. But with Muon the attention logits grew faster, and Kimi K2's latent attention never forms its keys in full, so QK-norm can't be applied. Moonshot's fix, QK-Clip: after each update, if a head's largest logit has passed a hundred, shrink that head's query and key weights. It clipped 12.7 percent of the heads early on and none after seventy thousand steps, and K2 trained on 15.5 trillion tokens without a loss spike. DeepSeek-V4 also uses Muon, normalizes its queries and keys, and tames the rare spikes from its experts by clamping SwiGLU and routing with slightly older weights.

16Predicting two tokens aheadMaster's2 min

Next-token prediction asks for one token at a time, which lets a model get by on local patterns. What if it had to look further? In 2024, Fabian Gloeckle and colleagues at Meta gave a model several output heads on a shared trunk, predicting the next token, the one after, and so on. On code, a thirteen-billion-parameter model solved twelve percent more HumanEval problems and seventeen percent more of MBPP. The gain grew with size; at their smallest models the extra heads hurt. And the heads double as a fast way to guess ahead at inference, up to three times faster.

DeepSeek-V3 made the extra prediction sequential. The main model predicts the next token as usual. A small module then takes the main model's last hidden state at position i and the embedding of the true next token, normalizes both, joins them, passes them through one more transformer block, and predicts the token after next with the same output head. Its loss is added with a weight of 0.3 for the first ten trillion tokens, then 0.1. At inference the module can be dropped, or used to guess the second token for the main model to check: DeepSeek reports the guess accepted 85 to 90 percent of the time, and 1.8 times the speed.

We added DeepSeek-V3's module to our small model and trained it on the same tokens, two seeds each, with the weight dropping from 0.3 to 0.1 near the end. The module costs about percent more arithmetic per step, .

And as a drafter? We let our main model write greedily from held-out openings, while its module guessed each token after next. Each step of the main model would then yield tokens instead of one. Part 19 builds speculative decoding properly.

17When hardware failsEngineering3 min

Back to Llama 3's run. In fifty-four days its job was interrupted 466 times, 419 of them unplanned. Here are the causes Meta reported: faulty GPUs above all, then their memory chips, software bugs, network switches and cables. That is one interruption every 3.1 hours. This is a job-level rate, including software and network faults; it does not measure the lifetime of an individual GPU. With sixteen thousand GPUs working synchronously, a single failure can require the whole job to restart. Thanks to automation, only three failures needed a person, and the run spent more than ninety percent of its time training. Even the weather showed.

So a run saves a checkpoint of every GPU's state regularly, and after a failure restarts from the last one. How often should it save? Saving every tau seconds, at a cost of delta each time, wastes delta over tau of the run. And a failure, arriving on average every M seconds, throws away the work since the last save, half an interval on average: tau over two M more. Set the derivative to zero. The best interval is the square root of two delta M: John Young's rule, from 1974. For Llama 3: checkpoints of up to four gigabytes per GPU, storage that wrote two terabytes a second. If every GPU writes that maximum at the sustained rate, the idealized save cost is 33 seconds; with a job interruption every 3.1 hours, the illustrative optimum is 14 minutes. These are modeled timings, not reported checkpoint or pause measurements.

We simulated it: 54 days of a run with random failures, one every 3.1 hours on average, 33 seconds to save and, as an illustration, ten minutes to restart, many times over for each interval between checkpoints. Save too often, and saving eats the run; too rarely, and every failure throws away hours. The best interval in the simulation is 14 minutes; Young's rule says 14. Even then, 12 percent of the time is lost: 5 percent to the restarts alone, the rest to saving and to work done twice. That is why frontier labs make restarts fast and checkpoints asynchronous.

18Our own full recipeEngineering2 min

Now we put the pieces together. Two models of the same shape, trained on the same three million tokens of the thirty novels, in the same order, from the same starting weights; and the whole comparison again from a second seed. One with the recipe of 2020: AdamW, a cosine schedule, plain attention. One with the recipe of 2026: Muon for the hidden matrices, warmup, stable, decay, QK-norm and the z-loss.

Watch them learn. On the left, each model's loss on text it never trains on; on the right, what each writes after the words 'The door opened, and', frozen at the same steps, with the same random seed. At the start both write noise, at a loss of about 8.4 nats. Let them read: the noise turns into words, then into phrases shaped like English. By the end, compare what they write; the curves tell which learned faster.

The scores. And on the series' scoreboard, the bits per character each model needs for chapter two of The Maltese Falcon. , and the series' own model of million parameters, trained on times our tokens, at . A recipe buys efficiency: the same quality for less compute. The frontier labs spend that saving on scale.

Recap, problems, and what comes nextAll tracks2 min

Let's take stock. A pretraining corpus starts as a crawl of the web, and most of it is thrown away: by address, by language, by quality. MinHash and locality-sensitive hashing find the near-duplicates without comparing every pair, and their S-curve came out as predicted. Mixtures are chosen for a target; our toy collapse experiment retains real text as synthetic samples accumulate. Training takes about six operations per parameter per token. Mixed-precision Adam's model state takes sixteen bytes per parameter, with activations on top. The ring all-reduce is optimal; ZeRO shards the copies away; tensor, pipeline, context and expert parallelism cut the rest. Fewer bits need scaling tricks, big runs need QK-norm, and sixteen thousand GPUs need checkpoints. And our own model, trained with the full recipe, took its place on the scoreboard.

All of this comes back. Serving the trained model is Part 19. The same data pipelines feed images, video and sound in Parts 22 and 23. Post-training starts from a pretrained model in Part 27, reasoning in Part 28, and Parts 30 and 31 open it up and test how far its evaluations can be trusted.

Here are six problems to try, from MinHash's probability to Young's checkpoint interval. Pause here and work through them; full solutions are in this part's notes.

Next time: inference. A trained model has to answer, quickly and cheaply, for millions of people. Reading a prompt is arithmetic; writing the answer, one token at a time, is moving memory. Drafts like DeepSeek-V3's second-token guesses let one pass check several tokens, and four-bit weights make every token cheaper. That is Part 19.

Most of this part's methods are written up openly, in the technical reports of the labs that use them, and they are well worth reading. Thanks for watching, and see you in Part 19.

Where it goes next. Serving the trained model is Part 19, where the multi-token-prediction module returns as a drafter and the number formats as four-bit weights. The same data pipelines feed images, video and sound in Parts 22 and 23; post-training starts from a pretrained model in Part 27 and reasoning in Part 28; Parts 30 and 31 open the model up and test how far its evaluations can be trusted.

Key results

The part's results in one place, for revision.

MinHash\(\displaystyle \Pr\bigl[\min h(A)=\min h(B)\bigr]=J(A,B)=\frac{|A\cap B|}{|A\cup B|}\)
Banding: b bands of r\(\displaystyle \Pr[\text{candidate }\allowbreak \text{pair}]=1-\bigl(1-s^{r}\bigr)^{b}\)
Compute and memory\(\displaystyle C\approx 6ND,\qquad\allowbreak \text{mixed-precision }\allowbreak \text{Adam: }(2+2+12)\ \text{bytes }\allowbreak \text{per }\allowbreak \text{parameter}\)
All-reduce's bandwidth bound\(\displaystyle T\ \ge\ 2\,\frac{p-1}{p}\,\frac{n}{B}\quad\allowbreak \text{(the }\allowbreak \text{ring }\allowbreak \text{meets }\allowbreak \text{it)}\)
The pipeline bubble\(\displaystyle \frac{\text{idle}}{\text{total}}=\frac{p-1}{m+p-1}\quad\allowbreak \text{(GPipe }\allowbreak \text{and }\allowbreak \text{1F1B)}\)
Young's checkpoint interval\(\displaystyle \tau^\ast=\sqrt{2\,\delta M},\qquad\allowbreak \text{waste}\approx\sqrt{2\delta/M}\)

Try it

Lab 18 · MinHash bands and the pipeline bubble

Two claims of the part, each derived on screen, each checked here. Draw 2,400 pairs of shingle sets with known Jaccard similarity s, hash them 112 times, and compare how often a pair shares a band with 1 - (1 - s^8)^14. Then run GPipe, 1F1B, interleaved 1F1B and ZB-H1 schedules through the film's simulator and compare each bubble with its formula.

Figure produced by Lab 18: MinHash bands and the pipeline bubble
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.ai.labs 18 needs numpy, scipy, matplotlib · download lab18.py · source on GitHub
per-hash agreement against Jaccard           largest gap 0.0035 over 8 levels
s = 0.50: pair shares a band                 measured 0.060   1 - (1 - s^8)^14 = 0.053
s = 0.70: pair shares a band                 measured 0.527   1 - (1 - s^8)^14 = 0.565
s = 0.84: pair shares a band                 measured 0.980   1 - (1 - s^8)^14 = 0.981
similarity caught half the time              0.685   (14 bands of 8)
GPipe: bubble at p = 4, m = 8                simulated 0.2727   formula 0.2727
1F1B: bubble at p = 4, m = 8                 simulated 0.2727   formula 0.2727
interleaved, v = 2: bubble at p = 4, m = 8   simulated 0.1579   formula 0.1579
ZB-H1: bubble at p = 4, m = 8                simulated 0.1111   formula 0.1111
micro-batches held on the first GPU, m = 64  GPipe 64   1F1B 4   (p = 4)

Banding turns 112 noisy coin flips per pair into a sharp threshold near s = 0.69, so only likely duplicates are ever compared. A pipeline wastes (p - 1)/(m + p - 1) of its GPUs' time; 1F1B has the same bubble as GPipe but holds p micro-batches instead of m.
The code (99 lines; it asserts its own result)
"""Lab 18: catch near-duplicates with MinHash bands, and measure a pipeline's bubble on the film's own simulator."""

import numpy as np

from videos.coursekit import labs
from videos.ai.ai18 import sched  # the film's exact pipeline simulator (plain Python)

TITLE = "MinHash bands and the pipeline bubble"
GOAL = ("Two claims of the part, each derived on screen, each checked here. Draw 2,400 pairs of shingle sets with "
        "known Jaccard similarity s, hash them 112 times, and compare how often a pair shares a band with "
        "1 - (1 - s^8)^14. Then run GPipe, 1F1B, interleaved 1F1B and ZB-H1 schedules through the film's simulator "
        "and compare each bubble with its formula.")
TASKS = [
    "Change the banding to 20 bands of 5 (100 hashes). Where does the S-curve cross one half, and what does it do to "
    "pairs at s = 0.5?",
    "Make the backward pass three times as long as the forward (dur = {'F': 1, 'B': 3}). Does GPipe's bubble change?",
    "Hold p = 8 and find the number of micro-batches m at which 1F1B's bubble falls under 5%; then read its peak "
    "memory and GPipe's at that m.",
]
BANDS, ROWS, UNION, PAIRS = 14, 8, 100, 300


def minhash_pair(shared, rng):
    """A pair of sets whose union has UNION shingles, ``shared`` of them in both: (signatures agree per hash)."""
    h = rng.random((BANDS * ROWS, UNION))  # one random hash value per shingle, per hash function
    only = (UNION - shared) // 2
    both = h[:, :shared].min(axis=1)
    a = np.minimum(both, h[:, shared:shared + only].min(axis=1))
    b = np.minimum(both, h[:, shared + only:].min(axis=1))
    return a == b


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. MinHash: Pr[minima agree] = J, and banding's S-curve
    levels = np.array([30, 50, 60, 66, 70, 76, 84, 92])  # shared shingles out of 100: Jaccard 0.30 ... 0.92
    s = levels / UNION
    predicted = 1 - (1 - s ** ROWS) ** BANDS
    agree, caught = [], []
    for c in levels:
        eq = np.array([minhash_pair(int(c), rng) for _ in range(PAIRS)])
        agree.append(eq.mean())
        caught.append(eq.reshape(PAIRS, BANDS, ROWS).all(axis=2).any(axis=1).mean())
    agree, caught = np.array(agree), np.array(caught)
    half = (1 - 2 ** (-1 / BANDS)) ** (1 / ROWS)
    lab.row("per-hash agreement against Jaccard", f"largest gap {np.abs(agree - s).max():.4f} over {len(s)} levels")
    for k in (1, 4, 6):
        lab.row(f"s = {s[k]:.2f}: pair shares a band", f"measured {caught[k]:.3f}   1 - (1 - s^{ROWS})^{BANDS} = "
                f"{predicted[k]:.3f}")
    lab.row("similarity caught half the time", f"{half:.3f}   ({BANDS} bands of {ROWS})")
    assert np.abs(agree - s).max() < 0.015, "a minhash agrees with probability J"
    assert np.abs(caught - predicted).max() < 0.12, "the S-curve"
    assert caught[0] < 0.02 and caught[-1] > 0.98, "dissimilar pairs are almost never compared, near-copies always"

    # 2. the pipeline bubble, on the film's simulator
    p, ms = 4, (4, 8, 16, 32, 64)
    sims = {"GPipe": [], "1F1B": [], "interleaved, v = 2": [], "ZB-H1": []}
    peaks = {}
    for m in ms:
        runs = {"GPipe": (sched.gpipe(p, m), 1, {"F": 1, "B": 2}), "1F1B": (sched.one_f_one_b(p, m), 1, {"F": 1, "B": 2}),
                "interleaved, v = 2": (sched.interleaved(p, m, 2), 2, {"F": 1, "B": 2}),
                "ZB-H1": (sched.zb_h1(p, m), 1, {"F": 1, "B": 1, "W": 1})}
        for name, (orders, v, dur) in runs.items():
            r = sched.stats(*sched.simulate_fixed(orders, p, v, dur), p, v)
            sims[name].append(r["bubble"])
            peaks[name, m] = r["peak"][0]
    ms_a = np.array(ms)
    formulas = {"GPipe": (p - 1) / (ms_a + p - 1), "1F1B": (p - 1) / (ms_a + p - 1),
                "interleaved, v = 2": (p - 1) / (2 * ms_a + p - 1), "ZB-H1": (p - 1) / (3 * ms_a + p - 1)}
    for name in sims:
        lab.row(f"{name}: bubble at p = {p}, m = 8", f"simulated {sims[name][1]:.4f}   formula {formulas[name][1]:.4f}")
        assert np.allclose(sims[name], formulas[name], atol=1e-9), name
    lab.row("micro-batches held on the first GPU, m = 64", f"GPipe {peaks['GPipe', 64]:.0f}   1F1B {peaks['1F1B', 64]:.0f}"
            f"   (p = {p})")
    assert peaks["GPipe", 64] == 64 and peaks["1F1B", 64] == p, "1F1B's memory stops growing with m"
    lab.note = ("Banding turns 112 noisy coin flips per pair into a sharp threshold near s = 0.69, so only likely "
                "duplicates are ever compared. A pipeline wastes (p - 1)/(m + p - 1) of its GPUs' time; 1F1B has the "
                "same bubble as GPipe but holds p micro-batches instead of m.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    grid = np.linspace(0.2, 1, 200)
    ax[0].plot(grid, 1 - (1 - grid ** ROWS) ** BANDS, color=labs.GOLD, label=f"1 - (1 - s^{ROWS})^{BANDS}")
    ax[0].plot(s, caught, "o", color=labs.BLUE, label=f"measured, {PAIRS} pairs per level")
    ax[0].plot(grid, grid, color=labs.MUTED, ls=":", lw=1, label="one minhash: probability s")
    ax[0].axvline(half, color=labs.MUTED, ls="--", lw=1)
    ax[0].set(title="Chance a pair shares a band", xlabel="Jaccard similarity s", ylabel="probability")
    ax[0].legend(loc="upper left")
    for (name, vals), color in zip(sims.items(), (labs.RED, labs.BLUE, labs.GREEN, labs.PURPLE)):
        ax[1].plot(ms, formulas[name], color=color, lw=1.2, ls="--" if name == "GPipe" else "-")
        ax[1].plot(ms, vals, "o", color=color, label=name, ms=8 if name == "GPipe" else 4)
    ax[1].set(title=f"The pipeline bubble against micro-batches, p = {p}", xlabel="micro-batches m",
              ylabel="idle share of GPU time", xscale="log")
    ax[1].set_xticks(ms, [str(m) for m in ms])
    ax[1].minorticks_off()
    ax[1].legend(title="dots simulated, lines formulas")
    lab.fig = fig
    return lab

Now change it

  1. Change the banding to 20 bands of 5 (100 hashes). Where does the S-curve cross one half, and what does it do to pairs at s = 0.5?
  2. Make the backward pass three times as long as the forward (dur = {'F': 1, 'B': 3}). Does GPipe's bubble change?
  3. Hold p = 8 and find the number of micro-batches m at which 1F1B's bubble falls under 5%; then read its peak memory and GPipe's at that m.

Problems, with solutions

Try each problem before opening its solution.

1. MinHash and banding. Show that for a random permutation, Pr[min over A = min over B] = J(A, B). With b = 20 bands of r = 5, at what similarity is a pair caught half the time? How often at s = 0.8?

Solution

Under a random permutation every element of A ∪ B is equally likely to come first. The two minima agree exactly when that first element lies in A ∩ B, so the probability is |A ∩ B| / |A ∪ B| = J. A band of r minhashes agrees with probability s^r, and a pair is caught if any of the b bands agrees: 1 − (1 − s^r)^b. Setting this to ½: s = (1 − 2^(−1/b))^(1/r) = (1 − 2^(−1/20))^(1/5) ≈ 0.509. At s = 0.8: 1 − (1 − 0.8⁵)²⁰ = 1 − 0.672²⁰ ≈ 0.9996.

2. The ring's bound. An all-reduce of 10 GB of gradients over p = 64 GPUs with 50 GB/s each: find the ring's bandwidth time, and show that no algorithm can beat it.

Solution

The ring sends 2(p − 1)/p · n per GPU: 2 · 63/64 · 10 GB / 50 GB/s ≈ 0.394 s (plus 2(p − 1) latencies). Lower bound: follow one number. Some GPU is the first to hold its full sum; every other GPU's value must have reached it, which takes at least p − 1 messages. At that moment no other GPU holds the sum, so each of the other p − 1 needs at least one more message. So at least 2(p − 1) values are sent per number, 2(p − 1)n in all, and with p GPUs receiving at most B each, the time is at least 2(p − 1)n/(pB), the ring's.

3. ZeRO for a 70B model. Mixed-precision Adam (K = 12) on 512 GPUs: bytes per GPU without ZeRO and with stages 1, 2 and 3. How much more does stage 3 communicate?

Solution

Without ZeRO: 16Ψ = 1,120 GB per GPU (impossible). Stage 1: 4Ψ + 12Ψ/512 ≈ 281.6 GB. Stage 2: 2Ψ + 14Ψ/512 ≈ 141.9 GB. Stage 3: 16Ψ/512 ≈ 2.19 GB, plus the layer being gathered and the activations. Stages 1 and 2 move 2Ψ per step, like an all-reduce; stage 3 gathers the parameters twice (forward and backward) and reduce-scatters the gradients: 3Ψ, 1.5 times as much.

4. Bubbles. A pipeline of p = 16 stages and m = 64 micro-batches: the bubble for GPipe, for 1F1B, interleaved with v = 4, and ZB-H1 when t_F = t_B = t_W.

Solution

GPipe and 1F1B: (p − 1)/(m + p − 1) = 15/79 ≈ 19.0% (1F1B only changes the memory). Interleaved: (p − 1)/(vm + p − 1) = 15/271 ≈ 5.5%. ZB-H1: the bubble is (p − 1)(t_F + t_B − t_W) = 15 units against m(t_F + t_B + t_W) = 192 busy units: 15/207 ≈ 7.2%.

5. Loss scaling. Gradients of size 2⁻³⁰ in FP16: which loss scale brings them to FP16's smallest normal number? Why does BF16 need none?

Solution

FP16's smallest normal number is 2⁻¹⁴, so S = 2¹⁶ (any S ≥ 2⁶ already keeps them from flushing to zero, at reduced precision, since the smallest subnormal is 2⁻²⁴). BF16 has FP32's eight exponent bits: its smallest normal number is 2⁻¹²⁶, far below 2⁻³⁰.

6. Young's interval. Checkpoints cost δ = 60 s and failures come every M = 2 h: find Young's interval and the share of time it wastes, to first order.

Solution

τ* = √(2δM) = √(2 · 60 · 7,200) ≈ 930 s ≈ 15.5 min. The waste δ/τ + τ/(2M) is then 2 · 60/930 ≈ 12.9% (at the optimum the two terms are equal, so the waste is √(2δ/M)), before the time spent restarting.

Notes and sources

Glossary

English 中文
pretraining run, frontier run 预训练,前沿训练
Common Crawl, WARC, WET Common Crawl,WARC,WET
text extraction, boilerplate 文本抽取,模板噪声(样板文字)
language identification 语言识别
URL blocklist URL黑名单
deduplication, exact / near-duplicate 去重,完全重复 / 近似重复
shingle (word n-gram) 片段(词n元组)
Jaccard similarity 杰卡德相似度
MinHash, signature 最小哈希(MinHash),签名
locality-sensitive hashing (LSH), band, bucket 局部敏感哈希(LSH),带,桶
quality classifier, annotator 质量分类器,标注模型
educational value 教育价值
contamination, n-gram overlap 数据污染,n元组重叠
data mixture, domain weights, proxy model 数据配比,领域权重,代理模型
synthetic data, rephrasing 合成数据,改写
model collapse 模型崩溃
epoch, repetition, effective data 轮次,重复,有效数据
causal LM, masked LM, span corruption 因果语言模型,掩码语言模型,片段破坏
fill in the middle (FIM), prefix / suffix / middle 中间填充(FIM),前缀 / 后缀 / 中间
warmup–stable–decay (WSD), cooldown 预热–稳定–衰减(WSD),冷却
annealing, mid-training, microanneal 退火,中期训练,微退火
long-context extension, RoPE base (ABF) 长上下文扩展,RoPE基频(ABF)
mixed precision, master weights 混合精度,主权重
activation memory, activation recomputation (checkpointing) 激活内存,激活重计算
data parallelism 数据并行
bandwidth-optimal, lower bound 带宽最优,下界
ZeRO (stages 1–3), sharding ZeRO(第1–3阶段),分片
FSDP (fully sharded data parallel) FSDP(全分片数据并行)
tensor parallelism, column / row split 张量并行,按列 / 按行切分
sequence parallelism 序列并行
pipeline parallelism, stage, micro-batch 流水线并行,阶段,微批次
pipeline bubble, 1F1B, interleaved schedule 流水线气泡,1F1B,交错调度
zero bubble, DualPipe 零气泡,DualPipe
context parallelism, ring attention 上下文并行,环形注意力
expert parallelism, all-to-all 专家并行,全对全通信
online softmax 在线softmax
model FLOPs utilization (MFU) 模型浮点利用率(MFU)
loss scaling, dynamic loss scaling, overflow, underflow 损失缩放,动态损失缩放,上溢,下溢
gradient accumulation 梯度累积
fine-grained (tile-wise, block-wise) scaling, microscaling (MX) 细粒度(按块、按瓦片)缩放,微缩放(MX)
quantization-aware training (QAT) 量化感知训练(QAT)
loss spike, rollback 损失尖峰,回滚
attention logit growth, QK-norm 注意力logit增长,QK归一化
z-loss, log-partition (log Z) z-loss,对数配分(log Z)
QK-Clip, MuonClip QK-Clip,MuonClip
multi-token prediction (MTP), acceptance rate 多词元预测(MTP),接受率
self-speculative decoding, draft 自推测解码,草稿
fault tolerance, interruption, MTBF 容错,中断,平均故障间隔
checkpoint, checkpoint interval (Young's rule) 检查点,检查点间隔(Young法则)
goodput 有效吞吐
recipe 配方

Sources

Checked against the primary sources on 23 October 2026 (arXiv papers and technical reports, model cards, vendor and lab pages):

  • Llama 3: Table 4 (TP, CP, PP, DP, TFLOP/s, MFU), Table 5's counts (the table's percentages don't divide by 419; only counts are shown), "higher than 90%" effective training time, three manual interventions, 1–2% diurnal variation, "tens of megawatts", checkpoints of 1 MB to 4 GB per GPU, Tectonic at 2 TB/s sustained, the 2 × CP chunk split, annealing over the last 40M tokens, six long-context stages over ~800B tokens, RoPE base 500,000.
  • DeepSeek-V3: E4M3 on all tensors (a custom E5M6 for a few activations), 1 × 128 / 128 × 128 scales, promotion every 128 elements, ~14-bit accumulation (~2% error at K = 4096), < 0.25% loss error; Table 2's bubble formulas; 2,048 H800s, NVLink 160 GB/s, IB 50 GB/s, 20 of 132 SMs; PP 16, EP 64 over 8 nodes, ZeRO-1, ≤ 4 nodes per token; the learning-rate, batch and MTP schedules; FIM 0.1 (PSM); YaRN 4K → 32K → 128K; 2.788M GPU-hours.
  • DeepSeek-V4 (arXiv 2606.19348, April 2026): Muon (hybrid Newton–Schulz, 10 iterations), RMSNorm on queries and KV instead of QK-Clip, 32T (Flash) and 33T (Pro) tokens, batches to 75.5M / 94.4M tokens, MTP 0.3 → 0.1, anticipatory routing and SwiGLU clamping, 4K → 16K → 64K → 1M, FP4 QAT for experts in post-training.
  • Kimi K2: MuonClip, τ = 100, 12.7% of heads clipped in the first 70k steps, 15.5T tokens without a spike, H800 cluster (count not stated), the rephrasing table. Kimi K3's model card: MXFP4 weights and MXFP8 activations from QAT (no training details used). Moonlight: "~2× computational efficiency".
  • Nemotron 3 Super (NVIDIA, March 2026): 120B / 12B active, NVFP4 pretraining, 25T tokens, MTP layers. NVFP4 paper: 12B on 10T tokens, MMLU-Pro 62.58 vs 62.62, 16% of linear layers in BF16, 16 × 16 Hadamard transforms. MXFP8 paper: up to 8B parameters, 15T tokens.
  • FineWeb / FineWeb-Edu: 96 snapshots, 15T tokens, lid ≥ 0.65, 5-grams, 112 hashes = 14 × 8; global vs per-snapshot dedup; 460k annotations (the released dataset has 467,424 rows), 410k for training, F1 82%, 6,000 H100 hours, 1.3T tokens, MMLU 33 → 37, ARC 46 → 57; the prompt is paraphrased on screen.
  • Olmo 3: 5.9T pretraining, 100B midtraining, 50B/100B long context to 65K, 1,024 H100s, 43%/41% MFU; deduplication 67% exact, 23% MinHash, 14% of bytes by substrings, 38.7B → 9.7B documents. SmolLM3: 11.2T tokens, 384 H100s for 24 days, stage mixtures, 4K → 32K → 64K with RoPE θ 1.5M and 5M. Qwen3: S1 30T at 4K, S2 ~5T, S3 at 32K with ABF 10⁴ → 10⁶, 119 languages. GLM-4.5: 23T, QK-Norm, MTP, Muon. Llama 4: FP8 on 32K GPUs, 390 TFLOP/s per GPU, 30T tokens.
  • PaLM: 6,144 TPU v4, MFU 45.7% without and 46.2% with attention (238.3k tokens/s), ~20 spikes, restart ~100 steps back and skip 200–500 batches, z-loss 10⁻⁴ log² Z. MegaScale: 55.2% MFU, 175B, 12,288 GPUs.
  • ZeRO: K = 12, 2Ψ + 2Ψ + KΨ = 16Ψ, Figure 1's 120 / 31.4 / 16.6 / 1.9 GB, 1.5× communication for stage 3.
  • Megatron-LM: 8.3B on 512 GPUs, 15.1 PFLOP/s, 76% scaling; two all-reduces forward and two backward per layer. GPipe: bubble O((K − 1)/(M + K − 1)), negligible for M ≥ 4K. Zero Bubble: up to 23% (31% with relaxed memory) over 1F1B. Ring all-reduce lower bound: Patarasuk & Yuan (2009), as restated by later work (some process sends and some receives at least 2(N − 1)M/N); the proof on screen is our own counting argument.
  • Muennighoff et al. (2023): effective data D′ = U + U·R*(1 − e^{−R/R*}) with R the repetitions beyond the first epoch (their Eq. 5) and the fitted R* = 15.387756 (Sec. 3.1, Eq. 17 uses 15.4); the Mixture chapter draws it as epochs' worth of new data against epochs over the same tokens. MXFP8: blocks of 32 values sharing one power-of-two (E8M0) scale, as in the OCP microscaling format that Mishra et al. use. The QK-Clip picture in the Stability chapter is labelled schematic: it shows only what the report states (logits held at τ, no head clipped after 70k steps), not its curve.
  • Common Crawl: founded 2007 by Gil Elbaz, crawling since 2008, over 10 PB (its own pages). GPT-1: "1 month on 8 GPUs" (OpenAI's 2018 post). Lee et al. (2022): "emit memorized text ten times less frequently".
  • Dettmers et al. (2022), LLM.int8(): a few feature dimensions of large transformers take much larger values than the rest (emergent outlier features), the reason FP8 recipes scale per tile rather than per tensor.
  • Gloeckle et al.: 13B, +12% HumanEval, +17% MBPP, up to 3× faster with 4-token prediction; at the smallest sizes multi-token prediction scored below next-token prediction (their Figure 3).
  • Our measurements: the precision runs emulate each format by rounding the inputs of every matrix product inside the blocks (forward and backward) and summing in FP32; the embedding, output head and attention's own products stay in FP32 (as in DeepSeek-V3). The tile in our FP8 run is 32 (our model is 64 wide); DeepSeek's is 128. The FP16 accumulation experiment divides each step's loss by 64 before the backward pass and multiplies the gradients back after it, which is what accumulating over 64 micro-batches does to the gradients' size. The collectives were timed on a shared machine. The restart time in the failure simulation (10 minutes) is illustrative. Every model trained here has its training on screen: the quality classifier's F1 after 1 to 25 passes over its labels (the cut re-chosen each time), the 32 RegMix proxies and the six mixture tests as held-out curves, the 24 stability runs, the precision, accumulation and MTP runs, both recipes (two seeds each) and the data-parallel check's six steps. The MTP module's cost is counted in FLOPs per token (mtp_cost): in a model with a 4,096-token vocabulary and width 64, the second pass through the output head is most of it, which is why it is far larger than in DeepSeek-V3.
  • On screen, text from crawled pages has e-mail addresses and phone numbers blanked (said in common.py). The bars under the collapse chain in the Mixture chapter (a Zipf-shaped frequency list losing rare words) are a schematic; the curves after them are computed.
  • Not used: training-token counts for Kimi K3; Kimi K2's GPU count; OLMo 3's optimizer; a DualPipe simulation (its formula is cited instead).

References: Broder (1997); Indyk & Motwani (1998); Lee et al. (2022); Penedo et al., FineWeb (2024); Li et al., DCLM (2024); Joulin et al. (2016–17); Xie et al., DoReMi (2023); Liu et al., RegMix (2025); Maini et al., WRAP (2024); Shumailov et al. (Nature, 2024); Gerstgrasser et al. (2024); Muennighoff et al. (2023); Devlin et al. (2019); Raffel et al. (2020); Bavarian et al. (2022); Hu et al., MiniCPM (2024); Hägele et al. (2024); Xiong et al. (2023); Rajbhandari et al., ZeRO (2020); Zhao et al., FSDP (2023); Shoeybi et al., Megatron-LM (2019); Narayanan et al. (2019, 2021); Korthikanti et al. (2022); Huang et al., GPipe (2019); Qi et al., Zero Bubble (2024); Patarasuk & Yuan (2009); Liu, Zaharia & Abbeel, Ring Attention (2023); Milakov & Gimelshein (2018); Chowdhery et al., PaLM (2022); Jiang et al., MegaScale (2024); Micikevicius et al. (2018, 2022); Mishra et al., MXFP8 (2025); NVIDIA, NVFP4 (2025), Nemotron 3 Super (2026); Dehghani et al. (2023); Wortsman et al. (2024); Liu et al., Moonlight (2025); Kimi Team, K2 (2025); Gloeckle et al. (2024); Young (1974); Llama Team (2024); DeepSeek-AI, V3 (2024), V4 (2026); Qwen Team, Qwen3 (2025); Team OLMo, OLMo 2 (2025), Olmo 3 (2025); Hugging Face, SmolLM3 (2025), The Ultra-Scale Playbook (2025), The Smol Training Playbook (2025); GLM-4.5 Team (2025); Meta, Llama 4 (2025); Moonshot AI, Kimi K3 model card (2026). Books: J. Leskovec, A. Rajaraman & J. D. Ullman, Mining of Massive Datasets, ch. 3.

About this partfrom its README

Part 18 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus). How a frontier language model is pretrained: where the text comes from and how it is cleaned (extraction, language identification, MinHash deduplication, quality classifiers, contamination checks, mixtures, synthetic data and model collapse); what the model is asked to predict and how training is staged (objectives, warmup–stable–decay, annealing and mid-training, long context); the arithmetic of a run in operations and bytes; the five ways to cut a model across devices (data, ZeRO/FSDP, tensor, pipeline, context, expert) and how much of the hardware a run really uses; training in fewer bits (BF16, FP16 with loss scaling, FP8 with fine-grained scales, MXFP8, NVFP4); keeping the run stable (QK-norm, z-loss, QK-Clip with Muon); multi-token prediction; and surviving failures at sixteen thousand GPUs. Everything that can be measured on one computer is: a sample of Common Crawl's September 2026 crawl goes through the whole data pipeline, four processes of this computer act as a cluster through PyTorch's own distributed library, and a dozen training runs on the series' thirty novels test each piece, ending with a model trained with the full 2026 recipe against the 2020 one, on the scoreboard.

  • Sixteen thousand GPUs, fifty-four days. Chips on one training run, 2018–2025 (GPT-1's eight GPUs for a month to Llama 4 Behemoth's 32,000; log scale); Llama 3's run as 16,384 dots: 3.8 × 10²⁵ FLOP, 15.6T tokens, 466 interruptions in 54 days (419 unplanned), one every 3.1 hours (computed); the question; the miniature; the plan.
  • 1. Anatomy of a frontier run. The pipeline from crawl to post-training; Olmo 3 (5.9T + 100B mid-training + 50B long context) and SmolLM3 (three stages) drawn to scale; six runs of 2024–26 (Llama 3.1 405B, DeepSeek-V3, Kimi K2, Olmo 3, Nemotron 3 Super, DeepSeek-V4-Pro): tokens, chips, number format, optimizer; C ≈ 6ND for Llama 3.1 (3.79 × 10²⁵ against the reported 3.8) and DeepSeek-V3 (37B active); 2.788M H800 GPU-hours, $5.576M, 180k GPU-hours (3.7 days on 2,048 GPUs) per trillion tokens.
  • 2. From the web to text. Common Crawl (Gil Elbaz, 2007; crawls since 2008; over 10 PB), WARC and WET; our sample (3 WET files × 3 slices of 3 MiB from CC-MAIN-2026-39); extraction with Trafilatura on WARC slices (HTML bytes → text bytes; one page shown; FineWeb's WARC-vs-WET ablation); a URL blocklist; fastText's lid.176 language identifier, FineWeb's 0.65 threshold, 50-word minimum: the funnel to the English pages that go on.
  • 3. Near-duplicates: MinHash and LSH. Duplicates and memorization (Lee et al. 2022: ten times less memorized text); shingles (word 5-grams) and Jaccard similarity; MinHash (Broder 1997) derived: Pr[min agree] = J; checked on 3,000 page pairs; banding derived: 1 − (1 − s^r)^b with FineWeb's 14 bands of 8; the S-curve predicted and measured; results: our sample, the thirty Gutenberg licence pages (all 435 pairs caught, no novel pair), Olmo 3's exact / MinHash / substring deduplication (67% / 23% / 14% of bytes; 38.7B → 9.7B documents), FineWeb's per-crawl finding.
  • 4. Quality, and keeping the test clean. FineWeb-Edu (Llama-3-70B's additive 0–5 prompt on 460k pages, a linear head on an embedding model trained on 410k, F1 82% at 3, 1.3T tokens; MMLU 33 → 37%, ARC 46 → 57% at 1.71B/350B); our fastText classifier trained on 13,000 of the released annotations (F1, precision, recall against theirs); its verdicts on our crawl sample; DCLM; contamination: GPT-3's 13-gram check applied to the scoreboard's passage and to our held-out text (computed).
  • 5. Mixtures, synthetic data and collapse. The Pile's hand-set weights; DoReMi (280M proxy, Group DRO, 8B: +6.5 points, 2.6× fewer steps); RegMix (512 models of 1M parameters, regression; the best of 64 mixtures at 1B); our RegMix on four groups of the novels, targeted at chapters 1 and 3 of The Maltese Falcon and tested on chapter 2 (32 proxy runs, leave-one-out fit, the pick against the natural and uniform mixtures at a larger size, two seeds); repetition (Muennighoff et al.: about four epochs are as good as new data; their fitted worth of repeated data, 1 + R*(1 − e^{−R/R*}) epochs of new data with R* = 15.4, drawn); rephrasing (WRAP, ~3× faster; Kimi K2's SimpleQA 23.76 → 27.39 → 28.94); model collapse in a unigram model (replace against accumulate; Shumailov et al., Gerstgrasser et al.).
  • 6. What the model is asked to predict. One sentence of Pride and Prejudice under the causal, masked (15%; 80/10/10), span-corruption (15%, spans of ~3, sentinels) and fill-in-the-middle (PSM) objectives; prediction targets per 256 tokens; FIM for free (Bavarian et al. 2022); DeepSeek-V3's FIM rate of 0.1.
  • 7. Annealing, mid-training, long context. Cosine against warmup–stable–decay (MiniCPM; Hägele et al.); our 2026-recipe run and a cooldown branched from its middle; annealing on the best data (Llama 3's last 40M tokens; Qwen3's 5T stage 2; Olmo 2's mid-training and microanneals; SmolLM3's stage mixtures); long-context stages (Llama 3, DeepSeek-V3, Qwen3, Olmo 3, DeepSeek-V4) and RoPE's slowest wavelength 2π θ^{(d−2)/d} for θ = 10⁴, 5 × 10⁵, 10⁶ (computed).
  • 8. Counting FLOPs and bytes. 6ND derived (2 forward, 2 + 2 backward); PyTorch's FLOP counter on our model (backward = 2 × forward; total = 6NT; attention's extra share); 16 bytes per parameter in mixed-precision Adam (ZeRO's 2 + 2 + 12); Llama 3.1 405B's 6.5 TB, DeepSeek-V3, Kimi K2; activations counted from autograd's saved tensors against sequence length (fused attention: linear; unfused: + a T × T matrix per head; recomputed: one d per token per layer); Korthikanti et al.'s sbh(34 + 5as/h) at Llama 3.1's shape.
  • 9. Data parallelism and the all-reduce. Copies of the model, slices of the batch; 4 processes against one, checked; the ring all-reduce as reduce-scatter + all-gather on a ShardGrid; the bandwidth lower bound 2(p−1)/p · n/B proved (Patarasuk & Yuan 2009), with the counting argument drawn on four GPUs. (The three collectives were also timed with torch.distributed against the α–β model, collectives in compute.py; the result is in the notes below, not on screen.)
  • 10. ZeRO and FSDP. ZeRO's three stages (Rajbhandari et al. 2019) on a ShardGrid; memory per GPU derived (the paper's 120 / 31.4 / 16.6 / 1.9 GB, computed); communication (2Ψ, 2Ψ, 3Ψ); FSDP; Llama 3 (FSDP) and DeepSeek-V3 (ZeRO-1); our ZeRO-3 on four processes, layer by layer, against one process: parameters, memory and traffic measured.
  • 11. Tensor parallelism. Megatron-LM's column-then-row split of the MLP derived, the f and g operators; attention by heads; four all-reduces per layer; TP inside the NVLink domain (Llama 3: TP 8, innermost); sequence parallelism; one block of our model split across 2 and 4 processes, checked against the whole block.
  • 12. Pipeline parallelism. GPipe (Huang et al. 2019) as a Gantt chart filling in (simulated exactly); the bubble (p − 1)/(m + p − 1) derived and checked against simulations for p = 4, 8, 16; 1F1B's memory; interleaving (Llama 3); ZB-H1 (Qi et al. 2024: (p − 1)(F + B − W)); DualPipe's bubble formula (DeepSeek-V3, Table 2).
  • 13. Context, experts, and utilization. Ring attention (Liu, Zaharia & Abbeel 2023) on four processes, exact; causal load imbalance and the 2 × CP chunk assignment (Llama 3); expert parallelism and all-to-all (DeepSeek-V3: EP 64 over 8 nodes, ≤ 4 nodes per token, IB 50 against NVLink 160 GB/s, 20 of 132 SMs for communication); Llama 3's 4D layouts (Table 4); MFU defined (PaLM 45.7%/46.2%, computed), MegaScale 55.2%, Llama 3 38–43%, Olmo 3 43%; our runs' MFU on this CPU.
  • 14. Fewer bits. Formats on a log₂ scale with the measured distribution of our activation gradients (the share below FP16's normal and subnormal range); loss scaling derived (Micikevicius et al. 2018), dynamic scaling; six training runs (FP32, BF16, FP16 without and with loss scaling, FP8 per tensor, FP8 per tile), two seeds; the same in FP16 with a loss divisor of 64 as a gradient-scale surrogate (without actual micro-batch accumulation); one tile of the series' model's activations scaled into E4M3's range per tensor and per tile (fp8_scale), and the per-tensor against per-tile error; DeepSeek-V3's FP8 recipe (1 × 128 and 128 × 128 scales, FP32 promotion every 128, < 0.25% loss error); MXFP8 (8B/15T), NVFP4 (12B/10T, MMLU-Pro 62.58 against 62.62), Nemotron 3 Super (NVFP4, 25T), Kimi K3 and DeepSeek-V4 (FP4 QAT).
  • 15. Keeping the run stable. PaLM's ~20 spikes and rollbacks; attention-logit growth and QK-norm (bound derived); our learning-rate sweep (plain / QK-norm / QK-norm + z-loss, 2 seeds): largest attention logit and final loss; the z-loss derived and log Z measured (in our 150-step runs the z-loss leaves log Z where it was: the narration branches on whether the difference beats the seeds' spread); Muon at scale (Moonlight ~2×), Kimi K2's QK-Clip (τ = 100, 12.7% of heads, 15.5T tokens without a spike; drawn as a schematic), DeepSeek-V4's anticipatory routing and SwiGLU clamping.
  • 16. Predicting two tokens ahead. Gloeckle et al. 2024 (13B: +12% HumanEval, +17% MBPP; worse at the smallest sizes); DeepSeek-V3's sequential MTP module (λ 0.3 → 0.1; 85–90% acceptance, 1 + a tokens per step, 1.8× TPS); our model with and without the module, two seeds, and the module's cost in FLOPs per token (mtp_cost: in a model this small the second pass through the output head dominates); its acceptance rate in greedy self-speculation.
  • 17. When hardware fails. Llama 3's interruptions by cause (Table 5), job-interruption interval 3.1 h (not a per-GPU lifetime),

    90% effective training, diurnal 1–2%, power swings; Young's checkpoint interval √(2δM) derived (δ from Llama 3's checkpoint sizes and storage bandwidth); a 54-day run with random failures simulated over checkpoint intervals.

  • 18. Our own full recipe. The 2020 recipe (AdamW, cosine) against the 2026 recipe (Muon, WSD, QK-norm, z-loss) at equal model, data, steps and seed, and the whole comparison again from a second seed (the verdict must beat the spread between seeds); a training replay (held-out loss and samples at the same steps); held-out loss, bits per character, largest attention logit; the scoreboard row against Parts 1 and 14 and the series' model.
  • Recap, where it comes back (Parts 19, 22–23, 27, 28, 30, 31), the problem set, Part 19's teaser, references.

Run from the repo root:

What is computed and built

Filled in from .cache/ai18/ after compute.py runs (python -m videos.ai.ai18.results):

The historical outcomes below are preserved while original inputs are restored for QA. The duplicate counts are not yet accepted as disjoint: the current producer includes exact copies in its cluster-removal count, then adds them again in its total share. A separate repair must be measured on the original pages before those counts or percentages are reused. The FP16 loss-divisor experiment is a gradient-scale surrogate, as clarified below.

  • From published figures: Llama 3.1's 6ND = 3.79e+25 FLOP (reported 3.8e25); its MFU from Table 4's TFLOP/s over 989: 43.5%, 40.4%, 38.4% (reported 43/41/38%); one unplanned job interruption every 3.09 h; idealized maximum-size checkpoint write ≈ 33 s, illustrative Young's interval 14.2 min; PaLM's MFU without attention 45.7%; DeepSeek-V3 $5.576M, 3.66 days per trillion tokens on 2,048 GPUs; 16 bytes/parameter: Llama 3.1 6.48 TB (≥ 81 H100s); ZeRO's example 120.00, 31.41, 16.64, 1.88 GB.
  • Common Crawl sample (CC-MAIN-2026-39, WET files [0, 33333, 66666]): 4,310 pages, 64 languages; 96 blocked by URL; English 1,728, of which 1,398 kept (p ≥ 0.65, ≥ 50 words). WARC slices: 387 HTML pages, 42.6 MB of HTML → 1.28 MB of text (3.0%; median page 2.3%).
  • MinHash-LSH (112 hashes, 14 × 8): on 3,000 page pairs, per-hash agreement vs Jaccard mean gap 0.026; measured collision rate within 0.105 of 1 − (1 − s⁸)¹⁴ in every bin; s at P = ½: 0.685. Sample: 3 exact and 8 near duplicates of 1,398. Gutenberg licences: 435/435 pairs caught (J ≥ 0.990); novels 0/435.
  • Quality classifier (fastText, 13,000 of FineWeb-Edu's Llama 3 annotations; cut 0.21 on P(score ≥ 3)): F1 59.0% (precision 54.5%, recall 64.3%) on 1,000 held-out pages, against FineWeb-Edu's 82%; kept 62 of 1,398 crawl pages (4.4%).
  • Contamination: the scoreboard's passage shares 0 of 4,042 13-grams (1 of 4,047 8-grams) with the training text; 6 of 2,758 held-out paragraphs share a 13-gram.
  • RegMix on the novels: 32 proxy runs, leave-one-out correlation 0.69; pick 92%, 3%, 1%, 4% (natural 16%, 27%, 15%, 42%); loss on the scoreboard's chapter, nats per token, mean of two seeds: natural 5.619; uniform 5.626; regmix 5.555.
  • Model collapse (unigram, 50,000 samples, 30 generations, 5 seeds): support 3108 → 1075 tokens (replace) vs 3108 (accumulate); cross-entropy on real text 9.82 → 10.64 vs 10.04 bits.
  • FLOP counter (our 128 × 4 model, 256 tokens): backward/forward 2.000; total / 6NT 0.9992; attention adds 20.1%; recomputation 15.5% more. Activations: 23.55 d per token per layer (FP32, fused attention), 1.00 d recomputed, unfused attention + 1.06 T² per head per layer.
  • Collectives (gloo, 4 processes): α = 66 µs, B = 2.37 GB/s from point-to-point; large messages took all_reduce 7.2×, reduce_scatter 16.5×, all_gather 13.1× the α–β prediction (load average 12 on 4 cores); sums checked: True.
  • Parallelism checked on 4 processes (285,856-parameter model, 6 AdamW steps): largest parameter difference from one process, DP 2.2e-05, ZeRO-3 2.1e-05; ZeRO-3 keeps 4.00× less and sends 1.50× more. Tensor parallel (2 / 4 ranks): output error 1.3e-06 / 1.2e-06. Ring attention: 3.3e-07.
  • Pipeline (p = 4, m = 8, simulated): bubble GPipe 27.3%, 1F1B 27.3%, interleaved 15.8%, ZB-H1 11.1% (all equal to their formulas); peak micro-batches on GPU 0: GPipe 8, 1F1B 4.
  • Precision (250 steps, two seeds, final held-out loss): fp32 5.592–5.659; bf16 5.588–5.659; fp16 5.592–5.661; fp16_scaled 5.591–5.659; fp8_tensor 5.580–5.652; fp8_tile 5.584–5.639. Activation gradients: 100% below FP16's smallest normal, 34% flushed to zero. E4M3 error on the series' model: per tensor 2.65%, per 1 × 128 tile 2.43%.
  • FP8 scales on one 1 × 128 tile of the series' model's activations: its tensor's largest value 4.30, the tile's 2.35 (scales 448/4.30 and 448/2.35).
  • FP16 gradient-scale surrogate (loss divided by 64, gradients restored before update): fp16 6.605–6.609; fp16_scaled 5.592–5.657.
  • Stability (learning rates [0.003, 0.01, 0.03, 0.1], final loss, mean of 2 seeds): plain: 6.05, 5.95, 6.22, 6.39 (max logit 19, 48, 172, 2062); qk: 6.11, 6.02, 6.22, 6.32 (max logit 6, 7, 9, 21); qkz: 6.12, 6.05, 6.05, 6.33 (max logit 6, 7, 8, 23). Final mean log Z at 0.003: 7.97 without the z-loss, 7.96 with it (within the seeds' spread of 0.06).
  • MTP (500 steps, two seeds): next-token loss without 5.193, with 5.126; acceptance 85.3%, 72.4%; extra arithmetic 88%.
  • Recipes (3.0M tokens, 732 steps, seed 0 / seed 1): 2020 held-out 4.487 / 4.498, 2.036 / 2.052 bpc; 2026 4.251 / 4.253, 1.946 / 1.950 bpc; largest attention logit 44 vs 11 (seed 0); WSD cooldown branch at 458 steps 4.517 vs 4.570 still stable.
  • MFU on this CPU (peak 67.1 GFLOP/s, one core): 2020 recipe 15%, 2026 recipe 11%.
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Anatomy of a frontier run (cited reports).
  2. Data: extraction, language ID, MinHash-LSH dedup with the collision probability derived, quality classifiers (FineWeb-Edu), contamination.
  3. Mixtures (DoReMi, RegMix); synthetic data and rephrasing; model collapse.
  4. Objectives: causal LM, MLM, span corruption, FIM.
  5. Annealing and mid-training; long-context extension.
  6. Accounting: 6ND; memory (weights, grads, Adam states, activations).
  7. Data parallel: ring all-reduce derived (bandwidth-optimal); ZeRO 1/2/3 and FSDP.
  8. Tensor parallel: Megatron's column/row split.
  9. Pipeline: bubble (p−1)/(m+p−1), 1F1B, DualPipe.
  10. Context parallel (ring attention); expert parallel; MFU.
  11. Precision: bf16 vs fp16 with loss scaling; FP8 with fine-grained scaling (DeepSeek-V3); MXFP8/NVFP4 training.
  12. Stability: z-loss, QK-norm.
  13. Multi-token prediction; fault tolerance at 16k GPUs (Llama 3 statistics).
  14. Our full-recipe model (scoreboard row).

Visuals: ShardGrid collectives; a pipeline Gantt chart filling in.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答

1. MinHash与分带。 证明:对随机排列,Pr[A上的最小值 = B上的最小值] = J(A, B)。用 b = 20 个带、每带 r = 5 行时,相似度为 多少的一对文档有一半的概率被找出?s = 0.8 时概率是多少?

解答

在随机排列下,A ∪ B 中每个元素排在最前的可能性相同。两个最小值相等,当且仅当这个最前的元素在 A ∩ B 里,所以概率是 |A ∩ B| / |A ∪ B| = J。一个带的 r 个最小哈希全部相等的概率是 s^r,只要 b 个带中有一个相等,这对文档就被找出:1 − (1 − s^r)^b。 令它等于二分之一:s = (1 − 2^(−1/20))^(1/5) ≈ 0.509。s = 0.8 时:1 − (1 − 0.8⁵)²⁰ = 1 − 0.672²⁰ ≈ 0.9996。

2. 环形算法的下界。 在 p = 64 块GPU上对10 GB梯度做全规约,每块GPU带宽50 GB/s:求环形算法的带宽时间,并证明没有算法能更快。

解答

环形算法每块GPU发送 2(p − 1)/p · n:2 · 63/64 · 10 GB / 50 GB/s ≈ 0.394秒(另加 2(p − 1) 次延迟)。下界:跟踪一个数。 总有一块GPU最先得到它的完整和;其他每块GPU的值都必须传到它那里,至少需要 p − 1 条消息。在那一刻,别的GPU都还没有这个和,所以 其余 p − 1 块GPU每块至少还要再收一条消息。于是每个数至少发送 2(p − 1) 个值,总共 2(p − 1)n;p 块GPU同时接收、每块至多 B, 时间至少是 2(p − 1)n/(pB),正是环形算法的时间。

3. 70B模型的ZeRO。 混合精度Adam(K = 12),512块GPU:不用ZeRO、用第1、2、3阶段时,每块GPU各需多少字节?第3阶段多传多少?

解答

不用ZeRO:16Ψ = 1,120 GB 每块GPU(不可能)。第1阶段:4Ψ + 12Ψ/512 ≈ 281.6 GB。第2阶段:2Ψ + 14Ψ/512 ≈ 141.9 GB。 第3阶段:16Ψ/512 ≈ 2.19 GB,再加上正在收集的那一层和激活值。第1、2阶段每步传 2Ψ,与全规约相同;第3阶段前向和反向各收集一次 参数,再对梯度做规约-分散:3Ψ,是1.5倍。

4. 气泡。 p = 16 级流水线、m = 64 个微批次:GPipe、1F1B、v = 4 的交错调度,以及 t_F = t_B = t_W 时ZB-H1的气泡各是多少?

解答

GPipe和1F1B:(p − 1)/(m + p − 1) = 15/79 ≈ 19.0%(1F1B只改变内存)。交错调度:(p − 1)/(vm + p − 1) = 15/271 ≈ 5.5%。ZB-H1:气泡是 (p − 1)(t_F + t_B − t_W) = 15 个单位,忙碌时间是 m(t_F + t_B + t_W) = 192 个单位:15/207 ≈ 7.2%。

5. 损失缩放。 FP16中大小为 2⁻³⁰ 的梯度:多大的损失缩放能把它们提到FP16最小的正规数?为什么BF16不需要?

解答

FP16最小的正规数是 2⁻¹⁴,所以 S = 2¹⁶(因为最小的次正规数是 2⁻²⁴,S ≥ 2⁶ 就足以让它们不被冲成零,只是精度较低)。 BF16有FP32的8个指数位:最小的正规数是 2⁻¹²⁶,远小于 2⁻³⁰。

6. Young的间隔。 保存一次检查点要 δ = 60秒,故障平均每 M = 2小时一次:求Young的间隔,以及一阶近似下浪费的时间比例。

解答

τ* = √(2δM) = √(2 · 60 · 7,200) ≈ 930秒 ≈ 15.5分钟。此时浪费 δ/τ + τ/(2M) = 2 · 60/930 ≈ 12.9%(最优点上两项相等, 所以浪费是 √(2δ/M)),还不算重启所花的时间。

Build the film

python -m videos.ai.ai18.compute        # the part's numbers, into .cache/ai18
python tools/build.py ai18                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai18 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/ai/ai18. Setup: see the course page. Source of these notes: the README and the scenes' narration.