Foundations to Frontier
Tests
F. NLP and Large Language Models › F6 Fine-Tuning and Adaptation

Domain Adaptation of LLMs (e.g., Scientific Text)

General LLMs can do poorly on specialised text: scientific papers, legal contracts, medical notes, aerospace manuals, code in rare languages. Domain adaptation options range from cheap to expensive. Retrieval-augmented prompting (F10). Supervised fine-tuning on domain tasks (F6-2). Continued pretraining on domain text (domain-adaptive pretraining, DAPT, as in BioBERT, SciBERT, Galactica and Meditron), usually mixed with general data to limit forgetting. Vocabulary extension for domain terms. Training a domain model from scratch (BloombergGPT). The art is balancing domain gain against loss of general ability. In the exercises you measure domain OOV rates, initialise embeddings for new tokens and interpolate models, then adapt trigram language models from a general source to a related domain with only 5000 domain tokens. On domain text the general model scored perplexity 102.5, the domain-only model 39.3 (but 13.8 on general text, against 5.27). Pooling domain with general data gave 66.4, and repeating the domain data 10× made it worse (96.6). Interpolating the general and domain models with a weight tuned on domain data was best on the domain (33.5) while keeping general perplexity at 7.6.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Teaching a general model a specialist’s language

A model that has read the whole web still stumbles on the dense jargon of a jet-engine manual or a physics paper. You can teach it the specialist language by letting it read lots of domain text, by fine-tuning it on domain questions, or by combining a general model with a small domain model. The challenge is to gain the new speciality without forgetting general knowledge. The demo measures how different two text distributions are.

Transfer and efficiency lab
Squared MMD between source (green) and target (red) samples: 0.281. Domain adaptation trains features that make this gap small while still classifying the source well.
Why engineers care

Aerospace text (ATA chapters, part numbers, NOTAMs, standards) is a classic adaptation domain: models need its vocabulary and conventions, and must stay reliable on general language.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Domain adaptation helps a model with…
  2. 2. Continued pretraining means further training on…
  3. 3. A key risk of domain adaptation is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Options, cheapest first:
    1. prompting with retrieved domain context (F10);
    2. SFT on domain tasks;
    3. continued (domain-adaptive) pretraining, then SFT;
    4. a domain model from scratch.
  • Continued pretraining: on domain text, typically billions of tokens (for example 10% of a Chinchilla budget, 14B tokens for a 7B model), with 10–30% general replay (10B general tokens alongside 30B domain tokens at 25%) and a modest learning rate with re-warm-up.
  • Vocabulary extension: add frequent domain tokens to reduce fertility; initialise new embeddings at the mean of existing ones (5000 tokens × 4096 dims = 20.5M new parameters), then train embeddings first.
  • Model interpolation: mix the predictions (or weights, F6-5) of a general and a domain model with λ chosen on domain validation data.
  • Evaluation: domain perplexity and tasks, plus general benchmarks to measure forgetting.
  • Examples: BioBERT and SciBERT (encoders), Galactica (science), Meditron (medicine), BloombergGPT (finance, from scratch on a 50/50 mixture).
📝 Quick check (Level 1)
0/3 answered
  1. 1. General replay share often used in continued pretraining:
  2. 2. New token embeddings are often initialised at…
  3. 3. Interpolation weight λ is chosen on…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Domain adaptation in code

Exercise 1.

  • Measure the share of domain tokens missing from a vocabulary.
  • Initialise embeddings for new tokens at the mean of existing ones.
  • Interpolate general and domain predictions.

Practice.

  • Continue pretraining with the same causal-LM objective using Trainer on domain text plus general replay; re-warm the learning rate to a fraction of the original peak.
  • tokenizer.add_tokens and model.resize_token_embeddings for vocabulary extension.
  • Deduplicate domain text against evaluation sets; domain corpora are small and leakage is easy.
  • Try RAG and SFT before continued pretraining; they are far cheaper and often sufficient.
tok.add_tokens(["FADEC", "N1", "EGT", "ATA-29"])                 # frequent domain terms
model.resize_token_embeddings(len(tok))
with torch.no_grad():
    E = model.get_input_embeddings().weight; E[-4:] = E[:-4].mean(0)    # mean initialisation
# then: continued pretraining on domain text + ~20% general replay, lr re-warmed to ~1/3 of the original peak
🐍 Exercise 1: domain OOV, new embeddings and interpolation
Compute domain OOV rates, initialise new token embeddings and interpolate two models' predictions.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Method to grow the embedding matrix in Hugging Face:
  2. 2. Before continued pretraining, first try…
  3. 3. Domain corpora must be deduplicated against…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Bias and variance again. A general model is low-variance but biased for the domain. A model trained only on a small domain set is unbiased but high-variance (it has seen few contexts) and forgets everything else. Combining them, by pooling data or interpolating, trades the two; the best weight depends on how much domain data there is and how far the domain is from general text.

Why repetition backfired. Repeating 5000 domain tokens 10 times makes the observed domain trigrams look ten times more certain, so the model gives too little probability to the many unseen domain trigrams. This is the n-gram analogue of overfitting by over-sampling a small dataset (compare repeated epochs, F5-2).

Forgetting. Any update that moves the model towards the domain moves it away from general text unless general data is kept in the mix. Interpolation makes the trade explicit through λ.

📝 Quick check (Level 3)
0/3 answered
  1. 1. A small domain-only model has high…
  2. 2. Over-repeating a small domain set causes…
  3. 3. Interpolation makes the domain–general trade explicit through…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How should a small domain corpus be combined with a general model?

History.

  • S. Gururangan et al., “Don’t stop pretraining: adapt language models to domains and tasks” (ACL 2020).
  • I. Beltagy, K. Lo and A. Cohan, “SciBERT” (EMNLP 2019); J. Lee et al., “BioBERT” (Bioinformatics, 2020).
  • S. Wu et al., “BloombergGPT” (2023); Z. Chen et al., “Meditron-70B” (2023).

Exercise 2.

  • Sources: a general language-like trigram source, and a related domain source: each domain trigram distribution mixes the general one with a domain-specific one. The domain’s own perplexity is 21.7.
  • Data: 200,000 general tokens; only 5000 domain tokens.
  • Models (Kneser–Ney trigram):
    • general only;
    • domain only;
    • pooled general + domain (continued pretraining), with the domain repeated 1× or 10×;
    • interpolation λ·domain + (1 − λ)·general with λ tuned on 3000 domain dev tokens.
model domain perplexity general perplexity
general only 102.54 5.27
domain only (5000 tokens) 39.29 13.83
pooled, domain 1× 66.40 5.29
pooled, domain 10× 96.57 5.61
interpolated (λ = 0.6) 33.50 7.57
true domain source 21.69 —
  • The general model fails on the domain, and the small domain model forgets general text.
  • Adding domain data helps a little for free: pooling 1× improves the domain (102.5 → 66.4) without hurting general text, but 5000 tokens are swamped by 200,000.
  • Upweighting by repetition backfired: 10× repetition overfits the small domain sample (96.6).
  • Interpolation is best here: it combines the general model’s coverage with the domain model’s specialisation (33.5), at a moderate general cost.
  • Seed 1: general 106.1, domain-only 39.0, pooled 66.9, pooled 10× 95.2, interpolated 33.4 (λ = 0.65).
🐍 Exercise 2 (research): how should a small domain corpus be combined with a general model?
Adapt trigram models from a general source to a related domain with little domain data: general, domain-only, pooled (1× and 10×) and interpolated models.

Domain adaptation in AI, robotics and aerospace

  • Aerospace assistants: continued pretraining on manuals and standards plus SFT on engineer questions, with general replay.
  • Scientific tools: domain models for propulsion, materials or astrodynamics literature.
  • Design lesson: combine general coverage with domain specialisation deliberately, and measure both.

References

  1. S. Gururangan et al. (2020). “Don’t stop pretraining: adapt language models to domains and tasks.” Proc. ACL.
  2. I. Beltagy, K. Lo and A. Cohan (2019). “SciBERT: a pretrained language model for scientific text.” Proc. EMNLP.
  3. S. Wu et al. (2023). “BloombergGPT: a large language model for finance.” arXiv:2303.17564.
  4. Z. Chen et al. (2023). “Meditron-70B: scaling medical pretraining for large language models.” arXiv:2311.16079.