Fine-tuning, training infrastructure, and model optimisation

Prompting and retrieval are usually the first tools. Sometimes you need to change the model itself. This guide explains when fine-tuning is worth it, the main methods, the infrastructure around training, and the techniques that make a trained model smaller and faster.

Fine-tuning in 60 seconds

  • Try cheaper tools first: better prompts, examples in the prompt, and retrieval solve most problems without training.
  • Fine-tune for behaviour, not facts. It teaches style, format, and task skill. Use retrieval for facts that change.
  • Methods: full fine-tuning updates all weights; adapter methods such as LoRA update a small add-on; preference tuning teaches the model which of two answers is better.
  • Data quality decides the outcome. A few thousand clean, consistent examples beat a large noisy set.
  • Operate it like software: version the data, track experiments, keep a model registry, evaluate before release, and keep a way to roll back.

Should you fine-tune at all?

Training a model is the most expensive and slowest way to change its behaviour, and it creates a model you must now maintain. Use it only when cheaper tools have been tried and measured. A useful order is: write a clear prompt, add a few worked examples to the prompt, add retrieval for the facts the model needs, and only then consider changing the weights.

GoalBest first toolWhyFine-tune when
Answer from your documentsRetrieval (RAG)Facts change; retrieval is current and citableAlmost never for facts alone
Follow a format or stylePrompt with examples, structured outputCheap and instant to changeThe prompt becomes very long, or the style is hard to describe
Do a narrow task reliably and cheaplyA larger model with a good promptFast to buildA smaller tuned model can match quality at far lower cost at your volume
Learn a domain's vocabulary or conventionsRetrieval plus examplesEasier to updateExamples are plentiful and the domain is stable
Match human preferencesPrompt guidelines and a reviewer stepNo training neededYou have many comparisons of better and worse answers
Run on a small deviceA small base modelAlready smallYou need to compress a larger model's behaviour into it

Fine-tuning methods

Full fine-tuning

Every weight in the model is updated. It gives the most flexibility and the highest memory and compute cost, because the training process stores not only the weights but also gradients and optimiser state, which together can take several times the model's size. It also produces a whole new copy of the model for each task. It is mostly used by teams with substantial training hardware.

Adapter methods (LoRA and relatives)

Instead of changing the big weight matrices, an adapter method keeps them frozen and trains a small set of extra weights alongside them. LoRA, short for low-rank adaptation, represents the change to a large matrix as the product of two much smaller matrices, so it trains a tiny fraction of the numbers. The result is a small adapter file, often a few percent of the model's size or less, that can be loaded on top of the shared base model. Training needs far less memory, and many adapters, one per customer or task, can share one base model at serving time.

A variant combines the idea with quantisation: the frozen base model is stored in low precision to save memory while the adapter is trained in higher precision. It lets a large model be tuned on a single high-memory GPU, at some cost in quality and training speed that you should measure.

An adapter-style training configuration (illustrative; names vary by library) (python)
# Illustrative: the shape of a configuration, not a specific library's API.

config = {
    'base_model': 'base-model-7b',
    'method': 'lora',
    'lora': {'rank': 16, 'alpha': 32, 'dropout': 0.05,
             'target_modules': ['attention_query', 'attention_value']},
    'training': {'learning_rate': 2e-4, 'epochs': 3, 'batch_size': 16,
                 'max_sequence_tokens': 2048, 'warmup_ratio': 0.03},
    'data': {'train': 'data/train.jsonl', 'validation': 'data/validation.jsonl'},
    'seed': 42,   # record the seed so a run can be reproduced
}

Instruction tuning

Instruction tuning trains on examples of an instruction and a good response, so the model learns to follow requests in the format you want. It is the most common form of fine-tuning for products, and the examples can be written by experts, drawn from real approved interactions, or generated by a stronger model and then reviewed.

Training examples as JSON lines (illustrative) (json)
{"messages": [{"role": "system", "content": "You write short, polite support replies."}, {"role": "user", "content": "My invoice shows two charges."}, {"role": "assistant", "content": "I am sorry for the confusion. I can see one charge and one temporary authorisation, which drops off in three to five days. If it does not, reply here and I will look into it."}]}
{"messages": [{"role": "system", "content": "You write short, polite support replies."}, {"role": "user", "content": "How do I change my email?"}, {"role": "assistant", "content": "Go to Settings, choose Account, and select Edit email. We will send a confirmation link to the new address."}]}

Preference tuning

Instead of one right answer, preference tuning learns from comparisons: for the same prompt, which of two responses is better. A classic approach trains a separate reward model on human comparisons and then uses reinforcement learning to steer the language model toward higher reward. Newer methods, such as direct preference optimisation, skip the reward model and train on the comparisons directly, which is simpler and more stable. Preference tuning shapes tone, helpfulness, and safety behaviour, and it needs consistent labelling guidelines for the comparisons.

Distillation

Distillation trains a small model, the student, to imitate a large one, the teacher. You run the teacher over many inputs, keep its outputs (and sometimes its probability scores), and train the student on them. The student often reaches good quality on a narrow task at a fraction of the cost and latency. Check the teacher provider's terms, because some prohibit using outputs to train competing models.

The data pipeline

Most fine-tuning success or failure is decided in the data. A model learns exactly what the examples show, including their mistakes and inconsistencies.

  • Collect from real tasks, with permission, and remove personal data and secrets.
  • Clean: remove duplicates, broken records, and examples with errors.
  • Make labels consistent. If two reviewers would answer differently, write guidelines and settle the cases, because the model will learn the inconsistency.
  • Balance the set. Include hard cases and refusals, not only the common easy ones.
  • Split before you look: train, validation, and a held-out test set that is never used for tuning. Make sure near-duplicates do not cross the split.
  • Version the dataset and record where each example came from.
A basic dataset check: duplicates, length, and leakage between splits (illustrative) (python)
# Illustrative: catch common data problems before spending money on training.
import hashlib

def fingerprint(example):
    return hashlib.sha256(example['messages'][-2]['content'].strip().lower().encode()).hexdigest()

def check_dataset(train, test, max_tokens=2048):
    problems = []
    seen = set()
    for ex in train:
        fp = fingerprint(ex)
        if fp in seen:
            problems.append(('duplicate prompt', ex['id']))
        seen.add(fp)
        if count_tokens(ex) > max_tokens:
            problems.append(('too long', ex['id']))
    leaked = [ex['id'] for ex in test if fingerprint(ex) in seen]
    if leaked:
        problems.append(('test prompts also in train', leaked[:10]))
    return problems

Training infrastructure

Training runs are long, expensive, and fragile, so the infrastructure around them matters as much as the code.

Evaluation failures become new training data.
  • Training cluster: accelerators with fast links between them. Larger jobs split the work across devices: data parallelism gives each device a different slice of the data; model or tensor parallelism splits the model itself; sharding the optimiser state and gradients across devices saves memory.
  • Checkpointing: save progress regularly so a hardware failure costs minutes instead of days, and so you can pick the best point rather than the last.
  • Mixed precision: use lower-precision numbers for most arithmetic to save memory and time, with care for numerical stability.
  • Experiment tracking: record the data version, configuration, code version, seed, metrics, and cost of every run, so any result can be reproduced and compared.
  • Model registry: a catalogue of trained models with their lineage, evaluation scores, owner, and status, such as candidate, approved, or retired.
  • Cost control: use cheaper interruptible capacity with checkpoints, cap run times, and stop runs that are clearly not improving.
A promotion gate from candidate to approved (illustrative) (python)
# Illustrative: a model enters production only if it beats the current one on held-out data.

REQUIRED = {'task_success': 0.0, 'faithfulness': -0.01, 'safety_pass_rate': 0.0}   # allowed change vs current

def promote_if_better(candidate, current, registry):
    for metric, allowed in REQUIRED.items():
        change = candidate.scores[metric] - current.scores[metric]
        if change < allowed:
            return registry.reject(candidate, reason=f'{metric} changed by {change:.3f}')
    if candidate.scores['task_success'] <= current.scores['task_success']:
        return registry.reject(candidate, reason='no improvement on the main metric')
    return registry.approve(candidate, replaces=current.id, rollback_to=current.id)

Making a trained model cheaper to run

After training, a second set of techniques reduces the cost of serving. Each trades a little quality, speed, or complexity for savings, so each should be checked on your own evaluation set.

TechniqueWhat it doesBenefitCost or risk
QuantisationStores weights in fewer bits, such as 8 or 4Smaller memory, faster decodingQuality loss, especially at very low bit widths
DistillationTrains a small model to imitate a large oneMuch cheaper serving for a narrow taskNeeds data and training; may lose rare abilities
PruningRemoves weights or structures that matter littleSmaller or faster modelNeeds retraining; benefits depend on hardware support
Speculative decodingA small model drafts tokens, the large model checks themFaster generation with unchanged outputExtra memory and engine support
Mixture of expertsRoutes each token to a few specialist sub-networksLarge capacity at lower compute per tokenAll experts still occupy memory
Merging adaptersFolds an adapter into the base weightsNo adapter overhead at serving timeLoses the ability to swap adapters

Releasing a tuned model safely

  • Evaluate on a held-out test set and on your safety and regression cases, not only on the training distribution.
  • Compare with the strongest cheap baseline, a well-prompted base model. If tuning does not clearly beat it, do not ship it.
  • Roll out gradually: shadow traffic, then a small share of users, then everyone, with monitoring at each step.
  • Keep the old model available so you can roll back at once.
  • Record the lineage: which data, code, and base model produced this version.
  • Plan for the base model changing. When the provider or the open model releases a new version, your tuned model may need retraining, so keep the pipeline repeatable.

What this means for your role

Common mistakes

Further reading

Change the model only when cheaper tools have run out, and treat the result as a product you will maintain: versioned data, tracked runs, a registry, and a way back.

Search topics

↑↓ to move · Enter to open · Esc to close