CHAPTER 33

Fine-Tuning, Evaluation and Safety

Choosing how to adapt a model, proving it works, and keeping it safe

Source: PDF pp. 88–90

Core PDF content

PDF page 88Prompting, RAG or fine-tuning? p. 88

Combine freely (RAG + fine-tuned model is common). Whatever you choose, measure it with the same eval set before and after.

Figure 60. Start with the cheapest intervention; escalate only when evals show a gap that the cheaper option cannot close. · PDF p. 88

Fine-tuning methods p. 88

MethodWhat changesNotes
Supervised fine-tuning (SFT)All weights, trained on (prompt, ideal response) pairsMost reliable way to teach format/style/behaviour. Quality beats quantity: 1k-50k curated examples often suffice
LoRA / QLoRA (PEFT)Train small low-rank adapter matrices (W + BA, rank 8-64) on a frozen base; QLoRA also quantises the base to 4-bitFine-tune big models on one or few GPUs; adapters are MBs, swappable per tenant (multi-LoRA serving)
Preference optimisationRLHF (reward model + PPO) or simpler DPO / IPO / KTO on (chosen, rejected) pairsShapes tone, helpfulness and refusals; DPO needs no separate reward model
RL with verifiable rewardsReinforcement learning where correctness is checkable (math, code, tests)Builds reasoning ability; needs reliable graders
DistillationTrain a small student on a large teacher's outputsCheaper, lower-latency model for a narrow task
Continued pre-trainingFurther next-token training on domain corporaHeavy; only for deep domain shift (law, biomedical, a language)
  • Data pipeline: collect real prompts, write or generate ideal responses (strong-model synthetic data reviewed by humans), deduplicate, filter for quality and safety, apply the model's chat template, hold out validation and test sets that mirror production.
  • Risks: catastrophic forgetting (mix in general data, use low learning rates or LoRA), overfitting to quirks, baking in outdated knowledge (use RAG for facts, fine-tuning for behaviour), and leaking private data into weights.
  • Operations: track datasets and runs, evaluate against the base model and prompting baseline, version adapters, canary the new model, and keep a rollback.
Figure 61. Evaluation-driven development: every failure becomes a test; every change is gated by the suite. · PDF p. 89
TechniqueGood forWatch out
Deterministic checksJSON validity, schema, regex, required citations, tool-call correctness, unit tests on generated codeNarrow, but cheap and exact: use wherever possible
Reference-based metrics (exactExtraction, classification, short answersPoor for open-ended text

match, F1, BLEU/ROUGE, embedding similarity)

LLM-as-judgeRubric scoring (helpfulness, faithfulness, tone), pairwise comparison of outputsBiases: position, verbosity, self-preference. Use clear rubrics, pairwise + swapped order, reasoning-before-score, and calibrate against human labels
Human evaluationGround truth for subjective quality, safety, edge casesExpensive, slow: sample smartly, measure inter-rater agreement
Public benchmarks (MMLU, etc.)Coarse model selectionContaminated and not your task; build your own golden set (100-500 real cases)
Online metricsTask completion, edits, retention, escalation rate, cost per taskLagging and noisy; combine with offline suites

Safety, security and guardrails p. 89

Threat (see OWASP Top 10 for LLM apps)Mitigation
Prompt injection (direct, or indirect via documents, web pages, emails, tool results)Separate instructions from data; treat external content as untrusted; privilege separation; least-privilege tools; human confirmation for sensitive actions; detect and quarantine suspicious content. No prompt alone is a sufficient defence
Jailbreaks and policy evasionLayered input/output classifiers, system-prompt hardening, refusal training, red-team suites, monitoring and rapid patching
Insecure output handlingNever execute or render model output unsanitised: escape HTML (XSS), parameterise SQL, validate JSON against schema, sandbox code
Excessive agencyMinimal tool set and scopes, allow-lists, budgets, approval flows, kill switches
Sensitive-data disclosurePII redaction, access control at retrieval, tenant isolation, output scanning for secrets, no secrets in prompts
Data and model poisoning, supply chainVet datasets, models and MCP servers; signed artifacts; monitor for anomalies
Denial of wallet / model DoSPer-user token budgets, max input/output sizes, rate limits, anomaly alerts, caching
HallucinationGround with RAG and citations, constrain outputs, let the model abstain, verify (retrieval check, tool call, second pass), calibrate UI to show uncertainty, human review in high stakes
Bias, fairness, harmful contentSlice-based evals, moderation models, policy-aligned refusals, diverse red-teaming, transparency and appeal paths
  • Defence in depth: assume any single layer fails. Combine input filters, hardened prompts, constrained tools, output validation, monitoring and human oversight.
  • Governance: model/data cards, risk assessment per use case, logging for audit, incident response, and compliance with regulations (for example the EU AI Act classifies systems by risk level and imposes obligations accordingly) and privacy laws (GDPR, CCPA).

Review questions for this chapter have not been written and reviewed yet. The chapter text above is the full source content.

Try it

References

System Design & AI System Design: The Complete Guide — 2026 Edition, pp. 88–90; figures 60, 61.

Tip: use ← and → keys to move between chapters.