# Fine-Tuning Pipeline

**Also known as:** Model customization · SFT pipeline  
**Category:** AI Patterns (Model in the loop)  
**Complexity:** 4/5  
**Guide:** https://layra4.dev/architectures/ai/fine-tuning-pipeline

*Try the prompt first. Fine-tune when the prompt cannot carry the behaviour.*

Fine-tuning trains an existing model further on your own examples, so a behaviour you used to describe in the prompt moves into the weights. It is good at format, tone and narrow, repeated tasks. It is poor at teaching facts: the model may learn to sound like your documents without reliably recalling what they say. Facts that change belong in retrieval.

So the first step is a question, not a training run. Would a better prompt, a few worked examples or RAG be cheaper and good enough? If you still need a tune, treat it as a pipeline you will rerun, not a one-off experiment: curated data, a frozen eval set, a training run, a gate against the prompt you would ship anyway, and a versioned rollout you can undo.

> **In one sentence.** A fine-tune is only as good as its eval set and its baseline. Without both, you cannot tell a better model from a different one.

## Origin (2021)

Pretrain once, fine-tune per task became standard with ULMFiT and BERT (2018). InstructGPT (Ouyang et al., 2022) showed tuning on demonstrations makes a model follow instructions. LoRA (Hu et al., 2021) made tuning cheap enough to repeat.

## The stages

### Data curation

Collecting and cleaning the examples the model will learn from: real inputs paired with the outputs you want. Quality beats volume. A few hundred to a few thousand reviewed examples often beat a large noisy dump, because the model learns the mistakes too.

- Write examples in the exact format used in production
- Remove duplicates, personal data and outputs nobody would approve
- Cover the hard cases, not only the common ones

> Support replies from logs, filtered to tickets the customer rated well and an agent reviewed.

### The held-out eval set

Cases the model never trains on, used to judge every candidate. Build it first and freeze it. Built after the training set, it gets the leftovers, and the best examples quietly end up in training.

- Split by customer, document or time, not by random row
- Remove near-duplicates of training examples, not only exact ones
- Add general-ability and safety cases to catch what tuning breaks

### Training (Full vs parameter-efficient)

Full fine-tuning updates every weight: the most capacity, the most memory, and a full model copy per variant. Parameter-efficient methods such as LoRA freeze the base model and train small low-rank adapter matrices beside it, a tiny fraction of the parameters.

- LoRA adapters are small files; one base model can serve many of them
- QLoRA trains adapters on a quantized base to fit smaller GPUs
- Supervised pairs teach the task; preference pairs (RLHF, DPO) teach which answer is better

### The gate

The comparison that decides promotion. The candidate must beat two baselines on the frozen eval set: the base model with your best prompt, and the model in production now. Beating the raw base model proves nothing; a good prompt often does the same.

- Require a margin larger than run-to-run noise
- List the cases that newly fail, not only the average

### Versioning and rollout

A tuned model is the product of a base model version, a dataset, a config and the training code. Record all four, so any checkpoint can be rebuilt or explained. Roll out behind an alias, to a slice of traffic first.

- Rollback means pointing the alias at the previous version
- Hosted base models get retired; the pipeline makes retuning a rerun

## Design rules

### Beat a strong prompt before you train

Write the best prompt you can, with few-shot examples and retrieval if they help, and score it on the eval set. That score is the bar. Often it is already good enough, and the project ends here, cheaply.

### Freeze the eval set before the training set

Hold out cases first, split by source or time so related examples do not land on both sides, and never train on them. A tune scored on cases it has seen measures memory, not skill.

### Train in the format you serve

Use the same chat template, system prompt and tool schemas in training as in production. A model tuned without the system prompt and served with one is a different input distribution, and it fails quietly.

### Make every model rebuildable and reversible

Pin the base model version, hash the dataset, store the config and seed with the checkpoint. Keep the previous version deployable until the new one has run on real traffic.

## Examples

### A run record and its promotion gate

```typescript
// One run = one immutable record. Anything missing here cannot be reproduced.
const run = {
  base: "open-model-8b@2026-09",              // pinned: a moving alias breaks reruns
  method: { kind: "lora", rank: 16, alpha: 32 },
  trainSet: "datasets/support-replies@sha256:9f2c…",
  evalSet: "evals/support-replies@v3",         // frozen before training data existed
  epochs: 3, learningRate: 2e-4, seed: 7,
};

const candidate = await train(run);

// Beat the prompt you would ship anyway, and the model in production, not the raw base.
const [tuned, prompted, live] = await Promise.all([
  evaluate(candidate, run.evalSet),
  evaluate(baseWithBestPrompt, run.evalSet),
  evaluate(production, run.evalSet),
]);

const bar = Math.max(prompted.score, live.score) + MARGIN;   // above run-to-run noise
const newFailures = tuned.failed.filter((id) => live.passed.includes(id));

if (tuned.score < bar || newFailures.length > ALLOWED_NEW_FAILURES) {
  return reject(candidate, { tuned, prompted, live, newFailures });
}

await registry.register(candidate, { run, scores: { tuned, prompted, live } });
await rollout.canary(candidate, { traffic: 0.05 });   // rollback = repoint the alias
```

The run is an immutable record, so a checkpoint can be rebuilt. The gate compares against the prompt you would ship anyway and the live model, and rejects new failures even when the average rises.

## When to use

- A prompt that works is too long, slow or costly to send on every call
- You need a format, tone or narrow skill that prompting cannot hold steady
- A small, cheap model must match a large one on one narrow task

## When not to use

- The model needs facts that change: use retrieval instead
- A better prompt or a few worked examples has not been tried yet
- You cannot yet say what a good answer looks like: write the eval set first

## Benefits

- Shorter prompts, because the behaviour lives in the weights
- More consistent format and tone across many calls
- A smaller model can take over a narrow task at a lower price

## Costs

- A data pipeline to run: collection, review, privacy and refresh
- A model to own: hosting or a premium per token, and retuning when the base is retired
- Narrowing: a tune can lose general ability and safety behaviour it once had

## Pitfalls

- Tuning to teach facts, then getting confident answers that are wrong.
- Eval cases leaking into training, so the score measures memory.
- Training without the production system prompt or template.
- Comparing only against the raw base model, never against a good prompt.

## Related patterns

- [Retrieval-Augmented Generation](https://layra4.dev/architectures/ai/rag) — the usual answer when the gap is knowledge, not behaviour
- [Few-Shot Examples](https://layra4.dev/architectures/prompting/few-shot) — the cheap baseline: examples in the prompt instead of the weights
- [Evaluation Harness](https://layra4.dev/architectures/ai/eval-harness) — the frozen cases every checkpoint is gated on
- [Versioned Prompt](https://layra4.dev/architectures/prompting/prompt-versioning) — the same discipline for the prompt the tune must beat

## Further reading

- *LoRA: Low-Rank Adaptation of Large Language Models* — Hu et al. (2021) — Freeze the base, train small adapters: why tuning got cheap.
- *Training Language Models to Follow Instructions with Human Feedback* — Ouyang et al. (2022) — InstructGPT: supervised tuning, then preference tuning, on a small curated set.
- *AI Engineering* — Chip Huyen (2025) — A clear chapter on when to fine-tune and when prompting or RAG is enough.
