AnyLearn
All lessons
AIadvanced

Continual Learning in Large Language Models: Continued Pretraining, Drift, and Editing

Every stage of a language model's life trains the same weights on new data, so every stage can erase the last. Learn the continued-pretraining recipe of re-warming, re-decaying and replay, how fine-tuning erodes skills and safety, why LoRA and on-policy RL forget less, and when editing or retrieval beats training.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 10

An LLM's life is a sequence of tasks

Every stage after pretraining trains the same weights on a different distribution, usually without the earlier data mixed back in. That makes a language model a continual learner whether or not anyone designed it as one, and forgetting shows up as lost general skills, weakened safety behaviour or contradictory facts. The post-training lesson on SFT, RLHF and DPO covers what each stage optimises; this lesson is about what each stage can erase.

Sign in free to save your progress and earn certificates.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. An LLM's life is a sequence of tasks

Every stage after pretraining trains the same weights on a different distribution, usually without the earlier data mixed back in. That makes a language model a continual learner whether or not anyone designed it as one, and forgetting shows up as lost general skills, weakened safety behaviour or contradictory facts. The post-training lesson on SFT, RLHF and DPO covers what each stage optimises; this lesson is about what each stage can erase.

flowchart LR
  P["Pretraining on a broad corpus"] --> C["Continued pretraining: new domain, language or period"]
  C --> S["Supervised instruction tuning"]
  S --> R["Preference or RL tuning"]
  R --> D["Deployment updates: fine-tunes, adapters, edits"]
  D --> E["Evaluate for lost capabilities at every arrow"]

2. Continued pretraining: re-warm, re-decay, replay

Pretraining from scratch every time new data arrives is the expensive baseline. Ibrahim et al. (Transactions on Machine Learning Research, 2024) asked what it takes for continued pretraining to match it. Working at 405 million parameters with hundreds of billions of tokens, and checking at 10 billion parameters, they studied a weak shift (between two English web corpora, the Pile then SlimPajama) and a strong one (English then German).

IngredientWhat it doesTheir finding
Re-warm the learning rateRaise it again from the low value pretraining ended onNeeded to adapt to new data, but increases forgetting, even when training continues on the same data
Re-decay itAnneal back down by the end of the new phaseNeeded for the final loss to settle
Replay old dataKeep a share of each batch from the original corpus5% sufficed for the weak shift, 25% was used for German

With all three, continually pretrained models matched the average performance of re-training on the combined data, using only a fraction of the compute. The authors also note later adopters: DeepSeek-Coder-V2 used 30% replay across 6 trillion tokens of continued pretraining.

Key idea: At LLM scale the oldest fix, replay, still does most of the work. The learning-rate schedule decides how far the weights are allowed to travel.

3. The recipe in code

A continued-pretraining loop needs two small pieces of logic: a schedule that re-warms and re-decays, and a batch sampler that mixes in old data at a fixed rate. Both are framework-independent.

import math, random

def lr_at(step, total, peak=3e-4, floor=3e-5, warmup_frac=0.01):
    """Re-warm linearly, then re-decay with a cosine back to the floor."""
    warm = int(total * warmup_frac)
    if step < warm:
        return peak * (step + 1) / warm
    t = (step - warm) / max(1, total - warm)
    return floor + 0.5 * (peak - floor) * (1 + math.cos(math.pi * t))

def batch_sources(batch_size, replay_frac, rng):
    """Each sequence comes from the old corpus with probability replay_frac."""
    return ["old" if rng.random() < replay_frac else "new" for _ in range(batch_size)]

rng = random.Random(0)
total = 10_000
for step in [0, 50, 99, 100, 2_500, 5_000, 9_999]:
    print(f"step {step:>5}: lr {lr_at(step, total):.2e}")

counts = {"old": 0, "new": 0}
for _ in range(1_000):                       # 1,000 batches of 32 sequences
    for s in batch_sources(32, replay_frac=0.05, rng=rng):
        counts[s] += 1
print(counts, f"replay share {counts['old'] / sum(counts.values()):.3f}")

Output:

step     0: lr 3.00e-06
step    50: lr 1.53e-04
step    99: lr 3.00e-04
step   100: lr 3.00e-04
step  2500: lr 2.63e-04
step  5000: lr 1.67e-04
step  9999: lr 3.00e-05
{'old': 1640, 'new': 30360} replay share 0.051

The learning rate climbs to its peak over the first 1% of steps, then follows a cosine back to the floor. Sampling per sequence lands at 5.1% replay against a 5% target. Ibrahim et al. compare runs at equal total tokens, so replayed tokens replace new ones rather than being added.

Try it: Set warmup_frac to 0 and the peak to the floor value. That is the no-re-warming baseline: forgetting falls, and so does adaptation to the new corpus.

4. Fine-tuning drift: capabilities and safety

Fine-tuning is short and narrow compared with pretraining, which makes it look harmless. Two findings say otherwise.

General knowledge erodes. Luo et al. (2023) continually instruction-tuned models from 1 to 7 billion parameters and measured domain knowledge, reasoning and reading comprehension. Forgetting appeared throughout that range and, within it, grew more severe with model size, which the authors attribute to the larger models starting from a higher baseline. Prior general instruction tuning reduced later forgetting.

Safety behaviour is a learned task too. Qi et al. (ICLR 2024) fine-tuned GPT-3.5 Turbo through OpenAI's fine-tuning API on 10 adversarially designed examples, at a cost under 0.20 US dollars, and the model then responded to nearly any harmful instruction. Fine-tuning on benign, commonly used datasets also degraded safety alignment, to a lesser extent.

What driftedMechanismSource
Domain knowledge and reasoningNarrow instruction data pulls shared weightsLuo et al., 2023
Refusal and safety behaviourAlignment is an earlier task the new data does not rehearseQi et al., 2024

Gotcha: Every fine-tune is a continual learning step. If your evaluation suite covers only the target task, you are reporting plasticity and calling it success.

5. LoRA learns less and forgets less

Low-rank adapters are parameter isolation in miniature: the base weights stay frozen and the update is confined to a small low-rank subspace. Biderman et al. (Transactions on Machine Learning Research, 2024) measured what that buys, on code and mathematics, with instruction tuning on about 100,000 prompt-response pairs and continued pretraining on 20 billion tokens.

  • On the target domain, LoRA in standard low-rank settings substantially underperformed full finetuning.
  • On the source domain, LoRA preserved more of the base model's abilities, forgetting less than full finetuning and less than the common regularisers weight decay and dropout.
  • Full finetuning learned weight perturbations with a rank 10 to 100 times greater than typical LoRA configurations, which is the mechanism behind both results: a low-rank update cannot travel as far.

That is the stability-plasticity dial again, set by the adapter rank rather than a penalty strength. A low-rank constraint limits interference; it does not remove it. A separate adapter per domain, swapped in by a router, is the stronger isolation, with the routing problem the second lesson of this cursus described.

6. Sparse updates: isolation inside one model

Lin et al. at FAIR, Meta (2025) pushed the isolation idea further with memory layers, which hold a very large table of key-value slots of which each token reads only a few. Their sparse memory finetuning updates only the slots that a new piece of knowledge activates heavily relative to how often pretraining data uses them, so new facts land where little else lives.

Drop in NaturalQuestions F1 after learning new facts
%020406080100897111Full finetuningLoRASparse memory finetuning
Source: Lin et al., Continual Learning via Sparse Memory Finetuning, FAIR at Meta, 2025 (same level of new-knowledge acquisition for each method)

At the same level of new-knowledge acquisition, held-out NaturalQuestions F1 fell 89% after full finetuning on the new facts, 71% with LoRA, and 11% with sparse memory finetuning. LoRA helps, as Biderman et al. found, but most of the damage remains when the new facts are pushed through shared parameters.

Key idea: The same principle as PackNet or per-task masks, applied at the granularity of individual memory slots: confine each update to parameters that the rest of the model's knowledge barely uses.

7. Why on-policy RL forgets less

Shenfeld, Pari and Agrawal at MIT's Improbable AI Lab (2025) compared supervised fine-tuning (SFT) with on-policy reinforcement learning (RL) trained to similar new-task performance, and found RL preserved prior capabilities markedly better. Across their experiments, the best single predictor of forgetting was how far the fine-tuned model's output distribution moved from the base model's, measured on the new task's inputs:

shift=Ex∼new task[KL(πbase(⋅∣x) ∥ πtuned(⋅∣x))]\text{shift} = \mathbb{E}_{x \sim \text{new task}} \left[ \mathrm{KL}\left(\pi_{\text{base}}(\cdot \mid x) \,\|\, \pi_{\text{tuned}}(\cdot \mid x)\right) \right]

A quadratic fit of forgetting against this shift reached R2=0.96R^2 = 0.96 in their MNIST setting and R2=0.71R^2 = 0.71 in their language model experiments. The explanation they give: on-policy RL samples from the model itself and reweights those samples, so among the many solutions to the new task it drifts toward one close to the base model. SFT on fixed target outputs can pull the model arbitrarily far.

In practice: Fine-tuning targets that the model could plausibly have produced itself, such as filtered self-generated answers, move the distribution less than external labels, and the KL shift on the new task can be tracked during training as an early warning of forgetting.

8. Knowledge editing: surgery on single facts

Sometimes the new task is one fact. Knowledge editing changes it directly instead of fine-tuning. ROME (Meng et al., NeurIPS 2022) treats a mid-layer MLP as a key-value store and applies a rank-one update so that a subject maps to a new object. MEMIT (Meng et al., ICLR 2023) spreads the update over several layers and scales to 10,000 edits applied in one batch.

Edits are continual learning too, and they forget in the same ways:

  • Sequential edits accumulate damage. Gupta, Rao and Anumanchipalli (ACL Findings 2024) applied ROME and MEMIT edits one after another. For ROME on GPT-J, edit success stayed near 100% until a point of decline that came as early as 100 edits or as late as 1,000, while accuracy on neighbouring facts fell steadily throughout. The gradual phase then ended abruptly with a single "disabling edit", after which new edits failed, earlier edits were forgotten and downstream tasks broke. Some of those facts disabled the model even when edited first.
  • Consequences do not propagate. Cohen et al. (TACL 2024) built RippleEdits, 5,000 edits with checks on facts that should change as a result. Prominent editing methods failed to make consistent changes, and a simple in-context baseline, stating the new fact in the prompt, scored best.

Gotcha: An edit that passes its own test can still contradict the facts around it. Evaluate the neighbourhood, not just the target.

9. Editing, fine-tuning or retrieval

For changing what a model knows, the three options trade forgetting risk against other properties. The fine-tuning versus RAG cursus develops the retrieval side in depth; here the axis is continual learning.

Fine-tuningKnowledge editingRetrieval
What changesMany weightsA few targeted weightsNothing in the model; the context
Forgetting riskHighest, grows with distance movedAccumulates over sequential editsNone to the weights
Updating a fact againRetrainAnother edit, more damageReplace the document
Consistency with related factsUnreliablePoor, per RippleEditsDepends on what is retrieved
Best forSkills, formats, behaviourA small number of urgent correctionsVolatile or large bodies of facts

The pattern from RippleEdits generalises: putting the fact in context often beats putting it in weights, because context changes nothing else.

Key idea: Continual learning in weights is the right tool for skills. For facts that change, the most forgetting-proof memory is one outside the network.

10. A checklist for updating a deployed model

The whole cursus reduces to a short operating procedure for any update to a model that already works:

  1. Freeze a regression suite before training. General capabilities, safety behaviour and the previous task, scored on the base model. Report the change on each, which is backward transfer under another name.
  2. Replay. Mix a share of earlier data, or general instruction data, into every batch. It is the most consistently effective fix at every scale this cursus covered.
  3. Limit the distance travelled. Moderate learning rates, few epochs, low-rank or sparse updates, and targets close to the model's own distribution.
  4. Isolate when tasks really differ. One adapter per domain, with an explicit router, beats one adapter trying to hold everything.
  5. Keep changing facts out of the weights. Retrieve them, and reserve editing for rare, urgent corrections.
  6. Watch for intransigence too. A model that has been updated many times can learn new things more slowly; measure how fast a fresh task is learned, not just what was retained.

In practice: If you can afford to retrain on all the data, retraining remains the upper bound every method here is measured against. Continual learning is what you do when you cannot, and the checklist is how you find out what it cost.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. In Ibrahim et al.'s continued-pretraining study, what was the downside of re-warming the learning rate?
    • It prevented the model from adapting to the new corpus
    • It made replay unnecessary
    • It increased forgetting, even when training continued on the same data
    • It only worked at the 10 billion parameter scale
  2. What did Qi et al. show about fine-tuning an aligned model?
    • Ten adversarial examples, costing under 0.20 US dollars, removed GPT-3.5 Turbo's safety guardrails, and benign data also degraded safety somewhat
    • Fine-tuning always improves safety if the data is benign
    • Safety behaviour is stored in separate weights that fine-tuning cannot reach
    • Only fine-tuning on more than one million examples affects safety
  3. According to Biderman et al., why does LoRA forget less than full finetuning?
    • It trains on replayed pretraining data automatically
    • It uses a smaller learning rate by design
    • It applies an EWC penalty to the base weights
    • Its low-rank update cannot move as far; full finetuning learned perturbations of 10 to 100 times higher rank
  4. Shenfeld, Pari and Agrawal found one quantity that best predicted forgetting. What was it?
    • The number of fine-tuning steps
    • The KL divergence between the base and fine-tuned models' outputs, measured on the new task's inputs
    • The size of the model in parameters
    • The accuracy reached on the new task
  5. A support assistant must reflect price changes that happen every week. Which approach carries the least forgetting risk?
    • Weekly full fine-tuning on the new prices
    • A ROME edit for each changed price, applied sequentially
    • Retrieving the current price list into the context at query time
    • Training a new LoRA adapter each week and merging it into the base weights

Related lessons

AI
advanced

Fixing Forgetting: Replay, Regularisation, and Parameter Isolation

The three families of continual learning methods, taken apart: experience and generative replay, gradient projection with GEM, weight penalties from EWC and synaptic intelligence, distillation, and per-task adapters. Includes a runnable PyTorch comparison of EWC and replay, and a table for choosing among them.

9 steps·~14 min
AI
intermediate

Catastrophic Forgetting: Why Neural Networks Overwrite What They Knew

Train a network on one task, then another, and the first often collapses. This lesson shows why: shared weights and conflicting gradients, demonstrated in twenty lines of code, then the stability-plasticity dilemma, the less known loss of plasticity, and how the brain's replay suggests the fixes.

10 steps·~15 min
AI
advanced

Measuring Continual Learning: Scenarios, Transfer Metrics, and Honest Baselines

The same method can score 99% or 21% on one benchmark depending on what the model is told at test time. Learn the task-, domain- and class-incremental scenarios, the accuracy matrix with backward and forward transfer, and the protocol choices and baselines that make a continual learning result trustworthy.

9 steps·~14 min
AI
intermediate

Bedrock: One Door to Many Models

Amazon Bedrock's pitch is that model choice becomes a configuration value instead of a rewrite. This lesson takes that claim apart: the four API dialects Bedrock exposes over the same models, what the unified Converse API actually normalises, what it cannot normalise, and the inference and governance machinery that decides cost and blast radius.

7 steps·~11 min