AI and ML FoundationsVol. 14A · Part XIV
0 / 0

Shelves / AI and ML Foundations

AI·158

The Foundation-Model Lifecycle

How a foundation model goes from raw data to a deployed product, and how engineers adapt one to a task: pre-training (data mixtures, compute budgets, scaling laws and Chinchilla-optimal training, infrastructure, failure handling), mid-training and context extension, post-training with supervised instruction tuning, preference optimisation (RLHF, DPO) and reinforcement learning with verifiable rewards for reasoning, safety training and red-teaming, evaluation (capabilities, safety, contamination), release and deployment (model cards, distillation, quantisation, serving), and then the application engineer's decision ladder: prompting, retrieval-augmented generation, tool use, fine-tuning and model routing, compared by what they change, cost, latency and when each is the right tool, with a worked routing example.

25 topics · ~16 min read · 30-question quiz
Updated Suggest a correction

Start here: from raw text to a model people use

A foundation model goes through a lifecycle: pre-training on a huge, mostly unlabelled corpus to learn language and knowledge; post-training (instruction tuning on example conversations, then preference optimisation such as RLHF or DPO) to make it follow instructions helpfully and safely; evaluation before release; and adaptation by the people who use it, from prompting and retrieval (Volume 14b) to fine-tuning on their own data. Engineers mostly work in that last stage, so its options and their costs matter most.

Scale: bigger helps, if you train it right

Four sizes, each trained for the same 400 steps (1.6 million tokens):

Text
                                   learning rate 3e-3   learning rate 1e-3
  0.24 M parameters (d=64, 2 layers)      5.058               5.588
  0.87 M parameters (d=128, 3 layers)     4.737               5.100
  2.20 M parameters (d=192, 4 layers)     5.155               4.872
  5.30 M parameters (d=256, 6 layers)     5.146               4.753

At a learning rate of 1e-3, every step up in size lowered the validation loss: the pattern behind scaling laws, where loss falls smoothly as parameters, data and compute grow together. At 3e-3 the two larger models did worse than a smaller one: bigger models needed a smaller learning rate. Scaling results only hold when each size gets suitable training settings, and when data grows too: the Chinchilla study found compute-optimal training uses roughly 20 tokens per parameter, so these models (training on 0.3–7 tokens per parameter) were all data-starved.

Adapting a trained model to a domain

The chapter 156 model was never trained on the security volume. Its loss on held-out security text, then after 150 steps of training on 62,651 security tokens:

Text
                                   trainable params   security loss   general loss
base model                                 —              4.331           4.227
full fine-tuning                       2,197,632          4.183           4.543   (forgot general text)
LoRA, rank 8                              98,304          4.281           4.353

Full fine-tuning updated every weight: it gained most on security text and lost the most on everything else (catastrophic forgetting: general loss rose by 0.32). LoRA froze the original weights and trained small rank-8 matrices added to each layer (4.5% as many parameters): it gained a third as much on security text and forgot far less. With large models, LoRA's small adapters (megabytes rather than gigabytes, one per customer or task, swappable at serving time) are often the decisive advantage.

The options, cheapest first

Option Changes Use when
prompting nothing in the model instructions and examples are enough
retrieval (RAG) the context, not the weights the model needs your current facts or documents
LoRA / adapters small added weights consistent style, format or domain behaviour
full fine-tuning all weights big shifts, with lots of data and compute
continued pre-training all weights, on a large domain corpus a new language or field

How deep to go in the foundation-model lifecycle

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Describe pre-training, post-training, evaluation and adaptation
L2 Choose between prompting, retrieval and fine-tuning for a use case
L3 Explain scaling laws, compute-optimal training, instruction tuning, RLHF/DPO and LoRA
L4 Run fine-tuning experiments with proper evaluation of gains and forgetting
L5 Plan an adaptation and evaluation programme for a product, with data, cost and risk
L6 Run pre-training and post-training of foundation models

Overview

data≈10–40T tok pre-trainnext token basemodel SFTinstructions pref + RLRLHF · DPO evalred-team deploymentserve · monitor feedback, failures, new data → next model application adaptation (most engineers work here) prompting → RAG → tool use → fine-tuning → routing across models
The foundation-model lifecycle. Pre-training on trillions of tokens produces a base model that predicts text. Post-training with instruction data, preference optimisation and reinforcement learning turns it into an assistant. Evaluation gates each stage, and deployment brings serving, monitoring and feedback that inform the next iteration. Application builders mostly work at the right-hand end, adapting a released model with prompts, retrieval, tools, fine-tuning and routing.

Pre-training

Data

The base model learns from a huge, diverse corpus (chapter 150's pipeline at scale): filtered web text, code, books, scientific papers, mathematics, multilingual data, and increasingly synthetic data (rewritten, generated or verified by earlier models). Key decisions:

  • Mixture: proportions of each source, often upsampling high-quality and reasoning-heavy data (code, maths) beyond their natural share.
  • Quality filtering and deduplication: among the largest levers on final quality.
  • Decontamination against evaluation benchmarks.
  • Curriculum / annealing: a final phase on the highest-quality data with a decaying learning rate measurably improves benchmark performance.
  • Legal and ethical constraints: licensing, opt-outs, PII, harmful content.

Frontier open models in 2025–2026 report pre-training on roughly 15–40 trillion tokens.

Compute and scaling laws

Training compute C ≈ 6·N·D FLOPs for N parameters and D tokens (chapter 154). Scaling laws (Kaplan et al., 2020; Hoffmann et al., 2022, "Chinchilla") model loss as a power law in N and D. Chinchilla's result: for a fixed compute budget, the loss-optimal model uses roughly 20 tokens per parameter; earlier models were under-trained.

In practice models are now trained far beyond that ratio (hundreds or thousands of tokens per parameter), because inference cost depends on N: a smaller model trained longer is cheaper to serve for its lifetime, and capability per parameter keeps improving with more data.

Python
def chinchilla_optimal(compute_flops, tokens_per_param=20):
    # C = 6 N D and D = 20 N  →  C = 120 N²
    n = (compute_flops / (6 * tokens_per_param)) ** 0.5
    return n, tokens_per_param * n

for c in (1e21, 1e23, 1e25):
    n, d = chinchilla_optimal(c)
    print(f"C={c:.0e}: N ≈ {n/1e9:.1f}B params, D ≈ {d/1e12:.2f}T tokens")
# 1e21 → 2.9B, 0.06T · 1e23 → 28.9B, 0.58T · 1e25 → 288.7B, 5.77T

def train_days(params, tokens, gpus, peak_flops=989e12, mfu=0.4):
    """Wall-clock days: 6ND / (gpus × peak × MFU). Default peak: H100 dense BF16."""
    return 6 * params * tokens / (gpus * peak_flops * mfu) / 86400

round(train_days(8e9, 15e12, gpus=1024), 1)     # an 8B model on 15T tokens with 1,024 H100s ≈ 21 days

Infrastructure and operations

Large runs use thousands to tens of thousands of accelerators for weeks or months, with combined data, tensor, pipeline, context and expert parallelism (chapter 152). Engineering realities:

  • Failures are routine: GPUs, links and nodes fail daily at scale; frequent asynchronous checkpointing and automatic restart are essential.
  • Loss spikes and divergence: monitored via loss, gradient norms and activation statistics; fixed by skipping data, rolling back to a checkpoint, lowering the learning rate, or architectural stabilisers (QK-norm, logit soft-capping, z-loss).
  • Throughput: MFU, data-loader stalls, communication overlap.
  • Reproducibility and provenance: exact data mixtures and code versions per checkpoint.

Mid-training

Between pre-training and post-training, many labs run mid-training stages: continued training on high-quality or domain-specific data (code, maths, long documents), context extension (RoPE scaling plus long-sequence data, chapter 154), and multilingual or multimodal adaptation.

Post-training

A base model continues text; it doesn't reliably follow instructions, hold a conversation, refuse harmful requests or use tools. Post-training shapes behaviour.

Supervised fine-tuning (SFT / instruction tuning)

Train on curated (prompt, ideal response) pairs and multi-turn conversations in the chat template (chapter 155): instructions, Q&A, coding, writing, tool-call traces, refusals. Loss only on the assistant's tokens. Thousands to millions of examples; quality and diversity matter more than quantity. Data increasingly comes from stronger models with human review and automated verification.

Preference optimisation

Many qualities (helpfulness, tone, honesty, harmlessness) are easier to judge than to demonstrate. Collect comparisons: for one prompt, two responses, and which is better (from humans or AI judges guided by principles).

  • RLHF: train a reward model to predict preferences (Bradley–Terry: P(A ≻ B) = σ(r(A) − r(B))), then optimise the policy with reinforcement learning (PPO) to maximise reward, with a KL penalty keeping it close to the SFT model (chapter 147's KL) to prevent reward hacking.
  • DPO (Direct Preference Optimization, 2023) and variants (IPO, KTO, ORPO, SimPO) optimise the policy on preference pairs directly with a classification-style loss, no separate reward model or RL loop: simpler and widely used.
  • Constitutional AI / RLAIF: AI feedback guided by a written set of principles supplements or replaces human labels.

Chapter 164 derives these losses and shows how to run them.

Reinforcement learning with verifiable rewards

Reasoning models are trained with RL on tasks whose answers can be checked automatically: maths with known answers, code with unit tests, formal proofs, puzzles, tool-use tasks with checkable outcomes. The model generates long chains of reasoning; correct final answers are rewarded; algorithms such as PPO or GRPO (group-relative: compare several samples for the same prompt) update the policy. This produces emergent behaviours (checking work, backtracking, trying alternatives) and large gains on reasoning benchmarks, with test-time compute (longer thinking) as a new scaling axis.

Safety training

Throughout post-training: refusal and safe-completion data for harmful requests, honesty and calibration training, resistance to jailbreaks and prompt injection, system-prompt adherence. Red-teaming (internal and external experts, automated attack generation) probes failures; findings feed back into data. Frontier developers publish risk frameworks with capability thresholds and corresponding safeguards.

Evaluation

Evaluation gates every stage:

Category Examples
Knowledge and reasoning MMLU-style knowledge, GPQA (graduate science), maths competitions (AIME), Humanity's Last Exam
Coding and agents SWE-bench Verified (real GitHub issues), Terminal-Bench, tool-use benchmarks (τ-bench), computer-use tasks
Long context Needle-in-a-haystack variants, multi-hop long-document QA (RULER-style)
Instruction following and chat IFEval, human and AI-judged preference arenas
Safety Refusal and over-refusal sets, jailbreak robustness, dangerous-capability evaluations (bio, cyber, autonomy)
Multilingual and multimodal Per-language suites, document/chart/video understanding

Caveats: contamination (benchmark items in training data), saturation (top scores near the ceiling), benchmark overfitting, and the gap between benchmark and real-world performance. For applications, your own evaluation set on your task is what matters (chapter 175).

Release and deployment

  • Model cards / system cards: intended uses, training data summary, evaluation results, limitations, safety testing.
  • Distillation: train smaller student models on a larger teacher's outputs or logits to get cheap, fast models.
  • Quantisation to 8/4-bit for cheaper serving (chapter 165).
  • Serving: inference engines, batching, caching, autoscaling (chapter 166, 179); APIs with rate limits, safety filters and usage policies; open weights on model hubs.
  • Monitoring and feedback: usage patterns, failure reports, abuse detection, quality regressions; data for the next model.
  • Versioning and deprecation: pinned model versions, migration windows; applications must re-evaluate when models change.

Adapting a model to your application

Application engineers rarely train foundation models. They adapt one. The roadmap asks to distinguish five tools:

Approach What it changes Good for Costs and limits
Prompting Instructions, examples, formats in the context Behaviour, format, task definition, tone; first thing to try Uses context tokens each call; brittle prompts; limited by model's knowledge
RAG (retrieval-augmented generation) What the model knows for this request: retrieved documents in context Private, changing or large knowledge; citations; freshness; access control per user Retrieval quality limits answers; extra latency and infrastructure (chapter 159–162)
Tool use What the model can do: call functions/APIs, run code, query databases, act Live data, calculations, transactions, multi-step workflows (agents) Security, error handling, latency, loops (chapter 168–172)
Fine-tuning The model's weights: style, format, specialised skills, domain language Consistent format/voice at scale, narrow tasks, smaller cheaper models matching larger ones, latency reduction Needs quality data, training and evaluation pipeline; knowledge injection is unreliable and goes stale; maintenance per base-model version (chapter 163)
Model routing Which model handles each request Cost/latency optimisation: easy requests to small models, hard ones to large; fallbacks; specialist models Router errors; evaluation per route; operational complexity
1 prompting+ eval set 2 RAGknowledge 3 toolsact · compute 4 fine-tunebehaviour · cost 5 routingmodel portfolio climb only when evals showa failure the step fixes: doesn't know → RAGmust act/compute → toolsinconsistent/costly → tunemixed difficulty → route
A decision ladder for adapting a foundation model. Start with prompting and evaluation; add retrieval when the model lacks knowledge; add tools when it must act or compute; fine-tune when behaviour must be consistent at scale or a smaller model must match a larger one; route across models to balance cost and quality. Each step adds capability and operational cost, and each is justified by measured failures, not assumed ones.

Common confusions

  • "Fine-tune it on our documents so it knows them": fine-tuning teaches behaviour and style far more reliably than facts; facts learned this way are hard to update, delete or cite, and models still hallucinate around them. Use RAG for knowledge; fine-tune for how to use it.
  • "RAG will fix formatting": no, that's prompting, structured outputs or fine-tuning.
  • "A bigger model will fix it": sometimes; often the fix is missing context or an evaluation that would have shown the real failure.
  • They combine: a production assistant typically uses all five: a well-designed prompt, retrieval over company docs, tools for live data and actions, perhaps a fine-tuned small model for a high-volume sub-task, and routing between models.

A routing sketch

Python
from dataclasses import dataclass

@dataclass
class Route:
    model: str
    max_tokens: int
    reason: str

def route(request: dict) -> Route:
    """Route by task type and estimated difficulty; every rule here should be backed by evals."""
    text, task = request["text"], request.get("task", "chat")
    if task in {"classify", "extract"} and len(text) < 4000:
        return Route("small-fast-model", 300, "structured, short: small model meets accuracy target")
    if task == "code" or "prove" in text.lower() or request.get("needs_reasoning"):
        return Route("reasoning-model", 8000, "multi-step reasoning measurably benefits")
    if len(text) > 100_000:
        return Route("long-context-model", 2000, "input exceeds standard window")
    return Route("general-model", 1500, "default")

def answer(request, call_model, validate):
    r = route(request)
    out = call_model(r.model, request, max_tokens=r.max_tokens)
    if not validate(out):                                   # cascade: escalate on failed validation
        out = call_model("general-model" if r.model == "small-fast-model" else "reasoning-model",
                         request, max_tokens=4000)
    return out

route({"text": "Extract the invoice number from: INV-2291 dated 3 Oct", "task": "extract"})

Routers can be rules (as above), a small classifier trained on logged requests labelled with which model succeeded, or a cascade that tries the cheap model first and escalates when a validator or confidence check fails. Gateways (LiteLLM, cloud AI gateways, Spring AI/LangChain4j abstractions) add fallbacks across providers, rate-limit handling and unified logging (chapter 179–180).

Lab: scaling, fine-tuning and LoRA on a tiny GPT

PyTorch 2.14.1 on the lab machine (2 CPU threads), chapter 156's gpt.py and 2,048-token tokenizer. Scope: these are toy-scale experiments (≤ 5.3 M parameters, ≤ 1.6 M tokens per run); they show the trade-offs qualitatively, and absolute numbers mean nothing for large models.

Experiment 1: a mini scaling study

Same data order, 400 steps × 4,096 tokens (1.64 M tokens), warm-up + cosine, AdamW; validation loss on the general corpus:

d / layers / heads Parameters (non-embedding) lr 3e-3 lr 1e-3 Tokens per parameter
64 / 2 / 2 239,360 (100,096) 5.058 5.588 6.8
128 / 3 / 4 873,600 (595,072) 4.737 5.100 1.9
192 / 4 / 6 2,197,632 (1,779,840) 5.155 4.872 0.7
256 / 6 / 8 5,296,128 (4,739,072) 5.146 4.753 0.3
time per run (both rates similar) 53 / 101 / 188 / 452 s

The first run used one learning rate for every size and produced a non-monotonic, misleading result; the second rate exposed why. Real scaling studies tune the learning rate (and batch size) per size, or use parameterisations designed so that one setting transfers across widths (μP). With only two rates tried here, the "best of both" column (5.058, 4.737, 4.872, 4.753) still isn't a clean curve: two points per size is too coarse a search, and every model is far from data-optimal. Kaplan et al. (2020) and Hoffmann et al. (2022, "Chinchilla") fit power laws to hundreds of such runs; the latter showed that many large models of the time were undertrained on data, and that for a fixed compute budget C ≈ 6·N·D (N parameters, D tokens), loss is minimised near D ≈ 20·N.

Experiment 2: full fine-tuning versus LoRA

Domain: Volume 10 (security), excluded from pre-training: 78,314 tokens, 80% for fine-tuning, 20% held out. 150 steps, batch 32 × 128.

Model Trainable parameters Time Security held-out loss General validation loss
base — — 4.331 4.227
full fine-tune, lr 1e-3 2,197,632 78 s 4.183 (−0.148) 4.543 (+0.316)
LoRA r = 8, α = 16, lr 3e-3 98,304 69 s 4.281 (−0.050) 4.353 (+0.126)

LoRA was applied to the attention QKV and output projections and both MLP matrices of all 4 blocks, with B initialised to zero so training starts from the base model exactly. Training time barely fell, because the frozen model still runs forward and backward through every layer; the savings with large models are in optimiser memory (no Adam state for frozen weights), checkpoint size and serving many adapters on one base model. 150 steps × 4,096 tokens is about 10 passes over the 62,651 fine-tuning tokens, so both runs were close to overfitting the small domain set; real fine-tuning monitors held-out loss and stops early. Forgetting can be reduced further by mixing some general data into the fine-tuning set ("replay").

Experiment 3: what's between pre-training and you

Stage Data What it changes
pre-training trillions of tokens of web, books, code knowledge, language, reasoning patterns
supervised fine-tuning (SFT) tens to hundreds of thousands of example dialogues following instructions, formats
preference optimisation (RLHF with a reward model, or DPO) human or AI preference comparisons helpfulness, harmlessness, style
safety and capability evaluation red-teaming, benchmarks, staged release go/no-go and mitigations
your adaptation prompts, retrieved documents, adapters your domain and task

Try it yourself

  1. Add two more learning rates (5e-4, 2e-3) to Experiment 1 and plot the best loss per size against parameters on log axes.
  2. Mix 25% general data into the security fine-tuning set and remeasure both losses for full fine-tuning.
  3. Run LoRA at ranks 2, 32 and 128. How do security gain, forgetting and trainable parameters change?
  4. Write 100 question–answer pairs from the glossaries, fine-tune with LoRA on 80, and score exact-match on the other 20 against the base model.

Revision sheet: the foundation-model lifecycle

Key ideas

  • Pre-training: data mixtures, deduplication and filtering; compute C ≈ 6·N·D FLOPs; scaling laws; compute-optimal ≈ 20 tokens per parameter (Chinchilla); many models now "over-train" smaller models for cheaper inference.
  • Post-training: SFT on demonstrations; preference optimisation (RLHF with reward models and PPO; DPO and variants); safety training; reasoning training with verifiable rewards.
  • Evaluation: benchmarks (and contamination risks), human and model-graded evals, red-teaming, task-specific evals.
  • Adaptation ladder: prompting → retrieval → adapters (LoRA, QLoRA) → full fine-tuning → continued pre-training.
  • LoRA: frozen W plus trainable low-rank BA (B starts at zero); small checkpoints; many adapters per base model; QLoRA trains adapters over a quantised base.
  • Forgetting and overfitting are the main fine-tuning risks; mix in general data, stop early, evaluate both domain and general skills.
  • Distillation and quantisation produce smaller, cheaper models for serving (Volume 15).

Numbers to remember

  • Lab: at one learning rate, bigger models were worse; at a lower rate, loss fell with size (5.588 → 4.753).
  • Lab: full fine-tuning −0.148 domain loss, +0.316 general; LoRA r=8 −0.050, +0.126 with 4.5% of parameters.
  • Training FLOPs ≈ 6 × parameters × tokens.

Pitfalls

  • Fine-tuning to add facts that change (use retrieval).
  • Comparing model sizes with one shared, untuned learning rate.
  • Evaluating only on the target domain and missing forgetting.
  • Benchmark scores inflated by training-data contamination.
  • Training on data you don't have rights to or that contains personal data.

Glossary

  • SFT: supervised fine-tuning on demonstrations.
  • RLHF / DPO: preference optimisation with a reward model and RL / directly from preference pairs.
  • LoRA / QLoRA: low-rank adapters / adapters over a 4-bit quantised base model.
  • Catastrophic forgetting: losing prior abilities during fine-tuning.
  • Data contamination: test items present in training data.