AAI, Built

Act III · The Transformer Era

Part 14 of 31

The Language-Model Lineage

how today's LLMs came to be

Undergraduatestarts at this level55 min of film16 chaptersprerequisites: Part 10, Part 12, Part 13

How did a model built to translate sentences become the engine of nearly everything?

The part opens in June 2017 with 'Attention Is All You Need', a translation model of 213 million parameters trained for three and a half days on eight graphics cards, and places every model it will meet by date and size. The Transformer is cut three ways: encoders, decoders and both. Pretraining on raw text and then fine-tuning becomes the recipe with ULMFiT, ELMo and GPT-1; BERT's masked objective wins the benchmarks, and T5 turns every task into text. The decoder then scales: GPT-2 does tasks it was never trained for, and GPT-3, 174.6 billion parameters counted from its shape and 3.14 x 10^23 operations by 6ND, learns from examples in its prompt. The part turns when a predictor of text becomes an assistant, through Codex, instruction tuning and ChatGPT in November 2022, and the frontier closes. Open weights follow from LLaMA to the models of 2026, converging on one recipe (pre-norm, RMSNorm, SwiGLU, rotary positions, grouped queries) and then splitting again, while training compute grows about five times a year. It ends on the series' novels, with a GPT-style and a BERT-style model of the same shape trained at matched budgets, and a family of small GPTs searched for learning in context.

What you need. Nothing beyond the earlier parts; the papers named are short and can be read alongside.

Mathematics and history
the 2017 Transformer, GPT-1 and BERT, T5, GPT-2/3, instruction tuning, ChatGPT, open weights, compute trends
Models, data
GPT, BERT, T5, LLaMA, DeepSeek, Qwen, Kimi

What you will be able to do

Undergraduate

  • Tell the lineage in order, from the 2017 Transformer through GPT-1, BERT, T5, GPT-2 and GPT-3 to ChatGPT and open weights, saying what each step changed.
  • Distinguish an encoder, a decoder and an encoder-decoder by what each position may see and by its training objective.

Master's

  • Count a decoder's parameters from its shape, 12Ld^2 plus the embeddings, and estimate its training compute as 6ND.
  • Write the causal and the masked language-model objectives, and work out how many prediction targets each gets from a sequence.
  • Compute a SwiGLU layer's width at equal parameters, and the size of a KV cache with and without grouped queries.

Research

  • Say what an equal-compute comparison of a causal and a masked model holds fixed and what it does not, and design a task on which both can be scored.
  • Design a test for in-context learning in a small model, with calibration against a content-free query, and state what a null result at that scale shows.

Engineering

  • Read a model card: layers, width, heads, context, total and active parameters, tokens per parameter, and whether a compute figure is published or an outside estimate.
  • Fit a growth rate to dated compute estimates and convert it to a doubling time, with its interval.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 26 min · Master's 52 min · Research 55 min · Engineering 38 min.

  1. 0From a translation paper to the open frontierUndergraduate3 min
  2. 1Attention is all you needUndergraduate4 min
  3. 2Pretrain, then fine-tuneUndergraduate3 min
  4. 3Masked language models and the benchmark eraUndergraduate3 min
  5. 4Everything is text to textMaster's3 min
  6. 5Unsupervised multitask learnersUndergraduate3 min
  7. 6Scale, and learning in contextMaster's4 min
  8. 7Code, and following instructionsMaster's3 min
  9. 8ChatGPT and the closed eraUndergraduate3 min
  10. 9Open weightsUndergraduate3 min
  11. 10The architecture convergesEngineering4 min
  12. 11The open frontier, 2024 to 2026Engineering4 min
  13. 12Compute, cost and dataEngineering3 min
  14. 13Our own lineage: GPT against BERTMaster's5 min
  15. 14Learning in context, in our own modelsResearch3 min
  16. Recap, problems, and what comes nextAll tracks3 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.

From a translation paper to the open frontierUndergraduate3 min

June 2017. Eight researchers at Google publish a paper with a confident title: Attention Is All You Need. Their model translates English into German and French. The larger version has 213 million parameters, and it trained for three and a half days on eight graphics cards. Here is every model this part will meet, placed by the date it appeared and by its size, on a scale where each step up is ten times more. By November 2022, the same building block, made much larger, was answering questions for anyone who asked: ChatGPT. And by the autumn of 2026, models you can download and run yourself have trillions of parameters. Moonshot AI's Kimi K3 has 2.8 trillion, about 13,000 times the 2017 Transformer.

How did a model built to translate sentences become the engine of nearly everything? That is the story of this part. It runs from the translation Transformer, through GPT and BERT, T5, GPT-2 and GPT-3, to ChatGPT, and on to the open-weight models of today. At each step we'll ask who built what, and when; what the step changed; and why it worked.

Along the way we'll rebuild the lineage in miniature, on the computer making this video, with the thirty novels this series reads. A GPT-style model, which learns to predict the next word, and a BERT-style model, which learns to fill in blanks, of exactly the same size, trained with the same approximate training budget, and compared fairly. And a family of GPT-style models of growing size, from thousand to million parameters, to see whether learning from examples in the prompt, the surprise of GPT-3, shows up at our scale.

This is Part 14 of AI, Built, in its third act, the transformer era. In this part: the 2017 Transformer, and the three ways to cut it; pretraining, from ULMFiT and GPT-1 to BERT and T5; scale, from GPT-2 to GPT-3, and learning from the prompt; how a predictor of text became an assistant; open weights, the design they converged on, and the frontier of 2026; the trends in compute, cost and data; and our own experiments.

1Attention is all you needUndergraduate4 min

In 2017 the best translation systems were recurrent networks, the sequence-to-sequence models of Part 10, with attention added on. They read a sentence one word at a time: the state after each word is computed from the state after the word before. That chain is the problem. Training can't run the steps of one sentence in parallel, and the last word reaches the first only through every state in between. The Transformer dropped the recurrence. Every position attends to every other position directly, all at once: a whole sentence goes through a layer in one parallel step, and any two words are a single hop apart.

Here is the model they built. An encoder reads the English sentence: six identical layers, each with self-attention, where every word looks at every other word, followed by a small feed-forward network applied to each position on its own. A decoder writes the German, one token at a time, with six layers of its own. Its self-attention is masked, so a position sees only the words already written. And a third sub-layer, cross-attention, lets each position of the output look at the encoded input. Around every sub-layer, a residual connection and layer normalization; and to tell the model where each word is, sine waves of many frequencies, added to the inputs. Part 13 took this machine apart. Here we care about what it became.

The paper gave two configurations. The base model: six layers in each stack, a width of 512, eight attention heads, 65 million parameters, trained for a hundred thousand steps, about twelve hours. The big model doubles the width and the heads: 213 million parameters, three hundred thousand steps, three and a half days. Both trained on the standard data of the 2014 Workshop on Machine Translation: four and a half million English–German sentence pairs, and thirty-six million English–French. On English to German, the big model scored 28.4 BLEU, a measure of overlap with human translations, more than two points above the best earlier systems, ensembles included. And it was cheap. The base model alone beat every earlier system, at a training cost about a seventh of Google's own recurrent system.

Where does a number like that come from? The paper's recipe is worth seeing, because the field still counts compute this way. Training time: three and a half days is 302,400 seconds. Times the number of GPUs, eight, times what one GPU sustains: the authors assumed 9.5 trillion operations a second for the P100. The product is about 2.3 times ten to the nineteen operations, the figure in their table. In chapter six we'll count the same thing a second way, from the model's size and the number of tokens it read.

Why did it win? Three reasons, and each matters more as we go. Every position is computed at once, so training uses parallel hardware fully. Any word reaches any other in a single step, so long-range dependencies are easy to learn. And the work is almost all matrix multiplication, which is exactly what graphics cards are built for, the subject of Part 17. The encoder–decoder was built for translation. By late 2019 the field had cut it three ways: keep only the encoder, as BERT did; keep only the decoder, as GPT did; or keep both, as T5 did. Which cut won, and why, is the thread of this part.

2Pretrain, then fine-tuneUndergraduate3 min

In 2017, almost every language task trained its own model, from scratch, on its own labelled data. A benchmark for sentence understanding, GLUE, collected eight such tasks; their training sets range from four hundred thousand examples down to two and a half thousand. Labels are expensive. Raw text is nearly free: billions of words of books and encyclopedias. Computer vision had already found the way to use the free kind: train one network on ImageNet, then fine-tune it for each new task. In 2018 language did the same. Pretrain on raw text with an objective that needs no labels, the guessing game of Part 1, then fine-tune a copy on each task.

January 2018: Jeremy Howard and Sebastian Ruder's ULMFiT. They pretrained a recurrent language model on Wikipedia, a hundred and three million words, then fine-tuned it on text classification, carefully, layer by layer. It cut the error of the best systems by 18 to 24 percent, and with only a hundred labelled examples it matched training from scratch on a hundred times as many. February 2018: ELMo, from the Allen Institute and the University of Washington. Two language models, one reading forward and one backward, whose internal states became word vectors that depend on the sentence. The bank of a river and the bank that sets interest rates get different vectors. Added to existing models, they improved the best results on six different tasks.

June 2018: OpenAI's GPT, by Alec Radford and colleagues. Instead of a recurrent network, the Transformer's decoder alone. Twelve layers, a width of 768, twelve heads, 117 million parameters, pretrained on BooksCorpus, over seven thousand unpublished books, to predict the next token from the 512 before it. Then one model is fine-tuned for each task, with every input written as a single sequence: for entailment, the premise, a delimiter, the hypothesis; for multiple choice, the context with each answer in turn. A new linear layer reads the last position. It set a new state of the art on nine of the twelve tasks it was tested on.

Written as objectives: pretraining maximizes the log-probability of each token given the ones before it, the chain rule of Part 1 on raw text. Fine-tuning maximizes the log-probability of the right label given the input sequence. And GPT kept the first objective on as a helper while fine-tuning, weighted by one half: it made learning faster and the result generalize better. Pretrain once, fine-tune many times: that was the recipe of 2018.

What remained open was the objective. GPT predicts from left to right, so each word's representation is built only from the words before it. For tasks like question answering, where the meaning of a word can depend on what comes after it, that looked like a handicap. Four months later, Google had an answer: BERT.

3Masked language models and the benchmark eraUndergraduate3 min

October 2018: Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova at Google. BERT keeps the Transformer's encoder alone, so every position sees the whole input, both ways. But a model that sees everything can't be trained to predict the next word: it would simply look at it. So BERT hides words instead. Pick fifteen percent of the positions at random. Replace eighty percent of those with a special mask token, ten percent with a random word, and leave ten percent unchanged. Then train the model to recover the original word at each picked position. The random and unchanged words matter: when the model is later fine-tuned there are no mask tokens, so it can't afford to think hard only where it sees one. A second task asked whether one passage really follows another.

Put the two objectives side by side. A left-to-right model like GPT makes every position a target, predicted from the words before it. The masked model's loss sums only over the picked positions, each predicted from the whole corrupted sentence. On average that is fifteen percent of the positions, so per sequence of text, the left-to-right model gets about six point seven times as many targets to learn from. BERT's authors measured the cost: their masked model learned slightly more slowly, step for step, but overtook a left-to-right model on the tasks almost immediately. We'll test that claim ourselves in chapter thirteen.

BERT came in two sizes. Base: twelve layers and 110 million parameters, the same size as GPT, chosen so the two could be compared. Large: twenty-four layers and 340 million. Both trained on books and English Wikipedia, 3.3 billion words, for a million steps. On the GLUE leaderboard BERT-Large scored 80.5, against GPT's 72.8, and it set new records in question answering too. Better still, the authors checked where the gain came from. They pretrained the same Base model a second way, left to right like GPT, everything else equal. Masking won on all five tasks, by a little on sentiment, and by about 10 points on question answering, where seeing the words after a word matters most.

BERT started a race on the benchmarks. GLUE combined nine tasks into one score; by July 2019 the best system had passed the estimate of human performance. So a harder benchmark, SuperGLUE, was built, with a human score of 89.8; BERT scored 69. Within months it too was nearly solved. RoBERTa, from Facebook, showed that BERT had simply been undertrained: drop the second task, train longer on more data, and it matched everything published after it. ELECTRA let a small network replace words and trained the main one to spot the replacements, so it learned from every position, not fifteen percent. Encoders ruled language understanding for two years, and they never went away: the embedding models behind search and retrieval are mostly encoders.

4Everything is text to textMaster's3 min

In October 2019, Colin Raffel and colleagues at Google asked a plain question. With so many objectives and architectures on offer, which actually work best? To compare them fairly, they first made every task the same shape. Text in, text out. Translation: the words 'translate English to German', then the sentence, and the model writes the German. Grammar: the model writes 'acceptable' or 'not acceptable'. Even a similarity score is written out as text: three point eight. And summaries. One model, one loss, one way of decoding, for every task. They called it T5, the Text-to-Text Transfer Transformer, and trained it on C4, a cleaned crawl of the web of about 750 gigabytes.

Their pretraining objective, the one that won their comparison, is a cousin of BERT's masking, called span corruption. Pick fifteen percent of the tokens, in spans averaging three tokens. Replace each span with one sentinel token in the input. The target is just the missing spans, each after its sentinel. The encoder reads the damaged text both ways; the decoder writes what was taken out.

Then came the comparison, with every model given the same budget of compute. Here are the architectures and objectives, each pretrained, then fine-tuned and scored on three benchmarks: GLUE, question answering, and SuperGLUE. The encoder–decoder trained by denoising came first, with 83.3 on GLUE. The decoder-only language model, trained to predict the next token, the GPT recipe, came last: 73.8, about 10 points behind. On tasks fine-tuned for understanding, seeing both ways won again.

The largest T5, eleven billion parameters, came within a point of the human score on SuperGLUE. And yet the decoder-only design is the one that took over. Why? A 2022 study by Thomas Wang and colleagues, in the BigScience collaboration, gives the clearest answer. They trained five-billion-parameter models on 170 billion tokens with each architecture and objective. Judged after fine-tuning on many tasks, the models that see both ways, with masked objectives, were best, just as T5 found. But judged with no fine-tuning at all, simply prompting the pretrained model, the causal decoder trained on the next token was best. And the field was about to stop fine-tuning a separate model for every task, and start asking one model, in words. That shift began with GPT-2.

5Unsupervised multitask learnersUndergraduate3 min

February 2019. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever, at OpenAI. Their bet: a big enough language model, trained on varied enough text, would learn tasks without being told, because the web is full of tasks being done. To get varied text of decent quality, they took every outbound link from Reddit that had earned at least three karma, about forty-five million links. After cleaning and removing duplicates: eight million documents, forty gigabytes of text. The model was GPT-1, scaled up, with layer normalization moved to the input of each block and a context of 1,024 tokens. Four sizes, the largest forty-eight layers deep and 1,600 wide: one and a half billion parameters.

The idea is that a task is just text with a pattern, and a good enough predictor will continue the pattern. To summarize an article, put 'TL;DR:' after it, the way people on the internet do, and let the model write. To translate, show a few lines of the form 'english sentence equals french sentence', then an English sentence and an equals sign. To answer questions about a passage, write the passage, the conversation so far, and 'A:'. Nothing is fine-tuned; the task lives in the prompt. On a reading comprehension test, that got 55 F1, matching three of four systems trained on more than a hundred thousand human answers.

With no task-specific training at all, the largest model set records on seven of eight language-modelling benchmarks. The cleanest picture is LAMBADA, where the last word of a passage can only be guessed from the whole passage. Accuracy climbs with size: 46, 55, 60, 63 percent, the last above the previous best of 59, set by models built for this test. On Wikipedia, character by character, it reached 0.93 bits per byte, a number from the family of our scoreboard. Its translations were still poor. But almost everything improved steadily with size, and that trend was the real result.

OpenAI did not release the largest model at first. Citing the risk of misuse, such as fake news written at scale, it published the smallest version in February, larger ones in May and August, and the full one and a half billion parameters in November 2019, with a model card describing what it was for, where it failed, and the biases of its training text. The debate it started, about when to release a model's weights, has never stopped; Part 31 returns to it. The paper's lasting lesson was simpler: one model, trained only to predict text, can be pointed at many tasks. The obvious next step was to make it much bigger.

6Scale, and learning in contextMaster's4 min

January 2020. Jared Kaplan, Sam McCandlish and colleagues at OpenAI measured how a language model's loss falls as it grows. Across more than seven orders of magnitude, the test loss followed a power law in the number of parameters, with a small exponent, about 0.076, and similar laws in the data and the compute. The message: bigger models get more out of every token, and for a fixed budget you should grow the model faster than the data. Part 12 derived these laws, and the correction that came two years later. In 2020 they were the case for building something enormous.

May 2020. Tom Brown and thirty colleagues at OpenAI: GPT-3. Eight sizes, from 125 million to 175 billion parameters, all trained on 300 billion tokens. The largest has 96 layers, a width of 12,288, 96 heads, and a context of 2,048 tokens. Where do 175 billion parameters come from? Each layer has four attention matrices, for queries, keys, values and the output, each d by d. The feed-forward network has two matrices of d by four d: eight d squared. So a layer holds twelve d squared, and the embeddings add the vocabulary and the positions times d. For GPT-3 that's 173.9 billion in the layers and 0.64 billion in the embeddings, 174.6 billion in all, exactly the figure in the paper's appendix. The training mix leaned toward quality: filtered web pages were most of it, but the smaller, cleaner sources were seen two or three times over.

Now the compute, counted a second way. Training on one token costs about six operations per parameter: two in the forward pass, a multiply and an add, and about four in the backward pass, because the gradient is needed both for the weights and for the layer below. So C is about six N D. Six, times 174.6 billion parameters, times 300 billion tokens, is 3.14 times ten to the twenty-three operations, the paper's own figure. In the paper's unit, 3,637 petaflop-days: a computer doing a thousand trillion operations a second, for about 10 years. That is about 14,000 times the compute of chapter one's Transformer.

But GPT-3 is remembered for something else, the thing its title promised: language models are few-shot learners. In-context learning: put a description of the task, and perhaps a few examples, in the prompt, and let the model continue. No gradient step is taken; not one weight changes. Here is the paper's own illustration: translate English to French; sea otter, loutre de mer; peppermint, menthe poivrée; and then cheese, and an arrow. With only the description, it's called zero-shot; with one example, one-shot; with as many as fit in the context, typically ten to a hundred, few-shot.

And it worked. On LAMBADA, GPT-3 reached 76.2 percent zero-shot and 86.4 percent few-shot, against a previous best of 68. Answering trivia questions from memory, with no documents to look in: 64.3 percent zero-shot, 68 one-shot, 71.2 few-shot. And across the eight sizes, the gap between zero-shot and few-shot widened: larger models made better use of what was in their context. Nobody had trained for this. It appeared with scale. In chapter fourteen we'll look for it in our own small models.

7Code, and following instructionsMaster's3 min

July 2021. Mark Chen and colleagues at OpenAI fine-tuned GPT models on code: 159 gigabytes of Python, from 54 million public GitHub repositories. The result, Codex, powered the first GitHub Copilot. To measure it, they wrote HumanEval: 164 programming problems, each a function signature and a description, checked by hidden unit tests. A program counts only if it passes. GPT-3 solved none of them. GPT-J, an open model of six billion parameters, 11.4 percent. Codex, with twelve billion parameters, solved 28.8 percent on its first try, and 70.2 percent when it could write a hundred programs and the tests picked any that worked. Sampling many answers and checking them comes back, as a way of thinking, in Part 28.

Meanwhile, two groups asked whether a model could learn to follow instructions in general. In September 2021, Jason Wei and colleagues at Google took a language model of 137 billion parameters and fine-tuned it on more than sixty existing datasets, each rewritten as instructions in plain English. To test it fairly, they grouped tasks by type and held out a whole type at a time: a model tested on inference had never been tuned on any inference task. Their model, FLAN, beat zero-shot GPT-3 on twenty of twenty-five datasets. A month later Victor Sanh and a large BigScience team did the same with T5. Their T0, eleven billion parameters, matched or beat GPT-3 on nine of eleven held-out datasets, while sixteen times smaller. Instruction tuning teaches the form of being asked, and the form carries over to tasks the model has never seen.

Instruction tuning used existing datasets. OpenAI's InstructGPT, published in March 2022, used people. Labellers wrote good answers to about thirteen thousand prompts, and GPT-3 was fine-tuned to imitate them. They ranked the model's answers to thirty-three thousand prompts, and a reward model learned their preferences. Then reinforcement learning pushed the model toward answers the reward model liked, on thirty-one thousand more prompts. People preferred the answers of the 1.3-billion-parameter InstructGPT to those of the 175-billion-parameter GPT-3. Every one of these stages is built, on our own model, in Part 27.

8ChatGPT and the closed eraUndergraduate3 min

On the thirtieth of November 2022, OpenAI put a model trained with InstructGPT's recipe, tuned for conversation, behind a free chat window, and called it ChatGPT. Nothing inside it was new to researchers: a GPT-3.5 model, supervised fine-tuning, a reward model, PPO. What was new was that anyone could try it. By one estimate it had a hundred million monthly users two months later, faster than any consumer app before it. It turned language models from a research topic into an industry, and it changed what the field optimized: not benchmark scores after fine-tuning, but how useful one model is when people simply talk to it.

On the fourteenth of March 2023 came GPT-4. It accepted images as well as text. On a simulated bar exam, it scored around the top ten percent of test takers, where GPT-3.5 had scored around the bottom ten. On MMLU, multiple-choice questions in fifty-seven subjects, 86.4 percent, against 70. And the report made a claim about method: OpenAI fitted scaling laws to small training runs, using at most ten thousand times less compute, and predicted GPT-4's final loss before the big run was finished. Scaling had become engineering.

And the report left something out, on purpose. In its own words: given both the competitive landscape and the safety implications of large-scale models like GPT-4, the report contains no further details about the architecture, including model size, hardware, training compute, dataset construction, training method, or similar. No size, no data, no compute. Outside estimates, from Epoch AI, put the compute at about two times ten to the twenty-five operations, and the hardware and energy of the final run at about forty million dollars. What it did publish was a system card: the model's risks, with examples, the testing by more than fifty outside experts, and the mitigations applied before release. System cards became standard for every frontier release after it.

For the next two years the frontier was closed. Anthropic released Claude the same week as GPT-4. Google's Gemini followed in December, built to take images, audio and video from the start. And in September 2024, OpenAI's o1 showed that a model trained with reinforcement learning to think at length before answering could do far better at mathematics and code: the reasoning models of Part 28. Their weights, data and sizes stayed private. If we want to read real configurations, year by year, we have to look at the models whose weights were released. That story starts in February 2023.

9Open weightsUndergraduate3 min

February 2023. Hugo Touvron and colleagues at Meta released LLaMA: four models, from seven to sixty-five billion parameters, trained only on publicly available data, one to one point four trillion tokens. The headline result: LLaMA-13B outperformed the 175-billion-parameter GPT-3 on most benchmarks, at more than thirteen times smaller. The weights went to researchers, and a whole open ecosystem was built on them within weeks: Stanford's Alpaca, Vicuna, and many more, fine-tuned on single machines.

How could a 13-billion-parameter model beat GPT-3? By reading far more text per parameter. GPT-3 saw about 1.7 tokens for each of its parameters. In 2022, DeepMind's Chinchilla paper had shown that for a fixed training budget, the best model sees about twenty tokens per parameter: GPT-3 was far too big for its data. LLaMA went past even that. Its 7-billion-parameter model saw about 149 tokens per parameter. That is more training than compute-optimal: you could have trained a better model with the same budget. But a smaller model is cheaper to run, for every token it ever serves, and once millions of people use a model, running it costs far more than training it. Part 12 derives the trade.

Then came a wave. In July 2023, Llama 2: two trillion tokens, forty percent more, twice the context, chat versions tuned with RLHF, and a license that allowed commercial use. In September, Mistral 7B, from a young company in Paris, under the Apache license. It beat Llama 2's 13-billion-parameter model, with grouped-query attention and a sliding window, both explained in the next chapter. In December, Mixtral: every layer has eight feed-forward experts, and a router picks two for each token, so the model holds forty-seven billion parameters but uses thirteen billion per token. It matched or beat Llama 2 70B and GPT-3.5. Mixtures of experts are Part 16. And in July 2024, Meta's Llama 3.1: 405 billion parameters, 15.6 trillion tokens, 3.8 times ten to the twenty-five operations, on up to sixteen thousand GPUs. Its report even counted the failures: 466 interruptions in fifty-four days. Frontier-scale training, documented in public.

And from China came open models that would soon lead. Alibaba's Qwen family began in 2023; by late 2024 Qwen2.5 was trained on eighteen trillion tokens, in sizes from tiny to large. DeepSeek's V2, in May 2024, had 236 billion parameters but used only 21 billion for each token, and a new kind of attention, multi-head latent attention, that cut the memory kept for past tokens by 93 percent. By 2025, the strongest open models came from Chinese labs: DeepSeek, Qwen, Moonshot's Kimi and Zhipu's GLM. Open weights mean open configurations. In the next chapter we read them side by side.

10The architecture convergesEngineering4 min

Open weights mean open configurations, so we can watch the designs change year by year. Here is one card, and how it changed. The 2017 Transformer. GPT-2, 2019: forty-eight layers. GPT-3, 2020: ninety-six layers, twelve thousand wide. LLaMA, 2023: smaller, but trained on 1.4 trillion tokens. Llama 3.1, 2024: 126 layers, 16,384 wide, a context of 128 thousand tokens. DeepSeek-V3: fewer layers, but 671 billion parameters, only 37 billion of them used for each token. Qwen3, 2025: 36 trillion tokens. And Kimi K3, 2026: 2.8 trillion parameters and a context of a million tokens, 2,048 times GPT-1's.

Now read the recipes side by side, across five design choices. The 2017 Transformer: layer normalization after each sub-layer, ReLU, sine-wave positions, ordinary multi-head attention, biases everywhere. GPT-2 and GPT-3 moved the normalization before each sub-layer; T5 dropped its mean and bias. PaLM, in 2022: SwiGLU, rotary positions, a single shared key and value, no biases. LLaMA put the pieces together, and from Llama 2's largest model on, nearly every open model looks the same: pre-norm RMSNorm, SwiGLU, rotary positions, grouped-query attention, no biases. Then DeepSeek-V3 changed the attention, Qwen3 added a normalization inside it, and the convergence began to loosen: the next chapter. First, why each choice won.

Normalization first. The 2017 Transformer normalized after adding each sub-layer's output to the stream. Pre-norm normalizes only the input of the branch, and adds the branch's output back untouched. Unroll that, and the stream at the top is the stream at layer l plus the sum of every layer's contribution above it. So its derivative contains the identity: the gradient reaches every layer directly, however deep the stack. Ruibin Xiong and colleagues showed in 2020 that pre-norm Transformers train without the long warm-up post-norm needs. And RMSNorm, from Biao Zhang and Rico Sennrich, drops the mean and the bias and just rescales by the root mean square: as good, and cheaper.

The feed-forward network. The original was two matrices with a ReLU between. SwiGLU, from Noam Shazeer in 2020, adds a third matrix as a gate: one branch, through the smooth Swish function, decides how much of the other branch passes, element by element. Three matrices instead of two, so to keep the parameter count, the hidden width shrinks to two thirds of four d. For LLaMA-65B, eight thirds of 8,192 is 21,845, rounded up to 22,016: exactly its published width. Why does gating help? It lowered the loss in Shazeer's experiments, and his paper's own answer is famous.

Positions and attention. Rotary embeddings won because a rotated query and key give a score that depends only on their distance, as Part 13 proved, and they stretch to longer contexts. Grouped-query attention won because of memory. To generate text, a model keeps the keys and values of every past token, in every layer: the KV cache. Per token, that's two, times the layers, times the key-value heads, times their size, times two bytes. GPT-3 kept about 4.7 megabytes per token. Llama 3.1, with all 128 heads keeping their own keys and values, would need 8.3. With grouped-query attention, the 128 query heads share just 8 key-value heads: 0.52 megabytes, sixteen times less. DeepSeek's latent attention compresses further, to about 70 kilobytes. At 128 thousand tokens of context, that's the difference between 1.1 terabytes and 68 gigabytes for a single conversation. Memory is the subject of Part 15.

11The open frontier, 2024 to 2026Engineering4 min

December 2024: DeepSeek-V3. 671 billion parameters, 37 billion used per token. A mixture of 256 small experts plus one shared, eight chosen per token; latent attention; a way to keep the experts balanced without an extra loss; training to predict two tokens at a time; and training in eight-bit floating point, at this scale, for the first time. Fourteen point eight trillion tokens. Its report stated the cost: 2.788 million GPU-hours, about 5.6 million dollars at two dollars an hour, for the final run alone, not the research before it. A month later, DeepSeek-R1, trained from V3 with reinforcement learning on problems whose answers can be checked. Its pure-RL version went from 15.6 to 77.9 percent on the AIME 2024 mathematics competition during training. Open weights, under the MIT license; Part 28 explains how.

Through 2025 the open frontier filled in. Qwen3, in April: dense and mixture-of-experts models from 0.6 to 235 billion parameters, 36 trillion tokens, 119 languages, and thinking and non-thinking modes in one model. Kimi K2, from Moonshot AI in July: a trillion parameters, 32 billion active, trained on 15.5 trillion tokens with a new optimizer, MuonClip, without a single spike in the loss. GLM-4.5, from Zhipu, the same month. And in August, OpenAI's first open language-model weights since GPT-2: gpt-oss, 117 billion parameters with 5.1 billion active, its weights in a four-bit format so that it fits on a single GPU, under the Apache license.

Put the models of this part on one chart: their total parameters against the parameters each token actually uses. Dense models sit on the diagonal: GPT-3, PaLM, LLaMA, Llama 3.1 use every parameter for every token. The open frontier moved below it. A mixture of experts routes each token through a few small networks out of hundreds, so capacity grows while the cost per token doesn't. Kimi K3 uses 104 billion of its 2.8 trillion: 3.7 percent. The frontier is sparse, and Part 16 is about how that works.

And the attention began to change. Its cost grows with the length of the context, and frontier models now read a million tokens. Hybrids replace most attention layers with layers whose memory stays a fixed size: AI21's Jamba in 2024; MiniMax-01 and NVIDIA's Nemotron-H in 2025; then Qwen3-Next and Moonshot's Kimi Linear, with three such layers for every attention layer. By 2026 the flagships were built this way, or with sparse attention. Qwen3.5, in February: a three-to-one hybrid. GLM-5, the same month: 744 billion parameters with DeepSeek's sparse attention. DeepSeek-V4, in April: 1.6 trillion parameters, compressed sparse attention, a million-token context. And Kimi K3, in July: 2.8 trillion parameters, sixty-nine layers of Kimi Delta Attention and twenty-four of latent attention. Parts 15 and 16 take these apart. The convergence of 2023 was real, but it was a pause: when contexts grew long and models grew sparse, the designs began to diverge again.

How far behind the closed frontier are the open models? One independent index, from Artificial Analysis, scores models on ten evaluations. Here is the best closed model's score over time, and the best open model's. For each new open record, ask when a closed model first scored as high. Across all of them, the median lag is months. The latest open record, , trailed by months.

12Compute, cost and dataEngineering3 min

Line up the training compute of the models in this part, on a scale where each step up is a hundred times more. The 2017 Transformer: two times ten to the nineteen operations. GPT-1, BERT, GPT-2, T5. GPT-3: three times ten to the twenty-three. PaLM. GPT-4, about two times ten to the twenty-five by Epoch AI's estimate; Llama 3.1, 3.8 times ten to the twenty-five, as Meta reported; and xAI's Grok 3, in 2025, about 3.5 times ten to the twenty-six, again an outside estimate. In 7.7 years, a factor of about 15 million.

How fast is that, as a rate? Epoch AI keeps a database of notable models. Here are the language models it marks as frontier, those near the top in compute when they appeared, since 2017. Fit a straight line to the logarithm of the compute against the date. The slope, b, comes out at 0.709 powers of ten per year. So the compute grows by a factor of ten to the b: about 5.1 times a year. It doubles every 5.1 months. Epoch's own analysis puts frontier models at four to five times a year. Our fit agrees with theirs.

Cost grew more slowly than compute, because each operation got cheaper, but it grew. Epoch AI estimates that the hardware and energy for GPT-4's final training run cost about forty million dollars, and Gemini Ultra's about thirty. Across frontier models, costs grew about 2.4 times a year since 2016; on that trend, the largest runs pass a billion dollars by 2027. Against that, DeepSeek reported about 5.6 million dollars for V3's final run: what sparse models, careful engineering and cheap 8-bit arithmetic buy. Like every such figure, it leaves out the research and the failed runs before the final one.

Finally the data: how many tokens each model read per parameter. In 2020 and 2021, GPT-3 and Gopher read fewer than two tokens per parameter. Chinchilla, in 2022, showed that about twenty is compute-optimal. Since then, open models have gone far past it: LLaMA's 7-billion-parameter model a hundred and fifty, DeepSeek-V3 four hundred per active parameter, and Qwen3's smallest model, 0.6 billion parameters, read about 36 trillion tokens: 60,000 per parameter. Small models are over-trained on purpose, because they are the ones that run most often. And good text is finite: where the tokens come from is Part 18.

13Our own lineage: GPT against BERTMaster's5 min

Now our own version of the 2018 question. Two models with exactly the same shape: layers, a width of , heads, million parameters, built from the modern block of chapter ten. They start from identical weights and read the same million tokens of the thirty novels, in the same order, with the same optimizer and learning-rate schedule. Only two things differ. The GPT-style model's attention looks back only, and it predicts every next token. The BERT-style model's attention looks both ways, and it predicts the fifteen percent of tokens we hide. By the same six-N-D estimate, their training budgets match: six, times the parameters each token passes through, times the tokens. That is what fair means here: the same model, the same data, the same estimated budget, with only the objective changed; and then a test on tasks both can do.

Watch the GPT-style model learn. On the left, its loss on held-out text as training goes on; on the right, what it writes after the words 'The door opened, and', frozen at each checkpoint, with the same random seed every time. Let it read. Each dot is the loss on text it never trains on, and the faint line is the loss on the batches it does train on. The checkpoints are spaced out geometrically: close together early, when it changes fastest. By the end, the loss is nats, and it writes something like the novels it read: not sense yet, but their words and rhythm.

The BERT-style model learns to fill blanks. Here is a sentence with three words hidden, and its best guess for each, at the same checkpoints. Its loss is measured only on the hidden words, and it falls to nats. To compare the two models fairly, we need tasks both can do.

Task one: fill in a blank. Take a sentence from a paragraph neither model has read, remove one word, and offer candidates: the real word and others about as common. The BERT-style model reads the sentence with a mask in the gap and picks the candidate it rates most likely. The GPT-style model can't see past the gap, but it can put each candidate in place and compare the probabilities of the whole sentences, which uses the words after the gap too. For contrast, we also let it judge from the words before the gap alone. On sentences, with chance at percent: from the left only, the GPT-style model gets percent. Scoring the whole sentence, .

Task two is the kind of test GLUE was made of: classify a sentence. Which of the thirty novels is it from? Freeze each model, run a sentence through it, average its final states over the sentence, and train the same simple linear classifier on top, for each model the same way. Chance is percent.

And the task only one of them can really do: write. Given the opening, the GPT-style model samples one token after another. The BERT-style model can be made to write by putting a mask at the end and filling it, again and again, but it was never trained to guess a word with nothing after it. And only the causal model gives a probability to a whole text, by the chain rule of Part 1, so only it joins the scoreboard: on the Maltese Falcon passage, 2.05 bits per character. A masked model's guesses don't multiply into the probability of a text, so it has no row. That is the deeper reason the decoder won. A model of the probability of text can be sampled, scored and prompted: one model does everything, and it gets better with scale.

14Learning in context, in our own modelsResearch3 min

GPT-3's surprise was that learning from the prompt appeared with scale. Can we see any of it at our scale? Four GPT-style models of growing size, all trained on the same text, the same number of tokens. First, the simplest measure of learning from context: the loss at each position of a 256-token window. Early positions have almost no context; later ones have a lot. From one to four tokens of context to more than a hundred, the smallest model gains nats per token;

Now replay the training of the largest of the family, and watch that curve form. On the left, its held-out loss; on the right, its loss at each position of the context, frozen at each checkpoint. Untrained, the curve is flat: a model that knows nothing gains nothing from context. By the end its held-out loss is nats, and the curve has the shape we just saw for model L.

A sharper test, the one Part 13 used: a list of sixty random common words, then the same list again. A model that can copy from its context finds the second copy much easier than the first. Here is how often each model guesses the next word, on the first copy and on the second.

Finally, GPT-3's own kind of test, built from the novels. Two books; a few labelled examples in the prompt, each a sentence and the book it is from; then a new sentence from a paragraph the models never read, and we compare the probabilities they give to the two titles. Small models tend to favour one title whatever the sentence, so, as Tony Zhao and colleagues proposed in 2021, we first subtract the score each title gets after a sentence with no content at all. We request zero, one, two, four or eight examples, then score each title within the model's 256-token context. Long prompts can retain different context for the real and N/A queries.

So what did our small models show? GPT-3's results showed stronger few-shot performance at larger scales; they do not set a universal parameter threshold. Part 13 covered attention; Part 12, the scaling laws that help explain performance trends.

Recap, problems, and what comes nextAll tracks3 min

Before the recap, here is the whole lineage on one page, with time running left to right. In 2017, the Transformer: an encoder and a decoder, built to translate. By late 2019 it had split into three branches: encoders, like BERT, which won the benchmarks; encoder-decoders, like T5; and decoders, like GPT. The decoder branch scaled: GPT-3, Codex, InstructGPT, ChatGPT, GPT-4. And as it scaled, it closed. From 2023, open lanes appear beside it: Meta's LLaMA, then Mistral, each built on the published designs before it. Then DeepSeek, Moonshot's Kimi, Alibaba's Qwen, and even OpenAI again, with open weights. Every open model at today's frontier is a decoder. The encoders live on, in search and classification, but the frontier grew from one branch.

Let's take stock. In 2017 a translation model made attention the whole architecture. In 2018, pretraining on raw text, then fine-tuning, became the recipe, and masked models like BERT won the benchmarks of the day. Then the decoder scaled: GPT-2 did tasks it was never trained for, and GPT-3, at three times ten to the twenty-three operations, learned from examples in its prompt. Instruction tuning and human feedback turned it into ChatGPT. Open models converged on one recipe, then grew sparse and began to diverge again, while compute grew about five times a year. And on our own small models, at equal estimated budgets, we measured what each objective buys.

All of this comes back. The memory of past tokens, latent attention and hybrids are Part 15. Mixtures of experts and sparse attention, Part 16. The hardware that made scale possible, Part 17, and how a frontier run is actually organized, Part 18. Serving these models cheaply, Part 19. Instruction tuning and human feedback, built on our own model, Part 27; and reasoning, Part 28.

Here are six problems to try, from counting GPT-3's parameters to the trends of the last chapter. Pause here, and work through them; full solutions are in this part's notes.

Next time: memory. A model reading a million tokens has to keep something of every one of them. Grouped-query and latent attention shrink the cache that grows with every token; linear attention, the delta rule and state-space models replace it with a memory of fixed size; and the hybrids of this part's frontier mix the two. That is Part 15.

The history in this part is best read in the papers themselves, most of them short and clear. Thanks for watching, and see you in Part 15.

Where it goes next. The memory of past tokens, latent attention and hybrids are Part 15; mixtures of experts and sparse attention Part 16; the hardware behind the scale Part 17, and how a frontier run is organized Part 18; serving Part 19; instruction tuning and human feedback are rebuilt on the series' own model in Part 27, and reasoning is Part 28.

Key results

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

Parameters from the shape\(\displaystyle N\approx 12Ld^2+(V+n_{\text{ctx}})\,d\)
Training compute\(\displaystyle C\approx 6ND\qquad\allowbreak (\text{GPT-3: }3.14\times10^{23}\text{ operations})\)
The causal objective\(\displaystyle L_{\text{LM}}=-\sum_{t}\log p(x_t\mid x_{<t})\)
The masked objective\(\displaystyle L_{\text{MLM}}=-\sum_{t\in M}\log p(x_t\mid x_{\setminus M}),\quad\allowbreak |M|\approx 0.15\,n\)
SwiGLU's width\(\displaystyle 3dh=8d^2\ \Longrightarrow\ h=\tfrac{8}{3}d\)
The KV cache\(\displaystyle 4\,L\,n_{kv}\,d_{\text{head}}\ \text{bytes }\allowbreak \text{per }\allowbreak \text{token, }\allowbreak \text{in }\allowbreak \text{16-bit }\allowbreak \text{numbers}\)

Try it

Lab 14 · Next word against fill in the blank, at equal compute

On text from a 12-symbol Markov chain, train a causal model (predict the next symbol) and a masked model (fill in 15% of the symbols from both neighbours) on the same batches with the series' autodiff. Then give both a cloze test, and compare each score with the entropy the chain's own probabilities allow.

Figure produced by Lab 14: Next word against fill in the blank, at equal compute
Produced by the lab below, seed 0, in 0.6 s.
python -m videos.ai.labs 14 needs numpy, scipy, matplotlib · download lab14.py · source on GitHub
floor with the left neighbour / with both                 2.745 / 2.062 bits
cloze: causal, left side only                             2.748 bits
cloze: causal, scoring the whole sequence                 2.060 bits
cloze: masked                                             2.072 bits
prediction targets, causal / masked                       307,200 / 46,022   (6.7 times fewer; 1/0.15 = 6.7)
fill-in loss above its floor after 40 steps / at the end  0.120 / 0.010 bits

Reading left to right, the causal model cannot use the right neighbour and stops at the one-sided floor; asked to score every candidate's whole sequence, the same model reaches the two-sided floor, where the masked model also lands, with a sixth of the targets per token read.
The code (116 lines; it asserts its own result)
"""Lab 14: a GPT-style and a BERT-style model on the same tokens, and three ways to fill in a blank."""

import numpy as np

from videos.coursekit import labs
from explainer.ai.autodiff import Tensor, cross_entropy

TITLE = "Next word against fill in the blank, at equal compute"
GOAL = ("On text from a 12-symbol Markov chain, train a causal model (predict the next symbol) and a masked model "
        "(fill in 15% of the symbols from both neighbours) on the same batches with the series' autodiff. Then give "
        "both a cloze test, and compare each score with the entropy the chain's own probabilities allow.")
TASKS = [
    "Raise the masking rate from 0.15 to 0.5. How much faster does the masked model reach its floor?",
    "Make the chain second order (the next symbol depends on the last two). Which of the three scorers falls short?",
    "Score the cloze with the causal model reading right to left only. Is it as good as left to right?",
]

V, MASK, STEPS, BATCH = 12, 0.15, 600, 512


def floors(T):
    """Bits per symbol the chain allows: knowing the left neighbour only, and knowing both neighbours."""
    w, vec = np.linalg.eig(T.T)
    pi = np.real(vec[:, np.argmax(np.real(w))])
    pi /= pi.sum()
    left = -np.sum(pi[:, None] * T * np.log2(T))
    joint = pi[:, None, None] * T[:, :, None] * T[None, :, :]  # P(a, b, c)
    both = -np.sum(joint * np.log2(joint / joint.sum(axis=1, keepdims=True)))
    return left, both


def bits(logits, target):
    z = logits - logits.max(axis=1, keepdims=True)
    lp = z - np.log(np.exp(z).sum(axis=1, keepdims=True))
    return -lp[np.arange(len(target)), target].mean() / np.log(2)


def log_softmax(z):
    z = z - z.max(axis=1, keepdims=True)
    return z - np.log(np.exp(z).sum(axis=1, keepdims=True))


def run(seed=0):
    rng = np.random.default_rng(seed)
    T = rng.dirichlet(np.full(V, 0.4), size=V) * 0.97 + 0.03 / V  # each symbol's own next-symbol probabilities
    text = np.zeros(80_000, dtype=int)
    for t, u in enumerate(rng.random(len(text) - 1)):
        text[t + 1] = min(np.searchsorted(np.cumsum(T[text[t]]), u), V - 1)
    train, test = text[:60_000], text[60_000:]
    a, b, c = test[:-2], test[1:-1], test[2:]  # left neighbour, the blank, right neighbour
    h_left, h_both = floors(T)

    W = Tensor(np.zeros((V, V)), requires_grad=True)  # causal: scores for the next symbol given this one
    A = Tensor(np.zeros((V, V)), requires_grad=True)  # masked: scores for the blank from its left neighbour ...
    B = Tensor(np.zeros((V, V)), requires_grad=True)  # ... plus scores from its right neighbour
    params = [W, A, B]
    m = [np.zeros((V, V)) for _ in params]
    v = [np.zeros((V, V)) for _ in params]
    targets = {"causal": 0, "masked": 0}
    curve = []
    for step in range(1, STEPS + 1):
        pos = rng.integers(1, len(train) - 1, BATCH)  # both models read the same BATCH tokens
        hidden = pos[rng.random(BATCH) < MASK]  # the masked model is asked about 15% of them
        for p in params:
            p.grad = np.zeros((V, V))
        cross_entropy(W[train[pos - 1]], train[pos]).backward()
        if len(hidden):
            cross_entropy(A[train[hidden - 1]] + B[train[hidden + 1]], train[hidden]).backward()
        targets["causal"] += BATCH
        targets["masked"] += len(hidden)
        lr = 0.2 * (1 - step / STEPS) + 0.005
        for i, p in enumerate(params):  # Adam
            m[i] = 0.9 * m[i] + 0.1 * p.grad
            v[i] = 0.999 * v[i] + 0.001 * p.grad ** 2
            p.data -= lr * (m[i] / (1 - 0.9 ** step)) / (np.sqrt(v[i] / (1 - 0.999 ** step)) + 1e-9)
        if step % 20 == 0 or step == 1:
            curve.append((step, bits(W.data[a], b), bits(A.data[a] + B.data[c], b)))
    curve = np.array(curve)

    lp = log_softmax(W.data)  # the causal model's log p(next | this)
    cloze = {
        "causal, left side only": bits(lp[a], b),
        "causal, scoring the whole sequence": bits(lp[a] + lp[:, c].T, b),  # log p(x | left) + log p(right | x)
        "masked": bits(A.data[a] + B.data[c], b),
    }
    lab = labs.Lab()
    lab.row("floor with the left neighbour / with both", f"{h_left:.3f} / {h_both:.3f} bits")
    for name, value in cloze.items():
        lab.row(f"cloze: {name}", f"{value:.3f} bits")
    ratio = targets["causal"] / targets["masked"]
    lab.row("prediction targets, causal / masked", f"{targets['causal']:,} / {targets['masked']:,}   ({ratio:.1f} times fewer; 1/0.15 = {1 / MASK:.1f})")
    lab.row("fill-in loss above its floor after 40 steps / at the end", f"{curve[2, 2] - h_both:.3f} / {curve[-1, 2] - h_both:.3f} bits")
    lab.note = ("Reading left to right, the causal model cannot use the right neighbour and stops at the one-sided "
                "floor; asked to score every candidate's whole sequence, the same model reaches the two-sided floor, "
                "where the masked model also lands, with a sixth of the targets per token read.")
    assert h_left - h_both > 0.25, "the right neighbour carries information"
    assert abs(cloze["causal, left side only"] - h_left) < 0.05, "left to right reaches the one-sided entropy"
    assert abs(cloze["causal, scoring the whole sequence"] - h_both) < 0.05, "whole-sequence scoring is Bayes's rule"
    assert abs(cloze["masked"] - h_both) < 0.08, "the masked model reaches the two-sided entropy"
    assert abs(ratio - 1 / MASK) < 0.8, "a masked model gets about 1/0.15 times fewer targets"

    fig, ax = labs.figure(2, size=(11, 4.2))
    names = ["causal,\nleft only", "causal,\nwhole sequence", "masked"]
    ax[0].bar(names, list(cloze.values()), color=[labs.BLUE, labs.TEAL, labs.GOLD], width=0.6)
    ax[0].axhline(h_left, color=labs.BLUE, ls="--", lw=1.2, label=f"floor, left neighbour only: {h_left:.2f}")
    ax[0].axhline(h_both, color=labs.GOLD, ls="--", lw=1.2, label=f"floor, both neighbours: {h_both:.2f}")
    ax[0].set(title="Filling in a blank on held-out text", ylabel="bits per blank", ylim=(0, h_left * 1.45))
    ax[0].legend(loc="upper right")
    ax[0].set_axisbelow(True)
    ax[1].plot(curve[:, 0], np.maximum(curve[:, 1] - h_left, 2e-3), color=labs.BLUE, label="causal: next symbol, above its floor")
    ax[1].plot(curve[:, 0], np.maximum(curve[:, 2] - h_both, 2e-3), color=labs.GOLD, label="masked: fill-in, above its floor")
    ax[1].set(title="The same tokens read, a sixth of the targets", xlabel="training step (512 tokens each)",
              ylabel="bits above the chain's floor", yscale="log")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Raise the masking rate from 0.15 to 0.5. How much faster does the masked model reach its floor?
  2. Make the chain second order (the next symbol depends on the last two). Which of the three scorers falls short?
  3. Score the cloze with the causal model reading right to left only. Is it as good as left to right?

Problems, with solutions

Try each problem before opening its solution.

1. Counting GPT-3. Show that a decoder layer with a feed-forward width of 4d has 12d² weights (ignoring norms and biases). With L = 96, d = 12,288, a vocabulary of 50,257 and 2,048 positions, check GPT-3's 174.6 billion.

Solution

Attention has four d × d matrices (queries, keys, values, output): 4d². The feed-forward network has a d × 4d and a 4d × d matrix: 8d². So a layer has 12d², and L layers 12Ld² = 12 · 96 · 12,288² = 173,946,175,488. The token and position embeddings add (50,257 + 2,048) · 12,288 = 642,723,840 (the output layer reuses the token embedding). Total: 174,588,899,328 ≈ 174.6 billion, the 174,600M of the paper's Table D.1.

2. Six operations per parameter per token. Argue that training costs about 6 operations per parameter per token, two forward and four backward. Compute GPT-3's C ≈ 6ND with D = 300 billion, in operations and in petaflop/s-days.

Solution

In the forward pass each weight w takes part in one multiply-add, y += w·x: 2 operations. In the backward pass the same weight takes part in two: the gradient for the layer below, dx += w·dy, and the gradient for the weight, dw += x·dy: 4 operations. So 6 per parameter per token (attention's own products and the nonlinearities are small for large d). C ≈ 6 · 174.6 × 10⁹ · 300 × 10⁹ = 3.14 × 10²³ operations; one petaflop/s-day is 10¹⁵ · 86,400 = 8.64 × 10¹⁹, so C ≈ 3,637 petaflop/s-days: the paper's 3.64 × 10³.

3. SwiGLU's width. A SwiGLU feed-forward network has three d × h matrices. For which h does it match a ReLU network of width 4d? Find h for d = 4096, rounded up to a multiple of 256.

Solution

3dh = 2 · d · 4d = 8d² gives h = 8d/3. For d = 4096, h = 10,922.7, rounded up to 43 · 256 = 11,008: the width of LLaMA-7B's feed-forward layers (and 22,016 for LLaMA-65B's d = 8192).

4. The KV cache. Show that the KV cache costs 4 L n_kv d_head bytes per token in 16-bit numbers. For Llama 3.1 405B (L = 126, d_head = 128), compare 8 and 128 key-value heads at 131,072 tokens.

Solution

Each layer keeps a key and a value for each key-value head, each d_head numbers of 2 bytes: 2 · 2 · n_kv · d_head bytes, times L layers. With n_kv = 8: 4 · 126 · 8 · 128 = 516,096 bytes per token, 67.6 GB for 131,072 tokens. With 128 heads, 16 times as much: 8.26 MB per token, 1.08 TB per sequence. Grouped-query attention lets 16 query heads share each key-value head, which is why the cache fits.

5. What equal compute holds fixed. A masked model predicts a fraction m of the positions. How many targets per sequence of n does it get, against a causal model? What does an equal-compute comparison hold fixed, and what not?

Solution

In expectation mn targets (0.15n for BERT) against n for a causal model: 1/m ≈ 6.7 times fewer. The same model, tokens and steps match the leading-order 6ND estimate, data and number of updates, rather than guaranteeing identical measured operation counts. They do not fix the number of prediction targets or their difficulty (a masked target sees both sides). Under the same per-token estimate, giving the masked model as many targets takes about 1/m as many training tokens and about 1/m times the compute. ELECTRA's answer was to make every position a target.

6. Growth rates. If training compute grows 4.5× a year and cost 2.4×, find the doubling time of compute in months, its growth over a decade, and the yearly gain in operations per dollar.

Solution

Doubling time: 12 · ln 2 / ln 4.5 = 5.5 months. Over a decade: 4.5¹⁰ ≈ 3.4 million times. Operations per dollar: 4.5 / 2.4 ≈ 1.9 times a year, from cheaper hardware and from using it more efficiently.

Notes and sources

Glossary

English 中文
pretraining, fine-tuning 预训练,微调
encoder-only, decoder-only, encoder–decoder 仅编码器,仅解码器,编码器-解码器
causal (left-to-right) language model 因果(从左到右)语言模型
masked language model (MLM), [MASK] token 掩码语言模型(MLM),[MASK]词元
next-sentence prediction 下一句预测
self-attention, masked self-attention, cross-attention 自注意力,带掩码的自注意力,交叉注意力
BLEU BLEU
benchmark, leaderboard 基准,排行榜
text-to-text, task prefix 文本到文本,任务前缀
span corruption, sentinel token 片段破坏,哨兵词元
zero-shot, one-shot, few-shot 零样本,单样本,少样本
in-context learning 上下文学习
scaling law 规模定律
compute-optimal, over-training 计算最优,过度训练
tokens per parameter 每个参数的词元数
petaflop/s-day petaflop/s-天
instruction tuning, held-out task 指令微调,留出的任务
staged release, model card, system card 分阶段发布,模型卡,系统卡
open weights, closed model 开放权重,闭源模型
pre-norm, post-norm, RMSNorm 前置归一化,后置归一化,RMSNorm
SwiGLU, gate SwiGLU,门控
rotary position embedding (RoPE) 旋转位置编码(RoPE)
multi-query, grouped-query attention (GQA) 多查询注意力,分组查询注意力(GQA)
multi-head latent attention (MLA) 多头潜在注意力(MLA)
KV cache KV缓存
mixture of experts, active parameters 混合专家,激活参数
sparse attention, linear attention, hybrid 稀疏注意力,线性注意力,混合架构
cloze test 完形填空测试
linear probe 线性探针
induction head, repeated-list test 归纳头,重复列表测试
equal compute 同等算力
lineage, family tree 谱系,家族树
calibration (content-free input) 校准(无内容输入)

Sources

Checked against the primary sources on 19 October 2026 (arXiv papers and technical reports, the GPT-2 repository and model card, Hugging Face model cards and API metadata):

  • Transformer: Table 2 gives EN-FR 41.8 for the big model; the text of v7 says 41.0 (the abstract says 41.8). The FLOP estimate is the paper's own method (time × GPUs × 9.5 TFLOPS for a P100, Table 2 footnote).
  • GPT-1's 117M is the GPT-2 paper's count for its smallest model "equivalent to the original GPT"; the GPT-2 repository later corrected its counts (124M, 355M, 774M, 1.5B); our 12Ld² check gives 1.557B for the largest.
  • BERT's Table 5 rows used in chapter 3 are "No NSP" (masked) against "LTR & No NSP" (left to right), so that only the objective differs.
  • Dates of 2026 releases: Qwen3.5 (Hugging Face, 16 February 2026), GLM-5 (11 February; arXiv 2602.15763), DeepSeek-V4 (model card, a preview, April 2026), Kimi K3 (announced 16 July 2026, weights later in July), MiMo-V2.6-Pro (21 September 2026). Parameters and architectures are from the model cards; DeepSeek-V4's "more than 32T" tokens is a lower bound.
  • Outside estimates (Epoch AI) are labelled as such: GPT-1, GPT-2, PaLM, GPT-4, Grok 3 in the compute tower; GPT-4's and Gemini Ultra's costs. Closed models' sizes and data are not stated anywhere on screen.
  • "100 million monthly users in two months" is a UBS estimate reported by Reuters (2 February 2023), not an OpenAI figure.
  • The family tree (Outro) is schematic: a line joins a model to its lab's previous one or to the published design it built on (LLaMA on GPT-3's pre-norm decoder; Mistral 7B, DeepSeek's and Qwen's first models on LLaMA's recipe; Kimi K2 on DeepSeek-V3's architecture, as its report says). T0 (an encoder–decoder, from T5) stands for 2021's instruction tuning in the encoder–decoder lane; FLAN itself was a decoder (LaMDA-PT).
  • Our measurements: the context gain compares the loss with 1–4 tokens of context to the loss with 129–256, on 512 held-out windows; the training replays use the 64 windows of each checkpoint, so their per-position curves are noisier. The few-shot test is scored with contextual calibration (Zhao et al. 2021): each title's log-probability minus its log-probability after the same examples and an "N/A" query; the raw scores are kept in the cache (fewshot_raw). Raw scores can reflect title bias; calibration aims to reduce it. Neither raw nor calibrated accuracy is fixed in advance.
  • Not used: claims about Kimi K3's training tokens and DeepSeek-V4's layer layout (not in the model cards); later closed-model compute estimates in Epoch's database (after mid-2026).

References: Vaswani et al. (2017); Howard & Ruder (2018); Peters et al. (2018); Radford et al. (2018, 2019); Devlin et al. (2018); Wang et al., GLUE (2018), SuperGLUE (2019); Liu et al., RoBERTa (2019); Clark et al., ELECTRA (2020); Raffel et al., T5 (2019); Lewis et al., BART (2019); Wang et al. (2022); Kaplan et al. (2020); Brown et al. (2020); Zhao et al., Calibrate Before Use (2021); Hoffmann et al. (2022); Chen et al. (2021); Wei et al. (2021); Sanh et al. (2021); Ouyang et al. (2022); OpenAI, GPT-4 Technical Report and System Card (2023); Touvron et al., LLaMA and Llama 2 (2023); Jiang et al., Mistral 7B (2023), Mixtral (2024); Llama Team (2024); Chowdhery et al., PaLM (2022); Shazeer (2019, 2020); Zhang & Sennrich (2019); Xiong et al. (2020); Su et al. (2021); Ainslie et al. (2023); DeepSeek-AI, V2 (2024), V3 (2024), R1 (2025), V3.2 (2025); Qwen Team, Qwen2.5 (2024), Qwen3 (2025); Kimi Team, K2 (2025), Kimi Linear (2025); GLM-4.5 Team (2025); OpenAI, gpt-oss (2025); Lieber et al., Jamba (2024); MiniMax (2025); NVIDIA, Nemotron-H (2025); model cards of Qwen3-Next, Qwen3.5, GLM-5, DeepSeek-V4, Kimi K3, MiMo-V2.6-Pro (2025–26); Sevilla & Roldán (Epoch AI, 2024); Cottier et al. (2024). Books: D. Jurafsky & J. H. Martin, Speech and Language Processing (3rd ed. draft); S. Raschka, Build a Large Language Model (From Scratch) (2024); S. J. D. Prince, Understanding Deep Learning (2023).

About this partfrom its README

Part 14 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 today's large language models came to be: the 2017 Transformer and the three ways it was cut; pretraining and fine-tuning (ULMFiT, ELMo, GPT-1, BERT, T5) and the benchmark era; GPT-2, scaling laws, GPT-3 and learning in context; code and instructions (Codex, FLAN, T0, InstructGPT); ChatGPT and the closed era; open weights from LLaMA to the frontier of 2026, the recipe they converged on and how it began to split again; the trends in compute, cost and data. Every published number is cited (facts.py); everything derived from it (parameter counts, 6ND, cache sizes, growth rates) is computed (compute.py). And the lineage is rebuilt in miniature on the series' thirty novels: a GPT-style and a BERT-style model trained at matched estimated matrix-compute budgets and compared on tasks both can do, and a family of GPT-style models of growing size, searched for learning in context.

  • From a translation paper to the open frontier. June 2017's Attention Is All You Need (213M parameters, 3.5 days on 8 GPUs); every model of the part by date and size, log scale; ChatGPT (30 November 2022); Kimi K3 (2.8T, 2026); our own GPT and BERT, and the family; the objectives.
  • 1. Attention is all you need. Recurrence is sequential (the seq2seq models of Part 10); self-attention connects every pair of positions in one step; the encoder–decoder (self-attention, masked self-attention, cross-attention, residuals, LayerNorm, sinusoidal positions); base and big configurations, WMT 2014 data; BLEU 27.3 / 28.4 EN-DE, 41.8 EN-FR against GNMT, ConvS2S and MoE; training cost the paper's way, time × GPUs × 9.5 TFLOP/s = 2.3 × 10¹⁹ (computed); why it won; the three cuts (encoder, decoder, both). Vaswani et al. (2017), Tables 2–3.
  • 2. Pretrain, then fine-tune. Labels are scarce (GLUE task sizes from 2.5k to 392k), text is free; ULMFiT (Howard & Ruder 2018: 18–24% less error; 100 labels ≈ 10,000 from scratch); ELMo (Peters et al. 2018); GPT-1 (Radford et al. 2018: 12 layers, 768 wide, 117M, BooksCorpus, input transformations, 9 of 12 tasks); the objectives L₁, L₂ and L₃ = L₂ + 0.5·L₁; left-to-right representations as a handicap.
  • 3. Masked language models and the benchmark era. BERT (Devlin et al. 2018): masking 15% (80/10/10), next-sentence prediction; L_LM against L_MLM and the 1/0.15 ≈ 6.7 times fewer targets; Base 110M and Large 340M, 3.3B words, GLUE 80.5 against GPT's 72.8; Table 5: the same BERT-Base pretrained masked or left to right (MNLI 83.9/82.1 … SQuAD 87.9/77.8); GLUE passed by July 2019 (88.4 against 87.1), SuperGLUE (BERT 69.0, people 89.8, T5 88.9), RoBERTa, ELECTRA; encoders today in retrieval.
  • 4. Everything is text to text. T5 (Raffel et al. 2019): task prefixes (Figure 1's examples), C4 (~750 GB), span corruption (15%, spans of ~3, sentinels; Figure 2's example), Table 2's comparison at equal cost (encoder–decoder denoising 83.28 GLUE … decoder-only LM 73.78); T5-11B 88.9 on SuperGLUE; Wang et al. (2022): causal decoders best for zero-shot use after pretraining alone, bidirectional masked models best after multitask fine-tuning.
  • 5. Unsupervised multitask learners. GPT-2 (Radford et al. 2019): WebText (45M Reddit links with ≥ 3 karma, 8M documents, 40 GB), four sizes to 1.5B; tasks as patterns ("TL;DR:", "english = french", "A:"); CoQA 55 F1 without 127k training answers; LAMBADA zero-shot 46 → 63% against a 59.23 record; enwik8 0.93 bits per byte; translation 5 and 11.5 BLEU; the staged release (Feb, May, Aug, Nov 2019) and the model card.
  • 6. Scale, and learning in context. Kaplan et al. (2020): L(N) = (N_c/N)^0.076 drawn from its fit; GPT-3 (Brown et al. 2020): 8 sizes, 96 layers × 12,288, 300B tokens, the data mix; N ≈ 12Ld² + (V + n_ctx)d = 174.6B (computed, against Table D.1's 174,600M); C ≈ 6ND = 3.14 × 10²³ = 3,637 petaflop/s-days (computed); in-context learning, zero/one/few-shot (Figure 2.1's prompt); LAMBADA 76.2/72.5/86.4 against 68.0, TriviaQA 64.3/68.0/71.2.
  • 7. Code, and following instructions. Codex and HumanEval (Chen et al. 2021: 164 problems; GPT-3 0%, GPT-J 11.4%, Codex-12B 28.8%, 70.2% from 100 samples); FLAN (Wei et al. 2021: 137B, 60+ datasets as instructions, held-out task clusters, 20 of 25 against zero-shot GPT-3); T0 (Sanh et al. 2021: 11B, 9 of 11, 16× smaller); InstructGPT's three stages (Ouyang et al. 2022; Part 27).
  • 8. ChatGPT and the closed era. 30 November 2022; 100M monthly users in two months (a UBS estimate reported by Reuters); GPT-4 (OpenAI 2023): images, bar exam top 10% against GPT-3.5's bottom 10%, MMLU 86.4% against 70.0%, predictable scaling from runs with ≤ 1/10,000 of the compute, the "no further details" passage quoted, the system card; Epoch's outside estimates (2.1 × 10²⁵ operations, $40M); Claude, Gemini, o1.
  • 9. Open weights. LLaMA (Touvron et al. 2023: 7–65B, 1.0–1.4T tokens, public data; 13B beats GPT-3); tokens per parameter (GPT-3 1.7, Chinchilla's ~20, LLaMA-7B ~149, computed) and over-training for inference; Llama 2, Mistral 7B, Mixtral (47B, 13B active), Llama 3.1 405B (3.8 × 10²⁵, 16,384 GPUs, 466 interruptions in 54 days); Qwen, DeepSeek-V2 (236B/21B, MLA, KV cache −93.3%).
  • 10. The architecture converges. One configuration card morphing from the Transformer to Kimi K3 with growth since GPT-1 (layers, width, context); the recipe matrix of 11 models (norm, activation, positions, attention, biases); pre-norm's identity path, derived (Xiong et al. 2020) and RMSNorm (Zhang & Sennrich 2019); SwiGLU (Shazeer 2020) and its width 8d/3 → LLaMA-65B's 22,016 (computed), with Shazeer's "divine benevolence"; the KV cache per token (GPT-3 4.7 MB, Llama 3.1 MHA-equivalent 8.26 MB, GQA 0.52 MB, DeepSeek-V3 MLA 70 kB; 1.08 TB → 68 GB at 128K, computed).
  • 11. The open frontier, 2024 to 2026. DeepSeek-V3 (671B/37B, MLA, aux-loss-free balancing, MTP, FP8; 2.788M H800 hours = $5.576M, computed) and R1 (AIME 2024 15.6 → 77.9%); Qwen3, Kimi K2, GLM-4.5, gpt-oss; total against active parameters, the active share (computed); hybrids (Jamba, MiniMax-01, Nemotron-H, Qwen3-Next, Kimi Linear) and the 2026 flagships (Qwen3.5, GLM-5, DeepSeek-V4, Kimi K3), each checked against its model card; open against closed on Artificial Analysis's index: the running best of each and the months between (computed from its timeline).
  • 12. Compute, cost and data. The compute tower (paper figures and Epoch estimates, marked); a least-squares fit to Epoch AI's frontier language models, 2017–mid-2026 (computed), against Epoch's 4–5× a year; the cost of frontier runs (Cottier et al. 2024: 2.4× a year, GPT-4 $40M, Gemini Ultra $30M) and DeepSeek-V3's $5.6M; tokens per parameter over time (computed from published N and D).
  • 13. Our own lineage: GPT against BERT. Two models of the same shape, initial weights, data, steps and schedule: matched approximate matrix-compute budgets, 6ND; training replays (the GPT-style model's sample and the BERT-style model's fill-ins, scrubbed with their curves); a cloze test with 8 candidates (GPT scoring whole sentences, GPT left-only, BERT); a linear probe for "which of the thirty books?"; writing; the scoreboard row.
  • 14. Learning in context, in our own models. Four GPT-style sizes on the same tokens, and the series' base model: loss at each position of the context; a training replay of how the curve forms; a repeated-list (induction) test; GPT-3 style few-shot "which book?" prompts with 0–8 examples, calibrated against a content-free "N/A" query (Zhao et al. 2021); what our scale shows and doesn't.
  • Recap. The family tree, 2017–2026: time left to right, one lane per branch or lab (encoders, encoder–decoders, OpenAI, Meta, Mistral AI, DeepSeek, Moonshot, Alibaba), open weights filled and closed models hollow, a line to the lab's previous model or the published design a model built on (schematic); eight pictures of the part; where it comes back; the problem set; Part 15's teaser; references.

Run source checks from the repository root:

What is computed and built

From published figures (published, epoch, aa):

  • The 2017 Transformer, the paper's way: big model 3.5 days × 8 GPUs × 9.5 TFLOP/s = 2.30 × 10¹⁹ operations (base: 3.28 × 10¹⁸).
  • Parameter counts from shape (12Ld² + (V + n_ctx)d): GPT-1 116.4M (published 117M), GPT-2 1.557B (1.5B), GPT-3 174.6B (Table D.1: 174,600M); LLaMA-65B 65.28B and Llama 3.1 405.8B with SwiGLU and GQA.
  • GPT-3's compute: 6 × 174.6B × 300B = 3.14 × 10²³ = 3,637 petaflop/s-days.
  • SwiGLU width: 8/3 × 8,192 = 21,845.3, rounded up to LLaMA-65B's 22,016.
  • KV cache per token (16-bit): GPT-3 4.72 MB; Llama 3.1 405B as multi-head 8.26 MB, with GQA (8 of 128) 0.52 MB; DeepSeek-V3 MLA 70.3 kB. At 128K tokens: 1.08 TB against 68 GB.
  • Tokens per parameter: GPT-3 1.7, Gopher 1.1, PaLM 1.4, Chinchilla 20, LLaMA-7B 149, LLaMA-65B 21.5, Llama 2 70B 28.6, Llama 3.1 405B 38.5, DeepSeek-V3 400 and Kimi K2 475 (per active parameter), GLM-5 713, Qwen3-0.6B 60,000.
  • DeepSeek-V3's final run: 2.788M H800 hours × $2 = $5.576M; 6ND = 3.3 × 10²⁴. Active share of parameters: DeepSeek-V3 5.5%, Qwen3-235B 9.4%, Kimi K2 3.1%, GLM-4.5 9.0%, gpt-oss-120b 4.4%, Qwen3.5-397B 4.3%, DeepSeek-V4 3.1%, Kimi K3 3.7%.
  • Compute tower: 7.7 years, a factor of about 15 million (Transformer to Grok 3).
  • Least-squares fit to Epoch AI's 40 frontier language models (2017 to mid-2026): slope 0.709 powers of ten a year, 5.1× a year (90% interval 4.6–5.7), doubling every 5.1 months; the 31 since mid-2020: 5.1×; all 271 language models with a compute estimate: 7.0× a year (the database's mix shifts toward larger models over time).
  • Artificial Analysis's index (v4.3.2, 8 October 2026): over 21 open-model records, the median time since a closed model first scored as high is 4.4 months; since 2025, 4.1 months; the latest record (MiMo-V2.6-Pro) trailed by 3.4 months.

Our model measurements are not embedded in this source-only change. They depend on separately verified scientific products and the protocol requirements above. Approximate 6ND matching does not establish identical measured execution cost or isolate the effect of the attention objective.

Compatible measured results must be reconciled before updating this section.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. "Attention Is All You Need" (2017): the translation Transformer, its configuration and BLEU (cited).
  2. Pretrain, then fine-tune: ELMo, ULMFiT, GPT-1 (2018); BERT's masked LM and the GLUE era.
  3. T5: text-to-text, and its ablations of objectives and architectures.
  4. GPT-2 (2019): zero-shot "unsupervised multitask learners"; the staged release.
  5. GPT-3 (2020): few-shot in-context learning appearing with scale; 175B; its 3.1 × 10²³ FLOPs from 6ND.
  6. Code: Codex and HumanEval.
  7. Following instructions: FLAN and T0; InstructGPT's three stages; ChatGPT (November 2022), the turning point.
  8. GPT-4 and multimodality; the closed era; system cards.
  9. Open weights: LLaMA, Mistral/Mixtral, Qwen, DeepSeek. The architecture converges: pre-norm RMSNorm, SwiGLU, RoPE, GQA, no biases (published configs animated year by year).
  10. The 2024–26 frontier: DeepSeek-V3/R1, Qwen3, Kimi K2, GLM-4.5, gpt-oss, hybrids; newer releases after verification against their reports.
  11. Compute trends (Epoch AI): training compute ×4–5 per year; cost; tokens per parameter over time.
  12. Our own lineage: GPT-style vs BERT-style pretraining on the novels at equal compute (scoreboard row); few-shot behaviour appearing as our models grow.

Visuals: configuration cards morphing year to year (layers, width, heads, context, tokens); a log-scale tower of training compute; the family tree of models.

中文讲义

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

习题与解答

1. 数一数GPT-3。 证明:前馈层宽度为4d的解码器层有12d²个权重(不计归一化和偏置)。用 L = 96、d = 12,288、词表50,257、 2,048个位置,验证GPT-3的1746亿个参数。

解答

注意力有四个 d × d 矩阵(查询、键、值、输出):4d²。前馈网络有一个 d × 4d 和一个 4d × d 矩阵:8d²。所以每层 12d²,L层共 12Ld² = 12 · 96 · 12,288² = 173,946,175,488。词元嵌入和位置嵌入再加上 (50,257 + 2,048) · 12,288 = 642,723,840(输出层复用词元嵌入)。合计 174,588,899,328,约1746亿,正是论文表D.1里的174,600M。

2. 每个参数、每个词元6次运算。 说明训练时每个参数每个词元大约要6次运算:前向2次,反向4次。用 D = 3000亿,计算GPT-3的 C ≈ 6ND,分别用运算次数和petaflop/s-天表示。

解答

前向时每个权重w参与一次乘加 y += w·x:2次运算。反向时同一个权重参与两次:给下一层的梯度 dx += w·dy,和给权重本身的 梯度 dw += x·dy:4次运算。所以每个参数每个词元6次(d很大时,注意力自身的乘积和非线性都很小)。C ≈ 6 · 1746亿 · 3000亿 = 3.14 × 10²³ 次运算;1 petaflop/s-天 = 10¹⁵ · 86,400 = 8.64 × 10¹⁹,所以 C ≈ 3,637 petaflop/s-天,与论文的 3.64 × 10³ 一致。

3. SwiGLU的宽度。 SwiGLU前馈网络有三个 d × h 矩阵。h取多少时,它和宽度为4d的ReLU网络参数一样多?求 d = 4096 时的h, 向上取到256的倍数。

解答

3dh = 2 · d · 4d = 8d²,得 h = 8d/3。d = 4096 时 h = 10,922.7,向上取整到 43 · 256 = 11,008:正是LLaMA-7B前馈层的宽度 (LLaMA-65B的 d = 8192 对应22,016)。

4. KV缓存。 证明用16位数存储时,KV缓存每个词元占 4 L n_kv d_head 字节。对Llama 3.1 405B(L = 126,d_head = 128),比较 8个和128个键值头在131,072个词元时的缓存。

解答

每一层为每个键值头存一个键和一个值,各有d_head个2字节的数:2 · 2 · n_kv · d_head 字节,再乘以L层。n_kv = 8 时: 4 · 126 · 8 · 128 = 516,096 字节/词元,131,072个词元共67.6 GB。128个头时是16倍:每个词元8.26 MB,每个序列1.08 TB。分组查询 注意力让16个查询头共用一个键值头,缓存才放得下。

5. 同等算力固定了什么。 掩码模型只预测比例为m的位置。长度为n的序列里,它得到多少个预测目标,因果模型又得到多少?同等算力 的比较固定了什么,没有固定什么?

解答

期望为mn个目标(BERT是0.15n),因果模型是n个:少了 1/m ≈ 6.7 倍。同样的模型、词元和步数匹配的是主要项6ND估算、 数据和更新次数,并不保证实际运算次数完全相同。它们没有固定预测目标的数量或难度(被遮住的目标能看到两边)。按同一个每词元 成本估算,要让掩码模型得到同样多的目标,训练词元数约需乘以1/m,算力也约需乘以1/m。ELECTRA的办法是让每个位置都成为目标。

6. 增长率。 如果训练算力每年增长4.5倍、成本每年增长2.4倍,求算力翻倍所需的月数、十年的增长倍数,以及每美元运算次数 每年提高多少。

解答

翻倍时间:12 · ln 2 / ln 4.5 = 5.5个月。十年:4.5¹⁰ ≈ 340万倍。每美元的运算次数:4.5 / 2.4 ≈ 每年1.9倍,来自更便宜的 硬件和更高的使用效率。

Build the film

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

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