Continued pretraining
Keep training a base model with the plain next-token objective on billions of unlabeled domain tokens so it absorbs a new domain or language; powerful but expensive, and for most enterprises RAG plus SFT wins.
Analogy: A general practitioner doing a radiology residency: same brain, now fluent in a new vocabulary, but it takes years and their general medicine may get rusty.
How it works
- SFT teaches format and behavior; CPT shifts knowledge and fluency: vocabulary, notation, style, facts.
- Start from the base model, then redo SFT and preference tuning, because CPT erodes instruction following.
- Replay general data and re-warm, then re-decay the learning rate to limit forgetting.
- Budget compute with ~6 × params × tokens FLOPs, and compare against RAG + SFT first.
- The real cost is owning a fork: each new base model means redoing CPT, SFT and evals.
Check yourself
Answer to mark it learned; your answers aren't scored.
A legal-tech company has ~5B tokens of contracts and two features: (A) clause drafting, autocompleting in house style with nothing to retrieve; (B) Q&A that must cite the current clause library. Where does continued pretraining pay?
Go deeper
Full explanation
Continued pretraining (CPT) takes an existing base model and keeps running the pretraining objective, next-token prediction on raw unlabeled text, over a large domain corpus: contracts, clinical notes, a proprietary codebase, a new language. Where Supervised fine-tuning (SFT) teaches format and behaviour from prompt/response pairs, CPT shifts knowledge and fluency: vocabulary, notation, style, facts.
How it's done:
- Start from the base model, not the chat model, then redo SFT and preference tuning on top: CPT erodes instruction following.
- Data: billions of deduplicated, quality-filtered tokens. For a new language, check tokenizer fertility (tokens per word) and extend the vocabulary if it's poor.
- Replay a slice of general data and re-warm, then re-decay the learning rate. Ibrahim et al. 2024 showed this recipe matches retraining from scratch on all the data while limiting Catastrophic forgetting.
- Budget with ~6 × params × tokens FLOPs, then compare against the cheap baseline: RAG + SFT on a general model.
Known results: Code Llama (Llama 2 + 500B code tokens) and Meditron (Llama 2 + ~48B medical tokens). BloombergGPT trained a 50B model from scratch on ~half financial data; general models like GPT-4 soon matched or beat it on several finance benchmarks.
The real cost is rarely GPU-hours. It's owning a fork: every new base model release means redoing CPT, SFT and evals.
Code Budget, replay mix and a CPT run
from datasets import load_dataset, interleave_datasets
from transformers import (AutoModelForCausalLM, AutoTokenizer, Trainer,
TrainingArguments, DataCollatorForLanguageModeling)
BASE = "meta-llama/Llama-3.1-8B" # a BASE model, not the -Instruct one
tok = AutoTokenizer.from_pretrained(BASE)
tok.pad_token = tok.eos_token
model = AutoModelForCausalLM.from_pretrained(BASE)
# Budget first: training FLOPs ~= 6 * params * tokens
params, tokens = 8e9, 10e9
print(f"{6 * params * tokens:.1e} FLOPs") # 4.8e+20 ~ 340 H100-hours at 40% MFU
domain = load_dataset("json", data_files="contracts/*.jsonl", split="train", streaming=True)
general = load_dataset("HuggingFaceFW/fineweb-edu", split="train", streaming=True)
# Replay general text so broad skills keep receiving gradient
mix = interleave_datasets(
[domain.select_columns(["text"]), general.select_columns(["text"])],
probabilities=[0.8, 0.2], seed=0)
mix = mix.map(lambda b: tok(b["text"], truncation=True, max_length=4096),
batched=True, remove_columns=["text"])
args = TrainingArguments(
output_dir="cpt", bf16=True, max_steps=20_000,
learning_rate=3e-5, warmup_steps=500, lr_scheduler_type="cosine", # re-warm, re-decay
per_device_train_batch_size=4, gradient_accumulation_steps=16,
)
Trainer(model=model, args=args, train_dataset=mix,
data_collator=DataCollatorForLanguageModeling(tok, mlm=False)).train()
# Real runs: FSDP across nodes + sequence packing. Then SFT + DPO, then eval vs RAG + SFT.Real example
A legal-tech company has ~5B tokens of contracts and court filings. CPT of an 8B base on 5B domain + 1B replay tokens is ~2.9e20 FLOPs, about 200 H100-hours: cheap. The expensive parts are three months of data cleaning and redoing SFT and DPO afterwards. Head-to-head on 400 held-out tasks, the CPT model wins clause drafting (autocomplete with nothing to retrieve), while RAG + SFT on a general model wins Q&A that must cite the current clause library. They ship CPT only for the drafting tool and budget a refresh per base-model generation.
Trade-offs +3 · −4
+ You gain
- Teaches vocabulary, notation and implicit knowledge that prompts and RAG can't inject, e.g. an internal DSL or a low-resource language.
- Knowledge lives in the weights: no retrieval latency, and it helps generation tasks with nothing to retrieve.
- Can let a small self-hosted model rival a much larger general model in one narrow domain.
− You pay
- Needs billions of clean tokens, real GPU budget and distributed-training skills.
- Erodes instruction following and safety: SFT and preference tuning must be redone on top.
- You own a fork: each new base model release means repeating CPT, SFT and evals.
- Knowledge is frozen and uncitable; facts that change still need RAG.
Use it when
You have billions of tokens of domain text whose vocabulary, notation or language the base handles poorly, a generation task with nothing to retrieve, and measured evidence that RAG + SFT falls short.
Avoid it when
Enterprise Q&A over documents, fast-changing facts, anything needing citations, or a corpus of only millions of tokens. Start with RAG and SFT; most teams never need to change the base.
Numbers to know 5
- Training compute ≈ 6 × params × tokens FLOPs: 8B params on 10B tokens ≈ 4.8e20, ~340 H100-hours at 40% MFU.
- Code Llama: Llama 2 continued on 500B code tokens (+100B Python tokens for the Python variant).
- Meditron: Llama 2 continued on ~48B tokens of medical text.
- BloombergGPT: 50B params trained from scratch on a corpus of 363B financial + 345B general tokens.
- Rule of thumb: replay ~5–25% general data, more for bigger shifts such as a new language.
Common pitfalls 4
- Running CPT on the instruct model and shipping it: chat behaviour and safety tuning wash out.
- Comparing only against the untouched base instead of against RAG + SFT on a general model.
- Ignoring the tokenizer: a language that splits into many tokens per word raises cost and slows learning.
- Treating it as one-off, with no plan or budget to redo it on the next base model.
Interview questions 3
Answer out loud first, then reveal.
The business wants a "legal GPT" trained on our 2M documents. Do you do continued pretraining?Show answer
Probably not first. I'd ask what job it does. If it answers questions about our documents, RAG gives fresh, citable answers with no training, and SFT fixes format and tone. CPT pays when the model must generate in a domain whose vocabulary the base handles poorly, there's nothing to retrieve at runtime, and we have billions of clean tokens; 2M documents might be ~2–5B tokens, so it's feasible. I'd run a time-boxed bake-off, CPT + SFT versus RAG + SFT on held-out tasks, and include the cost of redoing it every base-model release.
After continued pretraining, the model stopped following instructions. Why, and how do you fix it?Show answer
If we ran CPT on the instruct checkpoint, thousands of steps of raw next-token loss overwrote the thin SFT and preference layer: forgetting hits the last, smallest training stage first. If we ran it on the base, it never had instruction following to begin with. Either way, the fix is the pipeline the lab itself uses: CPT on the base with general-data replay and a re-warmed, re-decayed learning rate, then SFT and DPO on top, then regression evals for general skills and safety, not just domain perplexity.
How do you size the compute for a CPT run?Show answer
With the 6ND rule: training costs about 6 FLOPs per parameter per token. An 8B model on 10B tokens is 4.8e20 FLOPs. An H100 peaks near 1e15 dense BF16 FLOP/s and real runs reach ~40% MFU, so about 1.2 million GPU-seconds: ~340 H100-hours, or ~43 hours on one 8-GPU node. Then I tell stakeholders compute is the small line item; data cleaning, SFT re-runs, evals and redoing it per base release dominate.