Build and Serve a Domain-Adapted LLM Without Hallucinating
Machine LearningModel answerLast updated
Design, fine-tune, and operate a Transformer-based LLM on a specialized corpus while preserving general capabilities and controlling hallucinations in production.
Scenario
Your team is deploying a large language model to answer natural-language queries over a proprietary document corpus — think legal contracts, clinical notes, or financial filings. The system will serve real users, where a confidently wrong answer is worse than no answer at all.
You have access to a pretrained open-weight decoder-only LLM (7B–70B parameters) and roughly 5 billion tokens of domain text plus a few thousand curated question-answer pairs.
What you are expected to cover
Part 1 — Architecture. Walk through how a modern decoder-only Transformer is structured. What are its core components, and how do the design choices (normalization placement, positional encoding, attention variant, MLP activation) affect capability and efficiency?
Part 2 — Long-range dependencies. Explain mechanically how self-attention lets a model relate tokens that are thousands of positions apart. Compare this to recurrent models and be honest about the costs and failure modes.
Part 3 — Domain adaptation without catastrophic forgetting. Describe the full pipeline from raw domain data to a production-ready checkpoint. What techniques prevent the model from losing its general capabilities during fine-tuning? What should you gate on before shipping?
Part 4 — Hallucination: evaluation, monitoring, and mitigation. Define the types of hallucination relevant to a grounded QA system. Sketch the serving architecture. Explain how you measure faithfulness before launch, how you track it on live traffic, and what operational levers reduce hallucination rate over time.
What a strong answer looks like
- States concrete assumptions (parameter count, QPS, latency budget, risk tolerance) before diving in.
- Gives specific numbers: memory costs, learning rates, sample sizes, metric thresholds.
- Names trade-offs explicitly rather than listing techniques as universally good.
- Identifies what can go wrong at each stage and how you would catch it.
Hints
Hint 1
Start by fixing your assumptions out loud: model size, serving load, and what 'wrong answer' costs in your domain. These choices cascade into every subsequent decision.
Hint 2
For the attention section, think about what property makes O(1) path length between tokens meaningful — and then name at least one reason the model might still fail on long documents in practice.
Hint 3
Catastrophic forgetting has more than one cause. Separate the 'weights drift' problem from the 'training distribution shift' problem — they call for different fixes.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Scoping assumptions first
Before going into any architecture detail, nail down the operating parameters:
- Model: decoder-only, 7B–13B for a first deployment (fits on two A100 40 GB with standard quantization); upgrade to 70B if quality gates fail.
- Domain data: ~5B tokens of raw domain text, plus ~5k curated instruction pairs.
- Serving target: ~50 QPS peak, time-to-first-token under 500 ms, streaming at 30–50 tokens/s.
- Risk posture: grounded QA over a document store; abstaining is correct behavior when the answer is not in the sources. A fabricated citation is a worse outcome than "I don't know."
Part 1: Architecture of a decoder-only Transformer
The model is a stack of N identical blocks preceded by a token embedding table and followed by a final norm and a linear projection to vocabulary logits.
Inside each block (pre-norm layout):
h = x + Attn(RMSNorm(x))
y = h + MLP(RMSNorm(h))
Key design choices and why they matter:
- RMSNorm instead of LayerNorm. Drops the re-centering step; slightly faster and equally stable in practice.
- Causal multi-head attention with GQA. Grouped-query attention uses fewer KV heads than Q heads (e.g., 32 Q heads, 8 KV heads). This shrinks the KV cache — the main memory bottleneck at serving time — by 4× without meaningful quality loss.
- RoPE positional encoding. Applied to Q and K rather than embeddings, encodes relative distance, and can be stretched to longer contexts post-hoc with NTK or YaRN scaling.
- SwiGLU MLP. A gated activation that consistently outperforms ReLU on language modeling; hidden dimension is roughly 2.7× the model dimension.
Concrete numbers for a 7B-parameter model:
- d = 4096, L = 32 layers, 32 Q heads, 8 KV heads.
- Approximate parameter count: 12 · L · d² ≈ 6.4B, plus the embedding table.
- KV cache per token in fp16: 2 × L × d_head × n_kv_heads × 2 bytes ≈ 512 KB. At 4k context that's ~2 GB per sequence; GQA cuts it to ~500 MB.
The KV cache size is the number that governs serving decisions: batch size, paged attention, and quantization target.
Part 2: Self-attention and long-range dependencies
The attention operation is:
Output = softmax(QKᵀ / √d_k) · V
Every token's query vector is scored against every prior token's key vector. The output is a content-weighted blend of value vectors.
Why this handles long range better than an RNN:
- O(1) path length. Any two tokens are one matrix multiply apart in a single layer. An RNN propagates information through O(n) sequential hidden states, compressing it at each step — gradients vanish and distant context bleeds away.
- Content-based routing. A pronoun 3,000 tokens from its antecedent can attend to it if their Q/K projections align. The mechanism is blind to distance.
- Parallel computation. All positions are processed simultaneously during training, removing the sequential bottleneck that limits RNN scale.
Honest limitations:
- Compute and memory scale as O(n²) in sequence length. FlashAttention fixes the memory-bandwidth issue but not the raw FLOP count.
- Models poorly extrapolate to contexts longer than their training window unless positional encoding is explicitly extended.
- Empirically, models exhibit "lost in the middle" behavior: information at the start and end of long contexts is used more reliably than information in the middle. Attending to a token is not the same as reasoning over it correctly.
Part 3: Domain adaptation without catastrophic forgetting
Data pipeline first:
- Deduplicate with MinHash at the document level.
- Filter quality (length, language, perplexity under a small reference model).
- Scrub PII.
- Decontaminate: remove any document containing n-grams from your evaluation sets.
- Split into raw domain text (continued pretraining) and instruction pairs (SFT).
Fine-tuning stages:
Continued pretraining — only if the domain has heavy jargon or a distinct style (legal, clinical):
- 1–5B domain tokens, mixed with 10–30% general replay data from a pretraining-like distribution. The replay data is the single most effective anti-forgetting lever in full fine-tuning.
- Peak learning rate ~1e-5, with a short re-warm and cosine decay.
SFT:
- Domain instruction pairs plus a slice (~10–20%) of general instruction data to preserve chat and reasoning behavior.
- 1–3 epochs; watch for overfitting on the small instruction set.
Preference tuning (DPO preferred over PPO for simplicity):
- Include preference pairs that reward citing sources and choosing to abstain over confabulating.
Parameter-efficient fine-tuning (LoRA/QLoRA) as an alternative:
- Base weights stay frozen, so catastrophic forgetting is bounded by construction.
- Each domain gets its own adapter; swap at inference time.
- Preferred when you have multiple domains or limited compute.
Other anti-forgetting tools, roughly in order of practicality:
- Low learning rate + early stopping, gated on a general-capability benchmark.
- KL penalty toward base model logits during SFT.
- Model weight merging (TIES/DARE) to blend domain and base checkpoints post-hoc.
Checkpoint gating — ship nothing that fails either scorecard:
- Domain: task accuracy on held-out pairs, expert rating on a sample.
- General regression: MMLU, GSM8K, instruction-following evals. Set a hard tolerance (e.g., no more than 1 absolute point drop).
Part 4: Hallucination — evaluation, monitoring, mitigation
Taxonomy for a grounded QA system:
- Intrinsic hallucination: the answer contradicts the retrieved source documents.
- Extrinsic hallucination: the answer makes claims not supported by any provided source.
- Citation fabrication: the model invents document IDs or quotes.
Serving architecture:
Client
→ API gateway (auth, rate limit)
→ Retriever: hybrid BM25 + dense, reranker → domain document store
→ Prompt builder: retrieved context + "answer only from sources; cite; abstain if unsure"
→ LLM server: in-flight batching, paged KV, FP8 quantization
→ Verifier: groundedness score, citation validation, policy filters
→ Response: {answer, citations[], confidence, abstained: bool}
→ Async log: prompt, retrieved docs, output, scores, feedback
Offline evaluation before launch:
- Build a golden set of 1–5k domain questions with reference answers, source passages, and a set of intentionally unanswerable questions to test abstention.
- Decompose model outputs into atomic claims. For each claim, check entailment against its cited source using an NLI model or an LLM judge prompted for faithfulness.
- Report: claim-level precision, citation precision/recall, correct-abstention rate.
- Calibrate the LLM judge against expert labels before trusting it (target Cohen's κ > 0.7). A miscalibrated judge produces misleading dashboards.
- Track retrieval recall@k and generation faithfulness separately — you need to know which stage is failing.
Online monitoring:
- Score a sample (or all) of live traffic with a lightweight groundedness model.
- Alert on: groundedness score drop, abstention rate spike (retrieval degraded), abstention rate collapse (model ignoring the abstain instruction), and user thumbs-down rate.
- Log every request with model version, retrieved doc IDs, output, and all scores. This is the dataset for the next improvement cycle.
Operational levers to reduce hallucination rate:
- RAG over weights for facts. Fine-tune for format and reasoning style; retrieve volatile facts. Facts baked into weights go stale and cannot be corrected without retraining.
- Abstention training. Explicit preference pairs rewarding "I don't have enough information" reduce confabulation on out-of-distribution queries.
- Constrained decoding / citation verification. Post-process outputs to strip any citation that does not match a retrieved document ID.
- Retriever quality. A faithfulness problem that traces back to low recall@k is a retrieval problem, not a generation problem. Improve chunking, reranking, or the dense index first.
- Human feedback loop. Route low-confidence or flagged responses to human review; use those corrections as preference data for the next DPO round.
Common mistakes:
- Trusting ROUGE or BLEU as faithfulness proxies — they measure surface overlap, not factual grounding.
- Treating a single groundedness threshold as domain-agnostic; calibrate per use case.
- Optimizing generation after retrieval is broken; always profile both stages independently.