Skip to content
AI from Scratch
EN

How a model is born

The complete life cycle, with the real numbers: how much text, how much compute, how much money, how many people and how much time.


The four phases

  1. DATA              months of work · 80% of the final result
       │
  2. PRE-TRAINING      weeks or months of GPU · EVERYTHING is learned here
       │               the resulting model only knows how to continue text
       │
  3. POST-TRAINING     days or weeks · this is where it becomes an assistant
       │               SFT → preferences (RLHF/DPO) → RL on tasks
       │
  4. DEPLOYMENT        quantize, serve, evaluate, monitor, iterate

What almost nobody knows: phase 1 is the one that determines quality most, and it is the least glamorous. A team with mediocre data and 10,000 GPUs loses against a team with excellent data and 1,000.


Phase 1 · DATA

Where the text comes from

SourceRaw volumeComment
Common Crawl~100 TB per dumpThe crawled web. Most of it is rubbish.
Wikipedia~20 GBHigh quality, low volume.
Books~100 GBExtremely high quality. Legally dangerous territory.
Code (GitHub)~1 TBImproves reasoning, not just programming.
Scientific papers~50 GBarXiv, PubMed.
Forums, Q&A~500 GBConversational style.
SyntheticunlimitedGenerated by other models. Increasingly important.

The cleaning pipeline

What arrives is ~100 TB. What gets used is ~5 TB. 95% is thrown away:

  1. Extraction: pull the text out of the HTML. Remove menus, ads, footers. Harder than it looks.
  2. Language filter: a fast classifier (fastText). This is where you decide how much Spanish the model is going to know.
  3. Quality filter: heuristics (is the ratio of punctuation reasonable? are there repeated lines? what is the average word length?) plus a classifier trained on "good" examples (Wikipedia) against random web.
  4. DEDUPLICATION: the most important step and the most ignored.
  5. Exact: document hashes.
  6. Approximate: MinHash + LSH over n-grams.
  7. The same text appears hundreds of times on the web. Without deduplication, the model memorizes instead of generalizing, and regurgitates training data verbatim (a real privacy and copyright problem).
  8. Decontamination: find the texts of the evaluation benchmarks inside the corpus and delete them. Otherwise your results are a lie. It is done badly almost every time.
  9. Content filter: illegal material, personal data, and so on.
  10. Mixing: decide the proportion of each source. The good stuff gets oversampled (Wikipedia 3-5 times) and the web gets undersampled.

What is in the data is what the model will be. If 92% of the corpus is in English, the model will think in English and translate. If the medical texts describe symptoms mostly in men, that is what it will learn. There is no later mechanism that fixes a bad corpus.

Tokenizing the corpus

All the text is converted to integers once and stored as one giant binary array (uint16 if the vocabulary fits in 65,536, uint32 otherwise).

15 trillion tokens × 2 bytes = 30 TB for the tokenized corpus alone.

[In the project: datos/generar_corpus.py and stage 01.]


Phase 2 · PRE-TRAINING

The objective

Just one, and it is astonishingly simple:

Predict the next token.

There are no labels. There are no annotators. The text labels itself: the correct answer for position i is token i+1. That is why you can train on trillions of tokens: labelling them costs nothing.

And there lies the deep result of the decade: to predict the next token well you have to learn grammar, facts, reasoning, translation, code and theory of mind — because all of those things appear in texts where they are necessary to get it right. Compressing well requires understanding.

The recipe, with the values actually used

optimizer        AdamW, betas (0.9, 0.95), eps 1e-8
weight decay     0.1   (matrices only; NOT bias or LayerNorm)
max lr           1e-3 (small models) … 1.5e-4 (100B+ models)
schedule         warm-up 0.5-2% of the steps, then cosine down to 10%
clipping         global norm 1.0
precision        bf16, with an fp32 master copy of the weights
batch            0.5-4 million tokens (yes, million)
context          4k-8k at first; extended at the end
duration         ~20 tokens per parameter (Chinchilla) or far more

What happens during training, in order

  1. Steps 0-100: the loss collapses from log(V)≈11 to ~7. The model learns the frequency distribution: which tokens are common.
  2. Steps 100-5,000: it learns bigrams, spelling, the basic structure. Loss ~4.
  3. The long phase (millions of steps): a slow, sustained decline. This is where everything interesting is learned. And this is where the phase transitions appear: capabilities that show up all at once, like induction heads (which enable in-context learning) or two-digit arithmetic.
  4. The end: the lr comes down and the model settles.

What really goes on in the engine room

A three-month run on 10,000 GPUs does not go smoothly. It goes like this:

  • Constant hardware failures. With 10,000 GPUs, one fails every few hours. You have to checkpoint every ~20 minutes and be able to resume.
  • Loss spikes. Every so often the loss shoots up. Sometimes it recovers on its own; sometimes you have to roll back to the last checkpoint and skip that batch of data. The technical reports for OPT-175B and BLOOM document this in detail and are very much worth reading.
  • Human monitoring 24/7. There are people on shift watching graphs.
  • Nothing can be repeated. A 50-million-euro training run does not get relaunched because you had a better idea.

Parallelism (because it does not fit on one GPU)

TypeWhat it splitsCommunication cost
Data (DP)each GPU sees a different batch, same modelall-reduce of gradients
ZeRO / FSDPweights, gradients and Adam state split uphigh, but saves a lot of memory
Tensor (TP)each matrix split across GPUsvery high: only within one node
Pipeline (PP)different layers on different GPUsmedium; creates idle "bubbles"
Sequence (SP)the sequence split across GPUsfor very long contexts

In practice all four are combined (4D parallelism) and choosing the configuration is an optimization problem in itself.

[In the project: stage 06 does all of this on one CPU with 810,000 parameters. The ideas are identical; what changes is the number of zeros.]


Phase 3 · POST-TRAINING

The base model is a text continuer. It is useless as an assistant. Turning it into one takes three steps.

3.1 · SFT (supervised instruction fine-tuning)

  • Data: between 10,000 and 1,000,000 examples (instruction → answer). Written by humans, generated by other models, or both.
  • The key: the loss is computed only over the answer, never over the question.
  • Duration: 1-3 epochs, low lr (~1e-5). More than that and it starts forgetting.
  • What it teaches: FORMAT and STYLE. It does not teach knowledge.

The superficial alignment hypothesis (LIMA, 2023): a base model already knows everything it is going to know; SFT merely teaches it to present it. With 1,000 very well chosen examples you get almost the same as with 100,000 mediocre ones.

[In the project: etapas/09_finetuning_lora/01_sft_chat.py.]

3.2 · Preferences (RLHF or DPO)

  • Data: pairs of answers compared by people. Between 10,000 and 1,000,000 comparisons. It is the most expensive part of all post-training.
  • RLHF: train a reward model and optimize with PPO. Powerful and fiendishly complicated.
  • DPO: optimize directly on the comparisons. Far simpler.
  • What it teaches: helpfulness, honesty, tone, refusing what should be refused.

[In the project: etapas/10_alineamiento_dpo/01_dpo.py.]

3.3 · RL with verifiable reward

The most recent part (and what explains the "reasoning" models): on tasks where the answer can be checked automatically — maths, code with tests — you can give reward with no human involved. The model generates many chains of reasoning, the ones that reach the right result get rewarded, and it learns to reason more and better before answering.

It is the difference between a model that answers and one that "thinks" first.


Phase 4 · DEPLOYMENT

  1. Evaluation: dozens of specific tests, blind comparisons between models, red teaming squads hunting for failures.
  2. Quantization: to int8 or int4 for serving. [Stage 08.3.]
  3. Inference server: vLLM, TensorRT-LLM, llama.cpp. Continuous batching, PagedAttention, speculative decoding. [Stages 08.2 and 11.]
  4. Safety guardrails: classifiers before and after the model.
  5. Monitoring: latency, cost, complaints, misuse.
  6. Iteration: the real failures become training data for the next version.

The bill, in real numbers

A LLaMA 3 70B class model:

ItemAmount
Raw data processed~100 TB
Training tokens15 trillion
Parameters70 billion
Training FLOPs6.3 × 10²⁴
GPU × days~180,000 (H100)
Compute cost alone€8-15 million
Total cost (with failures and experiments)€30-60 million
Duration2-4 months of continuous training
Team30-100 people
Final size in fp16140 GB
Size in int4~38 GB

[Your model: 810,000 parameters, 8.2 million tokens, 9 minutes, one CPU, 3 MB, €0. The same four phases, the same recipe, nine orders of magnitude less. And it works.]


The question that always comes up

What if I want to train one myself?

  • From scratch, a large model: no. Not unless you have €10 million.
  • From scratch, a small model (100M-1B): yes, perfectly viable. A few hundred or thousand euros of rented GPU. The code in this project is the same; what changes is the scale.
  • Fine-tuning an open model: yes, and it is what you almost always want. With LoRA, a 7B model fine-tunes on a consumer GPU. [Stage 09.2.]
  • Prompting + RAG only: yes, and it is what you want 80% of the time. Always start here. [Stage 12.]

Practical order of preference: prompting → RAG → LoRA → full fine-tuning → pre-training. Go down a rung only when you have exhausted the previous one and can measure that it is not enough.


Next: 03-matematicas-minimas.md