Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

8.5 Continued Pre-training & Domain Adaptation

Continued pre-training (CPT) resumes a model’s pre-training objective from an existing checkpoint. For a causal language model, that means predicting the next token in unlabeled text. If you are choosing a training mixture, compare one pass with two passes through the same 80 work orders.

An equipment repair record says OUT P17 / IN P19. A technician asks which part is now installed. The assistant answers “P17.” Before training on a million repair records, give the model the right record and its notation key. In this shop, OUT marks the part removed and IN marks the replacement. What happens to the answer?

Decision Gate: CPT, RAG, or SFT?

If the model now picks P19, start with retrieval-augmented generation (RAG) and check whether retrieval supplies both pieces of evidence on unseen work orders. If it picks P19 but keeps putting it in the wrong output field, test a labeled example and then supervised fine-tuning (SFT). CPT becomes worth testing if the model still misreads the shorthand across many unseen orders after it sees relevant context and examples, and you have representative records to train on.

Observed gapFirst intervention to testWhyEscalate to CPT when
Facts change frequently or must be citedRetrieval-augmented generation (RAG)Updates are reversible and sources remain inspectableThe model cannot parse, rank, or synthesize the domain text even with good retrieval
Output format, tool protocol, tone, or task policy is wrongSFTDirectly supervises the desired input-output behaviorErrors trace to missing domain representations rather than response policy
Domain language has unfamiliar syntax, jargon, or long-form structurePilot CPT on unlabeled domain textRepeatedly predicts domain text in contextThe gap persists with good retrieval and a small supervised baseline
Both domain fluency and interaction behavior are missingCPT, then SFTSeparates distribution adaptation from behavioral supervisionOnly after cheaper RAG/SFT baselines and retention gates are measured

Run a controlled baseline for each plausible intervention. A lower domain perplexity is not sufficient evidence that users will receive better answers; compare the downstream task, retrieval-grounded baseline, cost, latency, and regression risk.

DAPT, TAPT, and Continual Pre-training

The terminology identifies the data stream and operational intent:

  • Domain-adaptive pre-training (DAPT) continues on a broad domain corpus, such as biomedical literature or source code. The original DAPT experiments showed gains for particular RoBERTa classification settings, not a universal guarantee for every generative model [1].
  • Task-adaptive pre-training (TAPT) continues on the unlabeled text distribution of a specific downstream task. It is narrower than DAPT and can follow it.
  • Continual pre-training processes a sequence of domains or time slices while trying to retain earlier capabilities. It introduces explicit stability-plasticity and replay decisions [2].
  • Continued pre-training is the broader operational term used in this chapter: resume the pre-training objective from an existing artifact. A single DAPT run is one form of CPT.

Write the intended sequence in the run specification. “Base checkpoint → DAPT → SFT → preference optimization” and “instruction checkpoint → temporal update” have different failure modes and cannot share an unqualified recipe.

Agentic Midtraining: Evaluate What Survives Post-training

Research snapshot as of 2026-11-25. Singhal et al.’s October preprint trains Nemotron models at 256K context on repositories, pull requests, commit histories, build logs, and agent traces. The authors ran the same SFT stage on the starting checkpoint and on the midtrained checkpoint. Base-model metrics did not reliably predict which recipe would work better after SFT [6]. The study focused on coding agents. Choosing where to spend a fixed token budget still requires a comparison with spending those extra tokens on pre-training or SFT.

The engineering implication is to evaluate post-trainability as well as current loss. For a pilot, fork matched base checkpoints into a no-midtraining control and candidate mixtures, then run the same small SFT probe with fixed data, template, token budget, and harness. Reuse the operational contracts below; specifically record which tool-result tokens are supervised, repository-level split boundaries, agent-trace provenance, and packed-document attention policy. Compare task success, critical regressions, and total training cost. Stop if representation gains disappear after the fixed downstream stage. A better base perplexity alone is not a promotion gate.

Choose the Starting Checkpoint

Prefer a base checkpoint when the objective is broad distribution adaptation and a later SFT stage is available. It preserves a clean next-token-training contract and avoids depending on an undisclosed instruction-tuning mixture. Starting from an instruction-tuned checkpoint can preserve an already useful interface, but sustained CPT may weaken chat formatting, refusal behavior, tool use, and calibration. The risk must be measured rather than assumed.

Freeze one immutable input bundle before the pilot:

ArtifactRequired identity
Modelprovider/repository, revision, config, weight hashes, license
Tokenizerfiles and hash, normalization rules, vocabulary size, special-token IDs
Prompting contractchat template bytes, BOS/EOS policy, generation prompt behavior
Datamanifest version, source/license/consent, filters, shard hashes, deletion lineage
Training systemcode commit, resolved config, container, CUDA/framework/kernel versions
Evaluationfrozen task and retention sets, prompt/rubric versions, decoding configuration

Load the checkpoint and run the complete baseline evaluation before the first update. If the baseline cannot be reproduced, a later regression cannot be attributed to CPT.

Build the Data Mixture

The repair records expose the model to shop shorthand. Replay mixes in text representative of capabilities the model should retain. Choosing the domain source with probability λ\lambda and the replay source with probability 1−λ1-\lambda gives the mixture

p(x)=λpdomain(x)+(1−λ)preplay(x),p(x) = \lambda p_{\text{domain}}(x) + (1-\lambda)p_{\text{replay}}(x),

Here xx is one draw and pdomainp_{\text{domain}} and preplayp_{\text{replay}} are the source distributions. The unit of a draw matters. In Hugging Face Datasets, interleave_datasets with source probabilities chooses which dataset supplies the next example (as of 2026-11-25) [7]. An example can be a short work order, an entire manual, or a block of tokens.

What does a second pass through the same 80 work orders buy?

First count the positions that contribute to next-token loss. This Python example has one right-padded document per row, a beginning token in the first position, a scored end token (ID 2), and padding labels set to -100. Each prediction is scored against the following position. The first label therefore drops out before we count.

def loss_targets(labels):
    return sum(target != -100 for target in labels[1:])

assert loss_targets([1, 42, 73, 2, -100, -100]) == 3
domain = loss_targets([1] + [42] * 399 + [2, -100])
replay = loss_targets([1] + [73] * 3999 + [2])
assert (domain, replay) == (400, 4000)

The repeated token IDs stand in for lengths. Suppose each of 80 distinct work orders contributes 400 targets and each replay document contributes 4,000. Compare two schedules with an identical budget of 112,000 targets, giving every target equal weight in the loss.

ScheduleWork-order visitsReplay documents, each seen onceDomain targetsReplay targetsDomain share
Read each work order once802032,00080,00028.6%
Read each work order twice1601264,00048,00057.1%

In the first schedule, 80% of the documents supply only 32,000 / 112,000 of the targets. In the second, eight fewer long replay documents make room for another pass through the same 80 work orders. Domain exposure doubles while the number of distinct work orders stays at 80. The arithmetic tells you what the model sees. Whether the second pass improves performance on a new work order is an evaluation question.

What would it take to give each source exactly half the targets? One replay document supplies as many targets as ten work orders. At this budget, 140 work-order visits and 14 replay visits give 56,000 targets from each source. That is about 90.9% work-order visits. Recalculate the ratio if truncation or masking changes the targets per visit.

Download the two schedules as a figure (PNG).

Download the Python token-count audit. Run python token_exposure.py to reproduce both schedules, or python token_exposure.py visits.csv for your own run. Each CSV row records one document visit as source,document_id,loss_targets. Count targets after truncation, packing, and label masking. If a visit spans several blocks, add their contributions and reuse the document ID on later visits.

The immutable dataset manifest should contain source URI or internal ID, license or consent basis, collection time, PII/secrets policy, deletion lineage, language/domain labels, filter versions, exact and near-duplicate cluster IDs, shard checksum, tokenizer hash, and sample ID. Perform deduplication and semantic clustering before assigning train/dev/test splits. Quarantine public benchmarks, private release prompts, rubrics, semantic neighbors, and synthetic variants from both domain and replay corpora.

Choose λ\lambda with a pilot sweep. Compare at least a domain-heavy mixture, a balanced mixture, and a replay-heavy control. The goal is a Pareto point: required domain gain with acceptable base-capability and safety retention. Replay is not a guarantee against forgetting, and very aggressive replay may prevent useful adaptation.

Document boundaries are part of the objective. Insert the tokenizer’s intended EOS/document separator, mask padding, and record whether packed documents may attend across boundaries. Cross-document attention can be deliberate for throughput, but it must be identical in training, evaluation, and any continuation-equivalence test.

Tokenizer and Vocabulary Decisions

Default to the original tokenizer. Changing tokenization changes sequence lengths, document boundaries, embedding identities, and checkpoint compatibility. Before deciding, measure:

  • byte or character round-trip behavior and unknown/fallback rate;
  • tokens per byte and the long tail of tokens per document by language/domain;
  • fragmentation of code, formulas, identifiers, and domain terms;
  • collisions and frequencies for reserved and special tokens;
  • encode/decode offsets and BOS/EOS behavior.

Do not add tokens merely because domain words are split. Subword composition may be adequate, and vocabulary changes add deployment and recovery risk. If the acceptance test shows a material throughput or representation problem, append tokens without reassigning existing IDs, initialize the new embedding and output rows deliberately, call the framework’s embedding-resize operation, and train those rows. The Hugging Face tokenizer contract explicitly requires resizing model embeddings after adding tokens [3]. Version the tokenizer and model as an inseparable artifact; an old serving tokenizer must be rejected at load time.

What happens to perplexity if a part ID becomes a token?

Take two six-byte strings from a toy parts log, P19P19 and P91P91. A predictor that guesses uniformly among the tokens P, 1, and 9 gives each possible next token probability 1/3. Give a second predictor a fourth token, P19, and let it guess uniformly too. Neither has had a training update. When the new token matches, the tokenizer takes it in one piece.

A token assigned probability pp costs −log⁡2p-\log_2 p bits. If the mean cost per token is bb, perplexity is 2b2^b. For bits per byte, divide the total cost by the number of UTF-8 bytes in the scored text. This example fixes the string length and scores only its contents, with no padding or boundary tokens.

import math
import re

for text in ("P19P19", "P91P91"):
    for pattern, vocab_size in [(r"[P19]", 3), (r"P19|[P19]", 4)]:
        tokens = re.findall(pattern, text)
        assert "".join(tokens) == text
        bits = len(tokens) * math.log2(vocab_size)
        perplexity = 2 ** (bits / len(tokens))
        bits_per_byte = bits / len(text.encode("utf-8"))
        print(text, vocab_size, len(tokens), f"{perplexity:.0f}", f"{bits_per_byte:.3f}")
TextVocabulary sizeTokens scoredPerplexityBits per byte
P19P193631.585
P19P194240.667
P91P913631.585
P91P914642.000

The new vocabulary raises per-token perplexity on both strings. For P19P19, it takes just two guesses to cover six bytes, so the cost per byte falls. For P91P91, all six guesses remain, each drawn from a larger vocabulary. Schaeffer and Koyejo’s November 3 preprint reports that tokenizer changes can move bits per byte even for untrained models [8].

In a CPT pilot, score the same held-out text spans with the same preceding context, and sum the bits and scored bytes across records before dividing. A character can contribute several UTF-8 bytes. This measures the model and tokenizer together. To find out whether the new token helps a technician, also check how often the system extracts the installed part correctly, including on IDs it never saw in training.

Pilot Before Scaling

Treat hyperparameters as experimental decisions, not book constants. Begin with a short run on a small model or a small token budget using the exact data path and evaluation harness intended for scale. Sweep learning rate, warmup, domain/replay weight, effective tokens per update, sequence length, and—if applicable—full-parameter versus adapter training.

Before launch, write a resource worksheet that separates:

  • parameters, gradients, optimizer states, master weights, adapters;
  • activations under the selected sequence length, microbatch, checkpointing, and attention kernel;
  • temporary buffers and peak collective/all-gather memory;
  • checkpoint staging and evaluation memory;
  • achieved FLOP/s, tokens/s/GPU, data-wait time, checkpoint bandwidth, restart overhead, and expected wall-clock cost.

Use the smallest learning rate that produces a meaningful, repeatable domain improvement within the pilot budget. A common fine-tuning learning rate is not automatically safe for CPT. Set warmup and decay in tokens, because gradient accumulation and variable-length packing can make “steps” incomparable. Scale only after one-worker, one-node, and multi-node smoke tests agree on loss masking, sample IDs, token counts, and checkpoint restoration.

Observable run contract

The dashboard should include global and token-normalized training/validation loss, domain and replay loss, fixed downstream probes, global and per-layer gradient/weight/activation norms, nonfinite and overflow counts, clipping fraction, learning rate, throughput, MFU, data-wait time, p50/p95 step time, collective time, stragglers, and reconstructable batch/sample IDs.

Define abort conditions before launch. Examples include any nonfinite parameter, repeated loss spikes that reproduce from a known-good checkpoint, a critical safety-slice failure, checksum mismatch, unexplained sample duplication, or domain progress accompanied by retention loss beyond the approved bound. The actual numeric thresholds must come from the pilot and product risk level.

Checkpoint and Exact Continuation Contract

A recoverable CPT checkpoint is more than model weights. Save sharded model and optimizer state, scheduler, gradient scaler or FP8 scaling state, global step and consumed tokens, every relevant RNG state, sampler state, and the exact data cursor. Bind them to dataset, tokenizer, model, code, and resolved-config hashes.

The data cursor should identify at least dataset version, epoch or stream generation, global rank and worker partitioning rule, deterministic permutation seed, shard ID, and sample or token offset. A worker-local counter is not sufficient: IterableDataset workers are separate processes, and the saved state must be consolidated with the model checkpoint.

Use a two-phase publish:

  1. Each rank writes to a unique temporary checkpoint location and records checksums.
  2. The coordinator verifies the expected shards and metadata, then atomically publishes a completion marker or manifest.

Readers load only completed checkpoints. Distributed checkpoint libraries can parallelize save/load and support load-time resharding, but their guarantees and APIs must be verified for the deployed framework version [4]. Run restore drills at the original world size and, when supported, a changed world size. A continuation-equivalence test should compare sample IDs, learning rate, and the next several losses/updates against an uninterrupted control within a declared numerical tolerance. At large scale, promise statistical equivalence unless the complete stack actually guarantees bitwise replay [5].

Evaluation and Release Gates

Evaluate checkpoints during training, not only at the end. Keep generation seeds, decoding parameters, prompt templates, evaluator versions, and baseline artifact hashes fixed.

GateMinimum evidenceExample failure action
Domain modelingheld-out domain perplexity/loss by source and languageinspect mixture, tokenizer, or contaminated split
Domain utilityprivate task metrics and blinded human or verifier reviewstop if lower perplexity does not transfer
Base retentiongeneral capability suite and replay-domain lossincrease replay, reduce LR/tokens, or roll back
Behavior retentionformat, instruction, tool-use, and refusal testsrerun SFT only after root-cause analysis
Safety/privacytoxicity, memorization, PII, jailbreak, and policy slicesblock release and quarantine offending data
Operationslatency, memory, error/OOM rate, cost, artifact compatibilityreject incompatible or uneconomic artifact

Use paired comparisons and uncertainty intervals where possible. Define minimum samples for critical slices; a global average must not offset a privacy or safety failure. Promote the CPT artifact only if it meets the domain target and every retention/release gate. Otherwise keep the last-known-good bundle.

For a hypothetical pilot, score the exact installed-part ID on the same 100 held-out work orders, with identical retrieved context. Suppose the one-pass schedule gets 82 right. The two-pass schedule fixes eight mistakes and introduces three new ones, for 87 right. Inspect those three regressions and check the general retention suite before deciding whether to spend 32,000 of the budgeted targets on repeat visits.

Failure Modes and Runbook

Domain loss improves while downstream quality does not. Check contamination, tokenization, and whether the task needs retrieval or labeled behavior rather than more language modeling. Compare against the frozen RAG and SFT baselines.

General ability or safety regresses. Reproduce the change on fixed slices, inspect the domain/replay realized token mix, reduce learning rate or training duration, and sweep more representative replay. Do not blindly reset optimizer moments; that changes the optimization trajectory and may create another instability.

A loss spike appears. Freeze the artifact IDs and suspect batch IDs, confirm all ranks agree on the step and nonfinite state, replay the batch from a known-good checkpoint, compare skip/replay/control branches, and bisect data, optimizer/numerics, and hardware. Quarantine a shard only with evidence and preserve it for diagnosis.

Resume diverges. Reject incomplete checkpoint manifests; compare world size, code/config hashes, RNG and sampler states, data cursor, packing order, and learning-rate/token counters. A model-only checkpoint is a warm start, not an exact resume.

Serving behavior changes unexpectedly. Verify the complete artifact bundle—base, CPT weights or adapter, tokenizer, chat template, generation config, tool schema, and safety configuration. Roll traffic back with the predeclared feature flag and last-known-good bundle, then rehearse the repaired path before ramp-up.

The deliverable from CPT is therefore not a weight file. It is a versioned artifact plus evidence that the model learned the intended distribution, retained required capabilities, can resume deterministically enough for the operating environment, and can be rolled back safely before later SFT or preference optimization.

Quizzes

Quiz 1: A model answers current regulations incorrectly but can summarize a retrieved regulation accurately. Should CPT be the first intervention? No. The facts change and require provenance, while the model can already interpret the text. A retrieval baseline is more reversible and keeps sources inspectable. CPT becomes relevant only if controlled evaluation shows that the model cannot process the domain material even with good retrieval.

Quiz 2: How can the domain share reach 57.1% without collecting another work order? Read the same 80 orders twice. They now contribute 64,000 scored targets, leaving room for 48,000 replay targets within the fixed budget. Record both the target count and the distinct document IDs to tell repetition from broader coverage.

Quiz 3: After adding P19 to the vocabulary, bits per byte falls on repeated P19s. What would convince you to keep the token? The extra token shortens that particular string even with uniform guesses. Measure token counts, bits per byte, and installed-part accuracy on representative held-out records, including other IDs. Check the resized embeddings, tokenizer revision, and serving compatibility before rollout.

Quiz 4: Why is saving model and optimizer weights insufficient for exact continuation? The next update also depends on scheduler and precision-scaler state, global tokens, RNG states, sampler partitioning, packing order, and the exact data cursor. Missing any of these can change samples or updates even when the weights are identical.

Quiz 5: Domain perplexity falls significantly, but the private task metric is flat and a safety slice regresses. Can the checkpoint be released? No. Perplexity is a diagnostic rather than the product objective, and a critical safety failure cannot be averaged away. The run should remain behind the release gate while the team checks whether RAG/SFT is the better intervention and investigates the data mixture and regression.

References

  1. Gururangan, S., et al. (2020). Don’t Stop Pretraining: Adapt Language Models to Domains and Tasks. ACL Anthology.
  2. Cossu, A., et al. (2022). Continual Pre-training Mitigates Forgetting in Language and Vision. arXiv:2205.09357.
  3. Hugging Face. Tokenizer documentation: adding tokens and resizing embeddings. Transformers documentation.
  4. PyTorch. Distributed Checkpoint. PyTorch 2.15 documentation.
  5. PyTorch. Reproducibility. PyTorch 2.15 developer notes.
  6. Singhal, S., et al. (2026). Priming Base Models for Agentic Post-Training: An Open Midtraining Recipe. Preprint. Source.
  7. Hugging Face. Datasets: interleave_datasets. Example-level source sampling and stopping strategies. Checked 2026-11-25.
  8. Schaeffer, R., and Koyejo, S. (2026). Tokenizer Myths and Where To Find Them. Preprint, §§2–3.