Fine-tuning, evals, safety and shipping
Part 6: Evals and Shipping
LoRA, evals, guardrails, observability, cost, deployment, GenAI system design.
On this page (29 sections)
- 6.1 Customising the model
- 6.2 Evaluation
- 6.3 Safety and operations
- 6.4 Shipping to production
- 6.1 Customising the model — detailed notes
- 1. Prompting vs RAG vs fine-tuning: decision guide
- 2. Fine-tuning basics: full vs PEFT
- 3. LoRA and QLoRA
- 4. Preparing fine-tuning datasets
- 5. Distillation and synthetic data
- 6.2 Evaluation — detailed notes
- 6. Preference tuning: RLHF and DPO
- 7. LLM evaluation: golden datasets and metrics
- 8. LLM-as-a-judge
- 9. Benchmarks: MMLU, SWE-bench and limits
- 10. Guardrails: input/output filters and moderation
- 6.3 Safety and operations — detailed notes
- 11. AI safety, bias, fairness, privacy and PII
- 12. Responsible AI and regulation: EU AI Act and India DPDP
- 13. Observability and tracing: LangSmith, Langfuse and OpenTelemetry
- 14. Cost control: budgets, caching, routing and batch APIs
- 15. Latency: streaming, smaller models and parallel calls
- 6.4 Shipping to production — detailed notes
- 16. Deploying LLM apps: serverless, containers and queues
- 17. Serving open models: vLLM, TGI and GPUs
- 18. Rate limits, retries and fallbacks
- 19. Testing and CI for LLM apps
- 20. GenAI system design interviews
- Part 6 cheat sheet — interview answers
Like I'm 5: Cooking a dish once is easy. Serving it to 10,000 guests every day, tasting it, keeping it safe and not going bankrupt is the real job. This part is that job.
6.1 Customising the model
Topics to cover, in this order:
- Prompting vs RAG vs fine-tuning: decision guide
- Fine-tuning basics: full vs parameter-efficient (PEFT)
- LoRA and QLoRA
- Preparing datasets for fine-tuning
- Distillation and synthetic data
6.2 Evaluation
Topics to cover, in this order:
- Preference tuning: RLHF and DPO at usage level
- LLM evaluation basics: golden datasets and metrics
- LLM-as-a-judge
- Benchmarks (MMLU, SWE-bench and others) and their limits
- Guardrails: input and output filters, moderation
6.3 Safety and operations
Topics to cover, in this order:
- AI safety, bias, fairness, privacy and PII
- Responsible AI and regulation basics (EU AI Act, India DPDP)
- Observability and tracing (LangSmith, Langfuse, OpenTelemetry)
- Cost control: token budgets, caching, model routing, batch APIs
- Latency: streaming, smaller models, parallel calls
6.4 Shipping to production
Topics to cover, in this order:
- Deploying LLM apps: serverless, containers, queues
- Serving open models: vLLM, TGI and GPUs
- Rate limits, retries and fallbacks
- Testing and CI for LLM apps
- GenAI system design interviews: chatbot, document Q&A, support agent
6.1 Customising the model — detailed notes
1. Prompting vs RAG vs fine-tuning: decision guide
LIKE I'M 5
Instructions tell a student how to work. A book gives facts. Training changes how the student performs.
EXPLAINED SIMPLY
- Prompting changes instructions and context at request time.
- RAG retrieves external knowledge for the current request.
- Fine-tuning updates model weights using a training dataset.
- Use prompting for format and behaviour changes; RAG for fresh/private knowledge; fine-tuning for repeated patterns or specialised behaviour when evidence supports it.
- Compare build cost, data needs, quality, update speed, latency and maintenance.
- These methods can be combined.
COMPARE WITH LOOKALIKES
| Method | Changes | Knowledge freshness |
|---|---|---|
| Prompting | Input instructions | Depends on supplied context |
| RAG | Retrieved context | Can be updated in index |
| Fine-tuning | Model weights | Requires further training to update |
INTERVIEW LENS
Choose the least expensive method that meets quality requirements; do not fine-tune to store changing facts.
TRAPS
Fine-tuning does not guarantee factual recall. RAG does not teach a new style permanently.
ONE-LINE RECAP
Prompt for instructions, retrieve for knowledge, fine-tune for learned behaviour.
2. Fine-tuning basics: full vs PEFT
LIKE I'M 5
Full fine-tuning changes many parts of the student. Parameter-efficient tuning adds a small adjustment instead.
EXPLAINED SIMPLY
- Fine-tuning continues training a pretrained model on a task-specific dataset.
- Full fine-tuning updates most or all model parameters and can require substantial compute and storage.
- Parameter-Efficient Fine-Tuning (PEFT) updates a smaller set of parameters or added modules.
- PEFT can reduce memory and make adapters easier to store and swap.
- Use a clean training/validation/test split and compare against the base model.
- Track data provenance, licence, privacy and model compatibility.
INTERVIEW LENS
Explain full parameter updates versus small trainable adapters and the compute/quality trade-off.
TRAPS
More training data is not always better. Fine-tuning can cause forgetting or overfit.
ONE-LINE RECAP
Fine-tuning specialises a pretrained model; PEFT reduces the number of trainable parameters.
3. LoRA and QLoRA
LIKE I'M 5
Instead of repainting a whole wall, add a small removable layer that changes the result.
EXPLAINED SIMPLY
- LoRA freezes original weights and learns low-rank update matrices for selected layers.
- The update is represented with smaller matrices, reducing trainable parameters.
- QLoRA combines quantised base weights with LoRA adapters to reduce memory needs during fine-tuning.
- Adapter rank and target modules affect capacity, memory and quality.
- Merge or load adapters according to the runtime and deployment needs.
- Evaluate against the base model and inspect training stability.
INTERVIEW LENS
Explain frozen base weights, low-rank updates and QLoRA's quantised base model.
TRAPS
LoRA is not merely pruning. QLoRA does not mean the final model must always run quantised.
ONE-LINE RECAP
LoRA learns small weight updates; QLoRA reduces training memory further.
4. Preparing fine-tuning datasets
LIKE I'M 5
A student learns from examples. If the examples contain wrong answers, the student learns the wrong lesson.
EXPLAINED SIMPLY
- Define the target behaviour and data format before collecting examples.
- Remove duplicates, corrupted rows, irrelevant samples and sensitive data without permission.
- Ensure labels are consistent and representative of real usage.
- Split train, validation and test data to prevent leakage.
- Include edge cases and difficult examples, not only easy ones.
- Track dataset version, source, licence, transformations and reviewer.
- Evaluate the tuned model on held-out real-world tasks.
INTERVIEW LENS
Describe curation, deduplication, privacy, label quality, split strategy and held-out evaluation.
TRAPS
Data leakage inflates results. Synthetic examples can repeat the same bias.
ONE-LINE RECAP
Dataset quality and provenance often matter more than raw dataset size.
5. Distillation and synthetic data
LIKE I'M 5
A teacher creates worked examples so a smaller student can learn the same kind of task.
EXPLAINED SIMPLY
- Distillation transfers behaviour from a teacher model to a student.
- Synthetic data is generated rather than directly collected from ordinary real-world examples.
- Synthetic examples can expand coverage and create rare edge cases.
- Teacher errors and biases can be copied into student training data.
- Filter, deduplicate and validate generated examples with rules, tools or human review.
- Compare student performance against the teacher and baseline on independent data.
INTERVIEW LENS
Explain teacher generation, filtering, student training and independent evaluation.
TRAPS
Synthetic volume does not guarantee diversity. A model can teach its own mistakes.
ONE-LINE RECAP
Distillation and synthetic data reduce data or model costs, but need quality controls.
6.2 Evaluation — detailed notes
6. Preference tuning: RLHF and DPO
LIKE I'M 5
People compare two answers and say which is more helpful. The model is trained to prefer answers people choose.
EXPLAINED SIMPLY
- RLHF uses human preference feedback to shape model behaviour, often through a reward model and reinforcement-learning optimisation.
- DPO trains directly from preference pairs using a preference-optimisation objective, without a separate online RL loop in the common formulation.
- Preference data contains chosen and rejected responses.
- Quality depends on clear rubrics, diverse raters and careful sampling.
- Preference tuning can improve helpfulness or style but may create reward hacking or reduce diversity.
- Evaluate safety and task performance after tuning.
COMPARE WITH LOOKALIKES
| RLHF | DPO |
|---|---|
| Often trains reward model then optimises policy | Direct preference objective |
| More moving parts | Simpler training pipeline |
| Can involve online RL | Usually offline preference pairs |
INTERVIEW LENS
Explain how preference pairs shape model behaviour and compare the optimisation pipelines.
TRAPS
Human preference is not the same as factual truth. Poor raters create poor alignment.
ONE-LINE RECAP
RLHF and DPO use preference feedback to tune model behaviour.
7. LLM evaluation: golden datasets and metrics
LIKE I'M 5
Use the same exam paper every time you change the teaching method.
EXPLAINED SIMPLY
- A golden dataset contains representative inputs and expected outcomes or grading rubrics.
- Metrics depend on the task: exact match, accuracy, F1, schema validity, factuality, relevance or human preference.
- Evaluate normal cases, edge cases, adversarial prompts and no-answer cases.
- Separate model quality from retrieval, tools and application logic.
- Track regressions across prompt, model and data versions.
- Use human review for subjective or high-impact outputs.
INTERVIEW LENS
Describe task-specific metrics, fixed datasets, holdout sets and regression evaluation.
TRAPS
One aggregate score can hide critical failure categories. Benchmarks can be overfit.
ONE-LINE RECAP
Evaluation makes model changes measurable and comparable.
8. LLM-as-a-judge
LIKE I'M 5
A second student grades the first student's answer using a marking guide.
EXPLAINED SIMPLY
- An LLM judge scores or compares generated answers against a rubric.
- It can scale evaluation for relevance, completeness, style and groundedness.
- Use explicit criteria, calibrated examples and blinded comparisons where possible.
- Judge models can prefer longer answers, familiar phrasing or their own provider's style.
- Compare judge decisions with human ratings and report agreement.
- Do not use a judge as the sole evaluator for consequential decisions.
INTERVIEW LENS
Explain rubric design, calibration, bias checks and human agreement measurement.
TRAPS
A judge can hallucinate a justification. Self-evaluation is not independent truth.
ONE-LINE RECAP
LLM judges scale review, but must be calibrated against humans and objective checks.
9. Benchmarks: MMLU, SWE-bench and limits
LIKE I'M 5
A test score tells you how a student did on that paper, not how they will perform at every job.
EXPLAINED SIMPLY
- Benchmarks provide standardised tasks for comparing systems.
- MMLU evaluates knowledge across multiple subjects. SWE-bench evaluates software-engineering issue resolution in repository settings.
- Benchmark versions, contamination risk, scoring methods and task setup affect results.
- Leaderboards can hide variance, tool differences and real-world constraints.
- Use benchmarks as one signal alongside your own workload evaluations.
- Check the exact benchmark version and methodology before citing scores.
INTERVIEW LENS
Explain what a benchmark measures, what it omits and why task-specific evaluation is necessary.
TRAPS
Scores from different setups are not directly comparable. Public benchmark performance can be overfit.
ONE-LINE RECAP
Benchmarks are useful evidence, not universal proof of capability.
10. Guardrails: input/output filters and moderation
LIKE I'M 5
A playground has rules before children enter and checks before they leave.
EXPLAINED SIMPLY
- Input guardrails inspect user requests for abuse, unsafe content, secrets or policy violations.
- Output guardrails inspect model responses before delivery or action.
- Moderation models and deterministic rules can work together.
- Guardrails may block, redact, transform, route to human review or allow.
- Design for false positives and false negatives; provide safe alternatives where appropriate.
- Enforce permissions and business rules in code, not only moderation prompts.
INTERVIEW LENS
Describe layered input, model, output and tool-action checks with logging and review.
TRAPS
A content filter is not an authorisation system. Filters can miss indirect prompt injection.
ONE-LINE RECAP
Guardrails reduce risk at multiple points but cannot guarantee safety alone.
6.3 Safety and operations — detailed notes
11. AI safety, bias, fairness, privacy and PII
LIKE I'M 5
A fair teacher should not judge students using irrelevant personal details or share their private notebooks.
EXPLAINED SIMPLY
- Safety includes preventing harmful outputs, unsafe actions, privacy leaks and misuse.
- Bias can enter through training data, labels, prompts, retrieval and evaluation.
- Fairness requires defining which groups and outcomes matter for the specific application.
- PII includes information that identifies or can help identify a person.
- Minimise collection, redact where possible, restrict access and define retention.
- Test demographic and edge-case performance with lawful, appropriate data.
- Provide escalation and human review for consequential decisions.
INTERVIEW LENS
Discuss threat modelling, data minimisation, subgroup evaluation, access control and human oversight.
TRAPS
No model is automatically unbiased. Removing names alone may not remove identifying information.
ONE-LINE RECAP
Safety and fairness require data controls, evaluation and accountable human processes.
12. Responsible AI and regulation: EU AI Act and India DPDP
LIKE I'M 5
Different places have rules for how organisations collect information and use powerful tools.
EXPLAINED SIMPLY
- Responsible AI covers transparency, accountability, privacy, safety, fairness and human oversight.
- The EU AI Act uses a risk-based regulatory framework with obligations that depend on system role and risk category.
- India's Digital Personal Data Protection (DPDP) framework governs processing of digital personal data and includes duties for relevant data fiduciaries and rights for individuals.
- Applicability, commencement dates, rules and obligations can change. Check official legal sources for the current position.
- Organisations should map data flows, purposes, legal basis/consent where applicable, processors, retention, security and user requests.
- This is an engineering overview, not legal advice; involve qualified counsel for compliance decisions.
INTERVIEW LENS
Explain risk-based governance and privacy-by-design, then distinguish technical controls from legal interpretation.
TRAPS
Do not assume one regulation applies identically to every product or country. Avoid outdated timelines.
ONE-LINE RECAP
Build privacy and accountability into the system and verify current legal obligations.
13. Observability and tracing: LangSmith, Langfuse and OpenTelemetry
LIKE I'M 5
A delivery company tracks each stop so it knows where a parcel got delayed.
EXPLAINED SIMPLY
- Observability helps explain what happened inside a running application.
- A trace groups related operations for one request. Spans represent individual steps such as retrieval, model call and tool execution.
- Record model ID, prompt version, token usage, latency, errors and safe tool metadata.
- LangSmith and Langfuse provide LLM-oriented tracing/evaluation workflows; OpenTelemetry is a broader observability standard.
- Redact sensitive content and set retention policies.
- Correlate traces with user-visible request IDs without exposing secrets.
INTERVIEW LENS
Explain traces, spans, metrics, logs and privacy-aware instrumentation.
TRAPS
Logging every prompt can leak PII. Metrics without trace context make debugging difficult.
ONE-LINE RECAP
Trace each stage so failures, latency and cost can be diagnosed.
14. Cost control: budgets, caching, routing and batch APIs
LIKE I'M 5
A shop saves money by buying in bulk, reusing prepared ingredients and sending simple jobs to a cheaper worker.
EXPLAINED SIMPLY
- Cost depends on input/output tokens, model tier, tools, retries, concurrency and infrastructure.
- Set per-request and per-user budgets.
- Cache repeated safe results with permission-aware keys and freshness rules.
- Route simple requests to cheaper models and escalate difficult cases.
- Batch offline workloads when the provider supports it and latency is not critical.
- Limit context and output length. Monitor cost per successful task, not only cost per call.
- Pricing and batch discounts change; verify current provider pricing.
INTERVIEW LENS
Describe budgets, caching, routing, batching and cost per successful outcome.
TRAPS
Retries and long prompts can silently multiply spend. Caching can serve stale or cross-user data.
ONE-LINE RECAP
Control cost with budgets, efficient routing, caching and workload-aware batching.
15. Latency: streaming, smaller models and parallel calls
LIKE I'M 5
A restaurant can bring the first dish quickly while other dishes are still cooking.
EXPLAINED SIMPLY
- Measure queue time, time to first token, inter-token delay and total completion time.
- Streaming improves perceived responsiveness by showing partial output.
- Smaller models may reduce inference latency when they meet quality requirements.
- Parallel calls reduce wall-clock time for independent work but increase concurrency and cost.
- Reduce prompt size, unnecessary tools and serial dependencies.
- Set timeouts and fallbacks; track p50 and p95 rather than averages only.
INTERVIEW LENS
Explain perceived versus end-to-end latency and the trade-offs of streaming, parallelism and model choice.
TRAPS
Streaming does not make total computation faster. Parallel calls can overload rate limits.
ONE-LINE RECAP
Optimise the slowest stages and measure user-perceived as well as total latency.
6.4 Shipping to production — detailed notes
16. Deploying LLM apps: serverless, containers and queues
LIKE I'M 5
A small request can go to a quick counter. A long job gets a ticket and runs in the kitchen.
EXPLAINED SIMPLY
- Serverless functions suit short event-driven requests with platform-managed scaling.
- Containers provide a consistent runtime and more control over dependencies.
- Queues decouple slow or bursty work from user requests.
- Use asynchronous jobs for document ingestion, batch processing and long-running tasks.
- Add authentication, rate limits, timeouts, retries, secrets management and health checks.
- Stream short interactive responses when useful; persist long-running job state.
- Design for provider outages and graceful degradation.
INTERVIEW LENS
Choose compute based on duration, traffic shape, state, deployment control and operational requirements.
TRAPS
Serverless limits can affect long tasks. Queues need deduplication and dead-letter handling.
ONE-LINE RECAP
Match deployment architecture to request duration, traffic and reliability needs.
17. Serving open models: vLLM, TGI and GPUs
LIKE I'M 5
A busy kitchen needs equipment that serves many customers without wasting space.
EXPLAINED SIMPLY
- Self-hosting means operating model weights and inference infrastructure.
- vLLM is an inference/serving engine known for efficient batching and memory management features.
- Text Generation Inference (TGI) is a serving toolkit from Hugging Face; project status and recommended usage should be checked in current docs.
- GPUs accelerate matrix operations; VRAM limits model size, context and concurrency.
- Quantisation, tensor parallelism and batching affect memory and throughput.
- Monitor GPU utilisation, memory, queue time, tokens per second and request failures.
- Compare infrastructure cost against managed APIs at realistic utilisation.
INTERVIEW LENS
Explain model loading, GPU memory, batching, quantisation and serving throughput.
TRAPS
A model fitting in VRAM does not guarantee acceptable concurrency. Idle GPUs are expensive.
ONE-LINE RECAP
Open-model serving requires capacity planning, runtime tuning and GPU operations.
18. Rate limits, retries and fallbacks
LIKE I'M 5
If one counter is busy, wait politely or use another counter—but do not submit the same payment twice.
EXPLAINED SIMPLY
- Providers enforce request and token limits over time.
- On transient failures, use bounded exponential backoff with jitter and respect retry guidance.
- Do not retry invalid requests, authentication failures or policy refusals blindly.
- Use idempotency keys for side-effecting operations where supported.
- Fallbacks may use another model, a cached answer, a queue or a graceful error.
- Keep fallback behaviour compatible with quality, privacy and data policies.
- Track retry counts and fallback rates.
INTERVIEW LENS
Explain retry classification, backoff, idempotency, circuit breakers and fallback policy.
TRAPS
Retry storms worsen outages. A fallback model may not support the same tools or schema.
ONE-LINE RECAP
Retry only recoverable failures and design safe fallbacks.
19. Testing and CI for LLM apps
LIKE I'M 5
Before opening a shop, test the door, payment machine, menu and food with the same checklist each time.
EXPLAINED SIMPLY
- Unit-test deterministic code: parsing, permissions, routing, schema validation and tool handlers.
- Integration-test provider calls, retrieval and external services with controlled fixtures.
- Use golden datasets for model behaviour and regression tests.
- Add adversarial tests for prompt injection, data leakage and unsafe tool use.
- Track model, prompt, dataset and index versions with each test run.
- Avoid brittle exact-text assertions when output is naturally variable; test schemas and task outcomes.
- Block releases on critical safety or quality regressions.
INTERVIEW LENS
Describe test pyramid, deterministic mocks, golden evaluations, adversarial tests and release gates.
TRAPS
A green unit-test suite does not prove model quality. Live provider tests can be flaky and costly.
ONE-LINE RECAP
Test code deterministically and model behaviour with repeatable evaluations.
20. GenAI system design interviews
LIKE I'M 5
Design a whole restaurant, not just one recipe: orders, kitchen, payments, delivery and safety all matter.
EXPLAINED SIMPLY
- Start by clarifying users, goals, scale, latency, quality, privacy and failure requirements.
- Draw client, backend, model provider, retrieval store, database, tools, queues and observability.
- Define data ingestion and online request paths separately.
- Explain model choice, prompt structure, retrieval, tools and output validation.
- Add auth, tenant isolation, rate limits, budgets, caching, retries and human review.
- Identify failure modes and graceful fallbacks.
- Estimate traffic, tokens, concurrency, storage and cost with explicit assumptions.
- Discuss evaluation and rollout before claiming the system is production-ready.
INTERVIEW LENS
Use a repeatable sequence: requirements → architecture → data flow → model/RAG/tools → security → scale/cost → evaluation → failure handling.
TRAPS
Do not jump straight to a vector database. Do not ignore privacy, cost or operations.
ONE-LINE RECAP
A production GenAI design is a complete software system with model-specific risks.
Part 6 cheat sheet — interview answers
- Prompting vs RAG vs fine-tuning → Instructions vs retrieved knowledge vs changed weights.
- PEFT → Train a small subset of parameters or adapters.
- LoRA → Low-rank weight updates; QLoRA combines this with quantised base weights.
- Dataset quality → Clean, representative, deduplicated, licensed and split without leakage.
- Distillation → Train a student to reproduce teacher behaviour.
- RLHF vs DPO → Preference-based policy optimisation with different training pipelines.
- Golden set → Fixed representative cases for regression evaluation.
- LLM judge → Scalable rubric-based evaluator calibrated against human ratings.
- Guardrails → Input, output and action checks; not a replacement for authorisation.
- Safety → Threat model, privacy, fairness, oversight and accountable controls.
- Regulation → Map data flows and verify current legal applicability with counsel.
- Tracing → Correlate model, retrieval and tool spans with safe metadata.
- Cost control → Budgets, caching, routing, batching and context limits.
- Reliability → Bounded retries, idempotency, fallbacks and observability.
- System design → Requirements, architecture, data flow, security, scale, cost and evaluation.