Fix the compute at 5.9 × 1023 operations. Spend it on 280 billion parameters and the model sees only 350 billion tokens: predicted loss 1.992. Spend it on 70 billion parameters and 1.4 trillion tokens: 1.974, the bottom of the curve. DeepMind made that trade with Chinchilla against the 280-billion Gopher and won on MMLU, 67.5% to 60.0%.
Drag the model size, or tap a size. The tokens shrink as the parameters grow, because the budget is fixed. Then we build the rest from zero. Why does text need no labels? How do ELMo, BERT, GPT and T5 learn from it? What do the data, the memory and the GPUs of a run cost?
You need a little Python, what a probability is and the Transformer of Lecture 5. We build the rest from zero.
Lecture 7, "Pretraining (Scaling, Systems, Data)", of Stanford CS224N, Natural Language Processing with Deep Learning (Winter 2026, Diyi Yang and Yejin Choi). Its readings are BERT (Devlin et al., 2018), Smith's "Contextual Word Representations: A Contextual Introduction", "The Illustrated BERT, ELMo, and co.", Jurafsky and Martin Chapter 10 and "The Llama 3 Herd of Models". Before: Lecture 6, Final Projects and Practical Tips. Next: Lecture 8, Post-training.
Illustrative: predicted loss from the fitted law L = E + A/Nα + B/Dβ with the constants of Besiroglu et al. (2024), a refit of Chinchilla’s data (Chapter 6). Budget C = 6ND = 5.88 × 1023, so the tokens are D = C/(6N). MMLU scores: Hoffmann et al. (2022).
Chapter 0
Count the labels a task gets, then see what plain text gives for free
A model that starts from random weights knows nothing about language. Everything must come from the task’s labelled examples. MRPC, a task that asks whether two sentences mean the same thing, has 3,600 of them. That is far too few to learn what words mean.
Plain text has no labels, but it holds its own answers. Hide a word, and the text knows what it was. Ask for the next word, and the next word is the answer. This is self-supervision: the data supplies the targets, so every sentence becomes a training example.
Yellow rings are the words you labelled. Every other word is a test. Add labels, then switch between a model from scratch and one on a pretrained map.
Illustrative toy: 24 words placed by hand on a 2-D map that stands in for pretrained vectors. On the map, each unseen word takes the label of its nearest labelled word. From scratch, an unseen word has no trained weight, so its guess is a coin flip.
Pretraining runs self-supervision once, on a huge corpus. Fine-tuning then trains the same weights a little on the labelled task. The labels no longer have to teach what words mean. They only teach the task.
The worked number is cost. BERT-Large pretrained for 4 days on 16 Cloud TPUs: 16 × 4 × 24 = 1,536 TPU-hours. Every fine-tuning result in the BERT paper takes at most 1 hour on one Cloud TPU. One pretraining run serves many tasks.
Labels also go further. ELMo, the first model of this lecture, matched on one task with 1% of the labelled data what its baseline needed 10% for. Once text supplies the targets, the limit moves from labels to compute and data. The hero asks how to spend that compute.
Symptom: a classifier trained from scratch scores well on its training words and near chance on new ones.
Measure: accuracy on test words that never appear in the labelled set.
Fix: start from pretrained weights, so an unseen word already sits near words with labels (Chapter 1).
Chapter 1
Give “bank” a different vector in each sentence, and let each task choose which layers to read
word2vec, from Lecture 2, gives each word one vector. “Bank” gets the same numbers in “I paid cash at the bank” and in “we sat by the river bank”. The task model must sort out the sense on its own, from its few labels.
A contextual representation runs a model over the whole sentence first, so each token’s vector depends on its neighbours. ELMo (Peters et al., 2018) did this with language models on the One Billion Word Benchmark. A forward LSTM predicts each word from its left, and a backward LSTM from its right.
ELMo’s layer 0 is a character CNN that sees one word, so both banks match there. The two LSTM layers read context. The first was better for part-of-speech tags (97.3% against 96.8%), the second for word sense (69.0 against 67.4 F1).
Each arrow is “bank” in one sentence. Raise a layer’s weight to lean the mix towards it. Watch the cosine between the two banks.
Illustrative toy: 2-number vectors we made up. The sliders are raw scores; a softmax turns them into the weights s0, s1, s2, as in ELMo. The real vectors have 1,024 numbers per layer.
Call token k’s vector in layer j hk,j. The task learns one weight per layer, sj, and one overall scale, γ:
ELMo-k equals gamma times the sum over j from zero to two of s-j times h-k-j.
Run the frozen model over the sentence. Take token k’s vector h-k-j from each layer. Multiply each by its weight s-j, add the three, and scale the sum by gamma.
With the device’s made-up vectors, s = (0.2, 0.3, 0.5) and γ = 1. Bank near cash: 0.2 × (1, 0) + 0.3 × (0.8, 0.6) + 0.5 × (0.3, 0.95) = (0.59, 0.655). Near the river the second numbers change sign: (0.59, −0.655). Their cosine is −0.10, so the two senses point apart.
Adding ELMo raised SQuAD question answering from 81.1 to 85.8 F1, and it helped all six tasks the paper tested. The LSTMs stayed frozen; only s, γ and the task model trained. BERT and GPT go one step further: they fine-tune every weight.
Symptom: a model treats “bank” the same in both sentences.
Measure: the cosine between the two token vectors. At 1.00 the representation ignores context, as layer 0 does.
Fix: read the layers above the word layer, or fine-tune the whole model.
Chapter 2
Hide tokens, predict them from both sides, and stop the model leaning on the [MASK] symbol
BERT (Devlin et al., 2018) is a Transformer encoder with no causal mask: every token attends to every token. A next-word objective would let each word see itself through the layers. So BERT corrupts its input and predicts the original tokens. Lecture 1 met the idea; here is the exact recipe.
Underlined tokens are the chosen 15%. Pick a rule, corrupt once, then run 10,000 sentences. The pink row is what the BERT paper measured for that rule.
Sampling is live in your browser. Scores are BERT-Base dev results from Table 8 of Devlin et al. They give MNLI accuracy, and NER F1 when fine-tuned or from frozen features (the last 4 layers).
Why not always [MASK]? Fine-tuning text never contains it. The paper’s Table 8 tested the choice. Fine-tuned MNLI barely moved (84.2 with 80-10-10, 84.3 with [MASK] only). NER from frozen features fell from 94.9 to 94.0, because those features cannot adapt. Random-only did worst on MNLI: 83.6.
Call the chosen positions M, the corrupted sentence x̃, and the token that was at position i xi. The loss averages the surprise at the chosen positions:
L-MLM equals minus one over the size of M, times the sum over i in M of the log of P-theta of x-i given x-tilde.
At each chosen position i, read the probability the model gives the true token x-i. Take minus its log. Average those surprises over the positions in M. That is L-MLM.
With made-up numbers, three chosen positions get 0.645, 0.30 and 0.80 for their true tokens. The surprises are 0.439, 1.204 and 0.223 nats, so LMLM = 0.622. The 0.645 is “mat” in the Code Lab below.
The price is signal. BERT trained on 128,000 tokens per batch for 1,000,000 steps, 128 billion token positions. Only 15% of them, 19.2 billion, were targets. The paper reports that this objective learns slightly slower than left-to-right, yet beats it on accuracy almost from the start.
Symptom: frozen BERT features tag entities worse than fine-tuned BERT does.
Measure: compare frozen-feature and fine-tuned scores. In Table 8 the gap is largest with [MASK] only: 94.0 against 94.9.
Fix: keep 10% random and 10% unchanged, so every visible token must carry a useful vector.
Chapter 3
Pack the input with [CLS] and [SEP], read the right output vectors, and train every weight for a few epochs
BERT packs one or two sentences into one input: [CLS], sentence A, [SEP], sentence B, [SEP]. A learned segment vector marks each token as A or B. The final vector of [CLS] is called C. Every other token i has a final vector Ti, with H = 768 numbers in BERT-Base.
BERT had a second pretraining task, next sentence prediction (NSP). Half the time sentence B follows A in the text, half the time it is random, and C predicts which. Removing NSP hurt BERT’s QNLI score, 88.4 to 84.9. RoBERTa (Liu et al., 2019) later trained longer on more text and found that removing NSP matched or slightly improved results.
Pick a task. Yellow chips are BERT’s special tokens. The highlighted output vectors feed the new head; the read-out counts its weights.
Illustrative sentences and scores. Head sizes follow the BERT paper for BERT-Base (H = 768). Labels use a matrix on C, and tags use the same matrix on each Ti (9 BIO tags, as in CoNLL-2003 NER). Spans use two vectors, S and E.
For a SQuAD question, BERT adds only a start vector S and an end vector E. The chance that passage token i starts the answer is a softmax over the passage:
P-i equals e to the S dot T-i, divided by the sum over j of e to the S dot T-j.
Dot the learned start vector S with each passage token’s vector T-i. Exponentiate each score and divide by their total. The largest P-i marks the start. The end uses E the same way.
With made-up scores S·T = 0.2, 1.1, 3.0, 2.2, 0.4 and −0.3 for six passage tokens, the softmax gives P = 0.034, 0.084, 0.565, 0.254, 0.042 and 0.021. Token 3 starts the answer with 0.565.
The worked number: S and E add 2 × 768 = 1,536 weights to BERT-Base’s 110 million, about 0.0014%. Fine-tuning trains all of them for 2 to 4 epochs. With this recipe BERT-Large reached GLUE 80.5 (7.7 points over the best earlier system) and MultiNLI 86.7%, and an ensemble reached SQuAD v1.1 F1 93.2.
Symptom: BERT-Large fine-tuned on a small dataset gives a different score on every run.
Measure: repeat with new seeds and compare dev scores. The paper saw this instability on small sets.
Fix: run several random restarts from the same checkpoint and keep the best on the dev set, as the paper did.
Chapter 4
Split a sentence into next-word guesses, hide the future with a mask, and train every position in one pass
GPT (Radford et al., June 2018) kept the decoder half of the Transformer: masked self-attention and no encoder. It had 12 layers, 768-number states and 12 heads. It pretrained on BooksCorpus, over 7,000 unpublished books, chosen for their long runs of continuous text.
The objective uses the chain rule of probability. The chance of a sentence is the chance of word 1, times word 2 given word 1, times word 3 given both, and so on. This is exact, not an approximation.
Call the token at position t xt and the tokens before it x<t. The loss averages the surprise of each next token over the T predictions:
L-LM equals minus one over T, times the sum over t from one to T of the log of P-theta of x-t given x-less-than-t.
At each position t, read the probability the model gave the token that came next. Take minus its log. Average over all T positions. That is L-LM.
With made-up numbers for “the cat sat on the mat”: the model gives cat, sat, on, the and mat probabilities 0.20, 0.35, 0.55, 0.70 and 0.30. The surprises are 1.609, 1.050, 0.598, 0.357 and 1.204, so LLM = 0.964 nats over T = 5 targets.
Row t reads the blue cells and predicts the token after it. Turn the mask off and watch what each row can now read.
Illustrative probabilities, not a trained model. With the mask off, the toy row copies its target from the visible future, as a real model would learn to do.
All T predictions come from one forward pass. The causal mask stops row t from reading anything after t, and the target of row t is the input shifted left by one. Every position trains, against BERT’s 15%. Each prediction sees less context, but the model can generate: sample a token, append it, repeat.
Scale came next. GPT-2 (2019) had 1.5 billion parameters, trained on WebText, 40 GB from 8 million pages, and did tasks zero-shot. GPT-3 (2020) had 175 billion parameters and 300 billion tokens, and learned tasks from a few examples in its prompt, with no gradient updates.
Symptom: training loss falls near zero, but generated text is nonsense.
Measure: the attention weight above the diagonal. Any weight there means a row reads its own answer.
Fix: add −∞ above the diagonal before the softmax, and keep the diagonal visible (first Code Lab above).
Chapter 5
Run one sentence through BERT, GPT and T5, and compare what each position sees and what each model predicts
An objective fixes two things: which tokens a position may read, and which positions the loss scores. BERT reads both sides and scores 15%. GPT reads the left and scores every position. A third shape keeps both halves of the 2017 Transformer.
T5 (Raffel et al., 2020) casts every task as text to text. The input “translate English to German: That is good.” gives the output “Das ist gut.” A classifier writes its label as a word. One model, one loss, every task.
T5 pretrains with span corruption. It drops 15% of the tokens, in spans of mean length 3, and puts one sentinel token in place of each span. The decoder writes the dropped spans, each after its sentinel. The authors chose spans and short targets “to reduce the computational cost of pre-training”.
The grid shows which tokens each position may read: blue cells are visible. Switch models and compare the input, the reading pattern and the targets.
The sentence and its corrupted words are the example of Figure 2 in the T5 paper. Tokens are whole words here; real models use subword pieces.
The worked number uses “Thank you for inviting me to your party last week.” Corrupt “for inviting” and “last”. T5’s encoder reads “Thank you <X> me to your party <Y> week.”, 10 tokens. Its decoder writes “<X> for inviting <Y> last <Z>”, 6 tokens. BERT would compute 11 outputs and score 3.
| Shape | A position reads | Scored | Writes text? | Example |
|---|---|---|---|---|
| Encoder | every token | the 15% chosen | no | BERT, RoBERTa |
| Decoder | tokens to its left | every position | yes | GPT, Llama 3 |
| Encoder-decoder | all of the input; the output so far | the target tokens | yes | T5 |
T5 pretrained on C4, about 750 GB of cleaned Common Crawl text, and its largest model has 11 billion parameters. Most large models today keep only the decoder: one stack, one objective, and generation built in.
Symptom: a BERT model asked to write a summary produces fragments.
Measure: ask whether its objective ever produced text left to right. For an encoder, it never did.
Fix: generate with a decoder or an encoder-decoder; use an encoder’s vectors to classify, tag or search.
Chapter 6
Fit the loss as a function of parameters and tokens, then find the size that spends a budget best
Kaplan et al. (2020) trained many language models. Test loss fell as a power law in parameters, data and compute, over more than six orders of magnitude. They concluded that extra compute should go mostly into size: the best model size grows as compute to the 0.73. GPT-3 followed that advice with 1.7 tokens per parameter.
Hoffmann et al. (2022) trained over 400 models, from 70 million to over 16 billion parameters, on 5 to 500 billion tokens. Their answer differed: grow size and data equally. Call the parameter count N and the training tokens D. They fit the final loss as three terms:
L of N, D equals E, plus A over N to the alpha, plus B over D to the beta.
Start from the floor E. Add a size penalty, A divided by N to the alpha. Add a data penalty, B divided by D to the beta. A model is as good as its weaker side allows.
With the paper’s constants: Chinchilla, N = 70 billion and D = 1.4 trillion, gets 1.69 + 0.084 + 0.163 = 1.937. GPT-3, N = 175 billion and D = 300 billion, gets 1.69 + 0.061 + 0.251 = 2.002. GPT-3’s data term is three times its size term: it ran short of tokens.
Each pink curve is one budget C: every point spends it all, with D = C/(6N). Dots mark the bottoms. Pick a budget, then switch the constants.
Computed live from the two published fits of L(N, D). Real training runs scatter around these curves.
A catch. With the paper’s rounded constants, each bottom sits at 50 to 100 tokens per parameter. The paper’s two other methods say about 20, and its Chinchilla used 20. Besiroglu et al. (2024) refit the same data, got E = 1.82, A = 482, B = 2,085, α = 0.348 and β = 0.366, and the bottom moved back to about 20. The hero and this device use the refit; the Code Lab keeps the paper’s numbers.
Symptom: a bigger model trained on the same tokens barely beats a smaller one.
Measure: tokens per parameter. GPT-3 had 1.7; Gopher had 1.1 (300 billion tokens for 280 billion parameters).
Fix: at a fixed budget, shrink the model and train it on more tokens.
Chapter 7
Turn a raw web crawl into training text, and catch near-copies with MinHash
A raw web crawl is full of menus, spam and copies. The Llama 3 paper (2024) lists the steps. Extract text from the HTML. Remove duplicates by URL, by document and by line. Apply heuristic filters, then quality classifiers that are themselves models. Mix the result: about 50% general knowledge, 25% maths and reasoning, 17% code and 8% other languages.
Copies waste compute and teach the model to recite. Line-level deduplication removes any line that appears more than 6 times in a bucket of 30 million documents, such as cookie warnings. Near-copies of whole documents need another tool, because a billion documents make 5 × 1017 pairs.
MinHash compares sets without comparing pairs. Cut each document into shingles, runs of 5 words (FineWeb’s choice). Call two documents’ shingle sets A and B. Hash every shingle with a random hash function h, and keep each set’s smallest value:
P of min h of A equals min h of B, equals the size of A intersect B over the size of A union B, equals J of A, B.
The smallest hash in A union B is equally likely to belong to any of its shingles. The two minimums match exactly when that shingle is in both sets. So over many hash functions, the share of matches estimates J.
With made-up counts, two pages share 45 of 55 distinct shingles: J = 45/55 = 0.818. Of FineWeb’s 112 hash functions, about 92 match. FineWeb splits them into 14 buckets of 8 and flags a pair if any bucket matches fully: 1 − (1 − 0.8188)14 = 0.96.
Page B is a copy of page A with some words changed. Change more words and watch the shared shingles, the matching hashes and the chance of a flag.
Computed live: a 60-word page, 5-word shingles, 112 seeded hash functions in 14 buckets of 8, as in FineWeb. The pages are illustrative.
Repeats are not poison. Muennighoff et al. (2023) found that up to 4 epochs of repeated data were almost as good as new data at the same compute. After that, returns fell fast. Deduplication removes accidental copies; good sources can still repeat a few times.
Symptom: a benchmark score jumps, and the model recites test answers.
Measure: the overlap of long word runs between the training data and the test set.
Fix: deduplicate the training data against the benchmarks before training.
Chapter 8
Count the operations a run needs, the bytes each weight costs, and how many GPUs must share them
How many operations does training take? For each token, the forward pass does about one multiply and one add per parameter: 2N operations. The backward pass costs about twice that, 4N. Kaplan et al. use this rule. With N parameters and D training tokens, the total compute C is:
C is about six times N times D.
Multiply the parameters N by the tokens D, then by six. The rule leaves out attention over long contexts, which is small when the context is short next to the model width.
Llama 3 405B: N = 405 billion and D = 15.6 trillion, so C ≈ 6 × 4.05 × 1011 × 1.56 × 1013 = 3.79 × 1025 FLOPs. The paper reports 3.8 × 1025.
Time follows from throughput. Llama 3 405B trained on up to 16,384 H100 GPUs at about 400 trillion FLOPs per second each, 41% of peak (the paper’s Table 4). So 3.79 × 1025 / (16,384 × 4 × 1014) = 5.8 million seconds: about 67 days of pure compute.
Memory is the other wall. Mixed-precision training with Adam keeps 16 bytes per parameter. That is 2 for the bf16 weight and 2 for its gradient. The other 12 hold fp32 copies of the weight and of Adam’s two running averages. A 70B model needs 1.12 TB of this state, 14 times one 80 GB H100.
The bar is one GPU’s share of the training state; the grey line is 80 GB. Grow the model, then shard the state across more GPUs.
Training state only: 16 bytes per parameter, as in the ZeRO paper (Rajbhandari et al., 2020). Activations come on top and depend on batch and sequence length.
So we split the state. Data parallelism gives each GPU different examples, and sharding splits Adam’s state, the gradients and the weights across those GPUs. Tensor and pipeline parallelism split each layer and the stack of layers. Llama 3 405B used tensor 8 and pipeline 16, times data parallel groups (Table 4).
Symptom: out of memory on the first step, though the bf16 weights alone fit.
Measure: 16 bytes × N, plus activations. A 7B model needs 112 GB of state.
Fix: shard Adam’s state and the gradients across the data-parallel GPUs, or shard everything (FSDP).
Chapter 9
Choose a size, a token count and a GPU count, and read the compute, the days, the memory and the loss
Every number in this planner comes from the last three chapters. Compute is 6ND. Days are compute divided by 400 trillion FLOPs per second per GPU. Memory per GPU is 16 bytes per parameter, sharded across every GPU. The loss is the refit law, next to the best loss any size could reach with the same compute.
Start from a real model, then move the sliders. The small curve shows where your size sits at your budget.
Illustrative planner. Model sizes and token counts are the papers’ (BERT: 128,000 tokens per batch × 1,000,000 steps). GPU counts are illustrative except Llama 3 405B’s 16,384. The planner prices every run on H100s at 400 TFLOP/s, Llama 3’s Table 4 rate. The loss law was fit on Chinchilla’s data, so for other models it is a guide, not a forecast.
Three presets tell the story. GPT-3 spends 3.15 × 1023 FLOPs at 1.7 tokens per parameter; its predicted loss is 2.009, while a 53-billion model on the same budget would reach 1.992. Chinchilla sits at the bottom of its curve. Llama 3 8B sits far to the left of its bottom, on purpose.
Why train past the optimum? Each generated token costs about 2N operations, so serving cost grows with size, and a popular model serves far more tokens than it trained on. Llama 3 8B predicts 2.022 against 1.968 for the best size at its compute, an 81-billion model. But each token it writes costs 16 billion operations instead of 162 billion. The Llama 3 paper says its smaller models “perform better than compute-optimal models at the same inference budget”.
Symptom: a planned run would take years, or will not start.
Measure: days = 6ND / (GPUs × FLOPs per second per GPU), and 16N / GPUs against 80 GB.
Fix: cut N or D, add GPUs, or shard the state; then check the tokens per parameter again.
Chapter 10
Keep the objectives, the laws, the numbers and the code, and see where the course goes next
Text supplies its own targets, so a model can pretrain on a corpus nobody labelled and then fine-tune on a few thousand labels. ELMo made word vectors depend on context. BERT masked 15% and read both sides. GPT predicted every next token behind a causal mask, and T5 wrote back corrupted spans.
Then scale took over. Loss falls as a power law in parameters and tokens, and at a fixed budget the two should grow together, about 20 tokens per parameter. A run costs 6ND operations and 16 bytes of state per parameter. Clean, deduplicated data decides what those operations buy.
| Model | Shape and objective | Parameters | Training data |
|---|---|---|---|
| ELMo (2018) | biLSTM, forward and backward LM | 2 LSTM layers of 4,096 units | One Billion Word Benchmark |
| GPT (2018) | decoder, next token | 12 layers, 768 wide | BooksCorpus, 7,000+ books |
| BERT-Large (2018) | encoder, 15% masked, NSP | 340 million | 3.3 billion words |
| GPT-2 (2019) | decoder, next token | 1.5 billion | WebText, 40 GB |
| T5-11B (2020) | encoder-decoder, span corruption | 11 billion | C4, about 750 GB |
| GPT-3 (2020) | decoder, next token | 175 billion | 300 billion tokens |
| Chinchilla (2022) | decoder, next token | 70 billion | 1.4 trillion tokens |
| Llama 3 405B (2024) | decoder, next token | 405 billion | 15.6 trillion tokens |
| Number | Value | Where |
|---|---|---|
| BERT pretraining against fine-tuning | 1,536 TPU-hours against at most 1 hour | Chapter 0 |
| ELMo on SQuAD | 81.1 to 85.8 F1 | Chapter 1 |
| Frozen-feature NER: 80-10-10 against [MASK] only | 94.9 against 94.0 | Chapter 2, Table 8 |
| BERT targets over pretraining | 19.2 billion of 128 billion positions | Chapter 2 |
| SQuAD head on BERT-Base | 1,536 new weights | Chapter 3 |
| T5 example: input and target | 10 and 6 tokens | Chapter 5 |
| Paper’s law: Chinchilla against GPT-3 | 1.937 against 2.002 | Chapter 6 |
| MinHash flag at J = 0.818 | 0.96 | Chapter 7 |
| Llama 3 405B compute and days | 3.79 × 1025 FLOPs, about 67 days | Chapter 8 |
Since 2017 the decoder has changed in its parts, not its plan. Llama 3 uses pre-normalisation with RMSNorm, the SwiGLU activation, rotary positions (RoPE, base 500,000), grouped-query attention with 8 key-value heads, and a 128,000-token vocabulary.
The core as code: BERT’s 80-10-10 corruption and GPT’s shifted next-token loss, in PyTorch.
python import torch, torch.nn.functional as F def bert_corrupt(ids, mask_id, vocab_size, p=0.15): """ids: [B, T] token ids. Returns corrupted ids and labels (-100 = not scored).""" labels = ids.clone() chosen = torch.rand(ids.shape) < p # 15% of positions labels[~chosen] = -100 # loss only at chosen positions r = torch.rand(ids.shape) x = ids.clone() x[chosen & (r < 0.8)] = mask_id # 80% -> [MASK] rnd = chosen & (r >= 0.8) & (r < 0.9) # 10% -> random token x[rnd] = torch.randint(vocab_size, ids.shape)[rnd] return x, labels # last 10% stay as they are def mlm_loss(logits, labels): # logits: [B, T, V] return F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) def lm_loss(logits, ids): # causal model, logits: [B, T, V] return F.cross_entropy(logits[:, :-1].flatten(0, 1), # predictions at 0..T-2 ids[:, 1:].flatten()) # targets: the next token def train_flops(N, D): return 6 * N * D # C = 6ND def state_bytes(N): return 16 * N # bf16 w + g, fp32 w + Adam m, v
Where the course goes next. A pretrained model continues text; it does not yet follow instructions. Lecture 8 turns it into an assistant with supervised fine-tuning, human preferences and DPO.
Now teach it: press Present or Teach. Explain why BERT keeps 10% random and 10% unchanged, why GPT’s targets sit one token ahead, and why Chinchilla beat a model four times its size. Then go back to the hero, drag the size to 280 billion, and say what the model ran short of.