AI State of the Art
SOTA/Training: Modern Training Techniques/36 min
Section 100

Continual Pre-training: Adapting an Existing Model to a Domain

Listen as a podcast →

The Idea: Resume Rather Than Restart

A generalist model knows a great deal, shallowly. You want a model that excels at medicine, law or finance. Two routes:

  1. Pre-train from scratch on a specialized corpus. That means redoing all the work, including learning grammar and elementary logic.
  2. Continual pre-training (often abbreviated CPT): take an existing model and keep training it on data from the target domain.

The analogy is renovation versus construction. The foundations (grammar, syntax, basic reasoning) are already there. You add the specialized rooms.

Three Neighbouring Pages, Not To Be Confused

This course covers three operations that look alike and are not the same thing.

  • Continual pre-training, this page: you start from an already published model, often somebody else's, and push it onto a target domain. The learning rate has to be re-warmed, and the main risk is forgetting.
  • Mid-training: this happens inside the original training run, at the same team, before any release, using the tail of the learning-rate schedule that was already planned. There is nothing to re-warm and no finished model to damage yet.
  • Context extension: lengthening the context window. An operation that borrows the same tools as this page, but whose purpose is not to add knowledge.

Why It Is Done

Adapting to a Domain

A generalist model answers medical questions with the depth of an encyclopedia entry. Continual pre-training roots it in the domain's literature: the jargon, the writing conventions, the reasoning patterns of the trade.

Three public examples, with what the papers actually say, and nothing more.

Three Documented Cases, with the Papers' Own Numbers

Code Llama. Starts from Llama 2 and adds 500 billion tokens of code. The paper reports scores of up to 67% on HumanEval and 65% on MBPP, two collections of programming exercises graded by executing the proposed code. The most telling fact is stated there as follows: Code Llama - Python at 7 billion parameters outperforms Llama 2 at 70 billion on both benchmarks. A model ten times smaller, specialized by continual pre-training, beats the generalist it descends from, on its own domain.

BioMistral. Starts from Mistral and continues pre-training on PubMed Central. The paper evaluates the result on ten established medical question-answering tasks in English, then on seven machine translations of that benchmark. It reports better results than existing open medical models. It publishes neither a token budget nor an overall percentage gain: figures of that kind circulating about BioMistral do not come from the paper.

SaulLM-7B. Starts from the Mistral 7B architecture and trains on an English legal corpus of over 30 billion tokens. Note this if you have read otherwise elsewhere: it is 30 billion, not 200. The paper claims state-of-the-art proficiency in understanding and producing legal text, with no aggregate gain figure.

Code Llama: Open Foundation Models for Code (Rozière et al., 2023) BioMistral: A Collection of Open-Source Pretrained Large Language Models for Medical Domains (Labrak et al., 2024) SaulLM-7B: A pioneering Large Language Model for Law (Colombo et al., 2024)
The Percentage Gains You Will Read Elsewhere

On this particular topic the popular literature is littered with invented figures: "BioMistral, +25%", "SaulLM, +40%", "Code Llama, +30%". None of those three numbers appears in the corresponding paper.

The reason is instructive. A specialized model is evaluated on several benchmarks, with very different gaps from one to the next, and often a regression on some. Summarizing that as a single percentage assumes an averaging recipe nobody publishes. When you meet a "+N%" on a domain model, the right reaction is to ask: on which benchmark, against which starting model, and what happened on the others? See how to read a benchmark.

Arrow diagram of the Code Llama pipeline. On the left, Llama 2 Foundation models at 7B, 13B and 34B. An arrow leads to a purple block Code training 500B tokens. From there, two branches: the upper one passes through Long context fine-tuning 20B and yields Code Llama, then through Instruction fine-tuning 5B and yields Code Llama Instruct. The lower branch passes through Python code training 100B then Long context fine-tuning 20B and yields Code Llama Python.
Continual pre-training in real conditions. Code Llama is not trained from scratch: it starts from Llama 2 and adds 500 billion tokens of code, the large purple block. Everything after that is an order of magnitude lighter, 20 billion tokens for context lengthening, 5 billion for instruction tuning. The figure also gives the scale of the stages relative to one another, which no prose says as well.Source : Code Llama paper (Rozière et al., 2023, figure 2), via alphaXiv

Updating Knowledge

A model has a knowledge cutoff. The world moves on: new statutes, new results, new events. Continual pre-training injects recent data without redoing everything.

One caveat, and it matters. Adding recent text does not replace what the model believed before: it adds a layer on top. A model can perfectly well know the new statute and go on citing the old one, because both are in its weights. Correcting a false belief is far harder than adding a new one, and it remains an open problem.

Adding a Language

A model trained mostly in English is weak at French legal writing or Chinese medical writing. Training on text in the target language works better than machine-translating English text, because idiom and convention do not survive machine translation.

The Mechanism of Forgetting

This is the heart of the page, and the point where almost every explanation stops at the name of the phenomenon ("catastrophic forgetting") without saying what happens. It is simple, and once seen, everything else follows from it.

Why Nothing Protects the Old Knowledge

A network learns by gradient descent. At each step: you show it text, measure its error, compute in which direction to move each weight to reduce that error, and take a small step in that direction. The detail is on gradient descent.

Now look at what that procedure takes into account during continual pre-training. You measure the error on the medical text. You compute the direction that reduces the error on the medical text. You step that way.

At no point in that computation does the generalist text appear. Nothing in the objective being optimized refers to what the model knew before. The old knowledge is therefore not "protected" and then "lost": it was never in the equation. If it degrades, that is simply because no force opposes the degradation.

Why There Is No Separate Place To Store It

The second half of the mechanism, and the half that makes the phenomenon inevitable rather than accidental.

A model has no drawer for "general English" and another for "medicine." It has one set of weights, and every piece of knowledge is encoded as a pattern spread across a very large number of them. The weights for grammar and the weights for cardiology are not different weights: to a large extent they are exactly the same ones.

So modifying weights to learn cardiology necessarily modifies the weights that encoded grammar. There is no update that touches one without touching the other. That is why the phenomenon is structural, not the symptom of a bad setting.

What "Catastrophic Forgetting" Names, Exactly

Three facts, in order:

  1. Gradient descent reduces the error on the data you show it, and on nothing else. No term defends the old knowledge.
  2. Old and new knowledge are encoded in the same weights. Writing one mechanically overwrites the other.
  3. The larger the learning step, the more it overwrites. And the step has to be large enough for the new domain to actually be learned.

Together those three give the outcome: the domain score rises, the general score falls. And "catastrophic" is not journalistic hyperbole, it is the established technical term, in use since the 1980s, for a loss that can be abrupt rather than gradual.

The Learning-Rate Trade-Off You Cannot Escape

What follows is a trade-off that cannot be avoided, only positioned.

To learn a new domain efficiently, the learning rate must be re-warmed: the model arrives with a near-zero rate inherited from the end of its original training, and at that setting it will barely move. But re-warming means taking bigger steps, which means overwriting harder what was already there.

Re-Warming, Measured: What the Two Papers Establish

Gupta et al. (2023) study exactly this question on a 410-million-parameter Pythia model, moving from The Pile (300 billion tokens) to SlimPajama (297 billion). Their result, as stated: re-warming the learning rate first increases the loss, on both the old corpus and the new one, but in the longer run improves performance on the new domain, to the point of outperforming training from scratch, even for a large downstream dataset.

Ibrahim et al. (2024) go further: they show that a simple combination (re-warm the learning rate, re-decay it, and replay a share of the previous data) is enough to match the performance of fully re-training on all available data, as measured by final loss and by the average over several benchmarks. Established at 405 million parameters for a weak distribution shift (English to English) and then a strong one (English to German), and confirmed at 10 billion parameters for the weak case. They conclude that this is achieved "using only a fraction of the compute."

That is the field's central result, and it should be read as written: match, not beat. The promise of continual pre-training is not to do better than training from scratch; it is to do as well for far less.

Continual Pre-Training of Large Language Models: How to (re)warm your model? (Gupta et al., 2023) Simple and Scalable Strategies to Continually Pre-train Large Language Models (Ibrahim et al., 2024)
Four plots of validation loss against number of continual pre-training tokens, for a 405M model. The left-hand plots show loss on the original Pile corpus: all curves rise from the start of training, and rise higher the higher the maximum learning rate, with the purple curve at a constant learning rate of 3e-5 staying lowest. The right-hand plots show loss on the new SlimPajama and German corpora: there all curves descend, but the purple one descends most slowly.
The learning-rate trade-off, measured, and the most useful figure on this page. On the left, loss on the original data: it rises. That is forgetting happening, and it is stronger the higher the learning rate. On the right, loss on the new domain: it falls. That is learning. The purple curve, at a rate ten times smaller, forgets far less but also learns more slowly. The entire tuning problem is picking a point between those two curves: there is no setting that wins on both.Source : Simple and Scalable Strategies to Continually Pre-train LLMs (Ibrahim et al., 2024, figure 3), via Semantic Scholar

The Main Remedy: Replay the Old Data

Replay: The Remedy That Follows Directly From the Mechanism

If forgetting happens because the old knowledge is not in the objective being optimized, the obvious remedy is to put it back in. That is all replay does: each training batch mixes a share of general data alongside the domain data.

The gradient computation then sees both. The direction chosen at each step is the one that reduces the error on medicine without raising the error on general text too much. This is not a trick: it is the direct consequence of the diagnosis. It is also why it is by far the most effective of the five techniques on this page.

Also worth noting: replay assumes you have a sample of the original data. When you start from someone else's published model, you generally do not, the corpus is not released. In practice you replay a public corpus of similar character, which is an approximation, and nobody publishes how good an approximation it is.

The proportions quoted here and there (often "70 to 80% domain, 20 to 30% general") are customary orders of magnitude with no single source. What the literature establishes is that replay works and is part of the minimal combination that matches full retraining, not that any precise percentage is optimal.

The Other Four Techniques

Lower the learning rate. Smaller steps overwrite less. They also learn more slowly: that is the trade-off in the figure above, not a solution.

Consolidate the important weights (EWC). Elastic Weight Consolidation. The idea: not all weights matter equally to the old knowledge. For each weight you estimate how much changing it would degrade the earlier tasks, and you add to the objective a term that penalizes changes to the most sensitive ones. This is exactly putting the old knowledge back into the equation, but indirectly: instead of replaying the data, you replay an estimate of its importance. Considerably heavier than replay, and rarely used at large-language-model scale.

Overcoming catastrophic forgetting in neural networks (Kirkpatrick et al., 2016)

Freeze the early layers. Forbid any change to the input layers, on the assumption that they encode universal linguistic regularities, and tune only the deeper ones. Simple, but crude: the assumption is plausible, not demonstrated.

Add adapters instead of modifying. With LoRA and its relatives the original weights are untouched: small matrices are added alongside. Forgetting is then zero by construction, you can even remove the adapter and recover the exact starting model. The price is a lower absorption capacity: you do not install 500 billion tokens of new knowledge into an adapter. See LoRA and the comparison of efficient methods.

Forgetting Is Silent

The Monitoring Rule

Forgetting triggers no alarm. You watch the score on your domain, it climbs steadily, everything looks fine. Meanwhile the general score falls with nothing to flag it, and you may find out weeks of compute later.

So the rule is simple and non-negotiable: evaluate on both fronts at every checkpoint, domain benchmarks and general benchmarks. And checkpoint often, so you can roll back when degradation appears instead of starting over.

The manifestations to watch for, in order of frequency: a drop on general knowledge benchmarks; degraded instruction following, with the model no longer understanding simple requests; vocabulary impoverishment, everything becoming uniformly technical; and loss of the languages thinly represented in the specialization corpus, that last one is the most common and the least often measured.

What It Costs, in Orders of Magnitude

A warning is in order here. The euro or dollar figures circulating about the cost of continual pre-training are, for every one we tried to verify, unsourceable, and they contradict each other by a factor of a thousand. No lab publishes what a training run cost it. What can be computed, on the other hand, is a ratio, and that is far more useful.

The Calculation, in the Open

The compute cost of a training run is estimated by a very simple and widely used formula:

C≈6×N×DC \approx 6 \times N \times D

CC is the number of arithmetic operations needed. NN is the model's parameter count. DD is the number of tokens it is trained on. The factor of 6 breaks down as follows: roughly 2 operations per parameter per token for the forward pass (one multiply and one add) and roughly twice that for the backward pass, which computes gradients with respect to the activations and then with respect to the weights. So 2 + 4 = 6. The detail is on scaling laws.

What matters here is that NN is the same in both cases: the specialized model has exactly the size of the one it starts from. The cost ratio therefore simplifies completely:

CCPTCscratch≈DCPTDscratch\frac{C_{\text{CPT}}}{C_{\text{scratch}}} \approx \frac{D_{\text{CPT}}}{D_{\text{scratch}}}

The relative cost of continual pre-training is simply the proportion of tokens you add. Nothing else.

What That Gives

AmbitionTokens addedShare of a 15-trillion-token pre-training
Light adaptation10 to 50 billion0.07% to 0.3%
Medium adaptation50 to 200 billion0.3% to 1.3%
Deep adaptation500 billion (Code Llama scale)about 3%

The ranges in the first column are observed practice, not thresholds. The third column, by contrast, is a division you can redo: 500 / 15,000 ≈ 3.3%.

The Order of Magnitude, Stated Cautiously

An ambitious continual pre-training run costs on the order of a few percent of the original pre-training. A modest adaptation, on the order of a few tenths of a percent. As a ratio, that is somewhere between about thirty times cheaper and over a thousand times cheaper.

Three caveats. One: the calculation assumes you start from a model somebody else already paid for, that is the whole point, but it means the total cost to the system has not gone down. Two: the formula counts only arithmetic operations. It ignores the work of assembling the specialized corpus, which is often the real expense, especially when the data is licensed. Three: it ignores failed attempts. A successful continual pre-training run is often the third one.

And Ibrahim et al.'s result sets the ceiling on what to hope for: at that price you match full retraining. You do not beat it.

The Tokenizer Question

A Badly Fitted Vocabulary Costs Tokens

The tokenizer cuts text into units before any processing, see tokenization. It was built on the original corpus, so on generalist text. A specialized term it never met will be split into several pieces: "acetaminophen" may become four or five units instead of one.

The consequence is mechanical, and worth seeing clearly: for the same text, a badly tokenized corpus consumes more tokens. That inflates the training budget, reduces how much text fits in the context window, and scatters across several units what should be a single notion.

Two options. Extend the vocabulary, which means adding rows to the embedding matrix, initializing them in a way that does not wreck the model, and training them, feasible but delicate. Or accept the inefficient split and compensate with volume. The second is more common, precisely because the first is risky.

The Rest of the Pipeline

Continual pre-training does not yield a usable model: it yields a model that is knowledgeable in a domain and still merely continues text. You then need to:

  1. Instruction-tune on domain question-and-answer pairs, so it answers instead of continuing, see instruction tuning;
  2. Align on the preferences of the domain's professionals, which is what defines a good answer here, see DPO in practice;
  3. Evaluate on both fronts at every stage, because each of these stages can in turn degrade what the previous one installed, see evaluation after fine-tuning.

What To Take Away

  1. You resume an existing model rather than build one. The linguistic foundations are already paid for; you add a domain.
  2. Forgetting is not an accident, it is structural. Gradient descent reduces error only on the data shown, and contains no term defending the old knowledge. Moreover, old and new knowledge live in the same weights: writing one overwrites the other. None of this is a bad setting.
  3. Replay follows directly from that diagnosis: putting general data back into each batch puts the old knowledge back into the objective. It is the most effective remedy and by far the simplest.
  4. The learning-rate trade-off cannot be escaped. You must re-warm to learn, and re-warming causes forgetting. Ibrahim et al.'s figure shows the two curves moving in opposite directions: no setting wins on both.
  5. The field's central result is "match," not "beat": re-warming, re-decaying and replay suffice to do as well as full retraining, for a fraction of the compute.
  6. Cost is computed as a proportion of tokens, not in currency. Since compute cost is proportional to parameters times tokens, and the parameter count is unchanged, the cost ratio is simply the token ratio: a few percent for an ambitious adaptation, a few tenths of a percent for a light one. The dollar figures found on this subject are not sourceable.
  7. Monitor both fronts at every checkpoint. Forgetting is silent; without measurement on general benchmarks you do not see it coming.
Check your understanding0 / 5

1. During continual pre-training on medical text, why does the general knowledge degrade?

2. Why is replay by far the most effective remedy against forgetting?

3. According to Ibrahim et al., what can a well-tuned continual pre-training (re-warming, re-decaying and replay) hope for at best against full retraining on all the data?

4. Why can one claim that a Code Llama-style adaptation (500 billion tokens added to a model pre-trained on 15 trillion) costs about 3% of the original training?

5. You read « BioMistral: +25% gain » in a popular article. What is the right reaction?