Slides · Fine-tuning
Evaluation, deployment and special cases
1 / 36
Evaluation, deployment and special cases
What happens after training finishes: a sign-off that can actually fail, checks for forgetting and lost safety, the choice between merged weights and adapters, and tunes where the model is not a chat model.
By the end you can write a gate with numbers, compare a tune with its base to detect regressions, pick a serving layout, and plan an embedding, reranker or distillation tune.
Concept
The sign-off has several examiners
- The task examiner asks whether the model does the new job.
- The regression examiner asks whether it still does the old jobs.
- The safety examiner asks whether it still declines what it must, and still helps with what it should.
- The format examiner asks whether every reply is well formed.
- A pass needs all four, and the pass marks are written before the test begins. A model that is later merged, quantised or moved to a new base is a different artefact and sits the test again.
Process
The gate has five parts
- A baseline ladder: the untouched base model, then a well-prompted version, then prompting with retrieval or tools, then a cheaper small model where one is plausible. The tune has to beat the best rung you could really ship, using the newest base.
- A task metric with an interval, matched to the task (exact match, schema-valid rate plus field accuracy, pass rate, validated pairwise judge).
- Slices: the groups that matter, each with a minimum size.
- Separate suites for regression, safety and format.
- Pass rules, written first. One failed rule fails the gate.
Diagram
The baseline is a ladder
Each rung is a cheaper alternative that might already be good enough, and the comparison is run on the newest base model. A tune that cannot beat the top rung has not earned its running cost.
Worked example
Worked: is a five-point gain real?
Illustrative: 1,000 held-out items, scored independently. Baseline accuracy 0.70, tuned 0.75.
| Step | Arithmetic | Result |
|---|---|---|
| Baseline standard error | 0.70×0.30/1000 | 0.0145 |
| Tuned standard error | 0.75×0.25/1000 | 0.0137 |
| Standard error of the difference | 0.01452+0.01372 | 0.0199 |
| 95 percent half-width | 1.96×0.0199 | 0.039 |
| Gain | 0.75−0.70 | 0.050 |
The gain is larger than the half-width, so the interval excludes zero. The same 0.05 gain stops clearing the bar below about 610 items per model, because the half-width reaches 0.05 there (at 900 items it is 0.041).
Code
A paired bootstrap
Python
def paired_bootstrap(base, tuned, resamples=2000, seed=0):
if len(base) != len(tuned) or not base:
raise ValueError("score both models on the same, non-empty set of items")
if resamples < 1:
raise ValueError("resamples must be at least 1")
rng = random.Random(seed)
n = len(base)
diffs = sorted(
sum(tuned[i] - base[i] for i in (rng.randrange(n) for _ in range(n))) / n
for _ in range(resamples)
)
return diffs[int(0.025 * resamples)], diffs[int(0.975 * resamples)]| Test (Python 3.14, standard library only, 24 October 2026) | Result |
|---|---|
| Simulated 400 items in this order: 34 fixed, 8 broken, 272 right for both, 86 wrong for both (base 0.700, tuned 0.765) | 95 percent interval 0.0325 to 0.0975 |
| Unpaired formula on the same scores | half-width about 0.061 |
| Identical score lists | interval (0.0, 0.0) |
Lists of different length, empty lists, or resamples=0 | each raises ValueError as intended |
Scoring both models on the same items let the shared hard cases cancel, so the paired interval is tighter. The data are simulated for the test, not real results.
Check yourself
Check: how many items do you need?
You expect both models to score near 0.80 and want a 95 percent interval on the difference no wider than plus or minus 0.03, scoring independently. About how many held-out items per model? What would you do if the labelling budget only allows half of that?
Answer
Half-width is 1.96×2×0.8×0.2/n. Setting it to 0.03 gives n of about 1,366 items. With half the budget, score both models on the same items and use a paired interval, which is usually tighter, or accept a wider interval and treat a small gain as unproven.
Concept
Slices: where an average hides damage
- An average can rise while one group gets worse. Split the test set by the things that matter: document type, language, customer tier, input length, and the cases the baseline already failed.
- Give every slice a minimum size. A slice with too few items cannot be read, so say so rather than act on it.
- Write the allowed margin per slice before the run, for example “no slice below the baseline by more than a set amount”.
Diagram
Four suites, one decision
In practice a pass moves the candidate on to shadow traffic and a canary, and a miss goes back for a data or recipe fix, and all four suites run again.
Compare
Example pass rules (illustrative, choose your own)
| Suite | Rule written in advance |
|---|---|
| Task | Interval on the gain excludes zero and sits above the best ladder rung |
| Slices | No slice with enough items falls below its baseline by more than the set margin |
| Regression | General suite within a set drop of the base model, same prompts |
| Safety | Refusal rate on harmful prompts at or above the base; answer rate on harmless prompts not lower by more than a set margin |
| Format | Schema-valid rate at the target, reported next to accuracy and never instead of it |
Check yourself
Check: read the scoreboard
A candidate’s valid-JSON rate rose from 94 to 99 percent and its field accuracy rose. Against the base, its refusal rate on harmful prompts fell from 98 to 91 percent, and its answer rate on harmless prompts fell from 97 to 92 percent. Under the example rules, what is the verdict and what do the two safety numbers say about the cause?
Answer
The gate fails on the safety suite, because both safety measures moved the wrong way. The model is both less careful about harmful requests and less helpful on harmless ones, which points to a blunt shift in behaviour such as a data mix or learning rate that disturbed the refusal boundary, rather than a single fix. Add examples near the boundary or lower the training strength, then rerun every suite.
Concept
Forgetting and safety loss: read the difference
- Both are found the same way: run the same suite on the base and on the tuned model, then read the gap.
- An absolute score says little, because a hard suite gives a healthy model a low number.
- Forgetting shows as a fall on the regression suite while the task score rises. It concerns abilities the training data never touched, so the training set cannot reveal it.
- Overfitting is different: a held-out score worse than the training score, sometimes with verbatim repetition. Check the held-out set for that and the regression suite for forgetting.
Concept
Levers against forgetting
- Lower the learning rate or the number of epochs.
- Use an adapter, and a smaller one. A study comparing methods reports that LoRA keeps more of the base model’s performance outside the target domain than full fine-tuning, while learning less in the target domain under standard low-rank settings.
- Mix general data into the training set. The right share is something you measure on the regression suite, not a number to copy.
- Blend the tuned weights back toward the base (see the merging slides).
- Every lever is itself a change, so rerun the suites afterwards.
Concept
Safety can erode during tuning
- The authors of one red-team study report that tuning GPT-3.5 Turbo on only 10 adversarially designed examples, at a cost under $0.20 through the provider’s API, jailbroke its safety guardrails.
- They also report that tuning on benign, commonly used datasets can inadvertently degrade alignment, though to a lesser extent.
- Consequences: a safety result for the base model does not carry over to the tune, and “our data is harmless” is not evidence. The suite on the candidate is the evidence.
- Measure both directions: refusals of harmful prompts and answers to harmless ones.
Source[2] Fine-tuning Aligned Language Models Compromises Safety, Even When Users Do Not Intend To!
Compare
From signal to first action (course judgment)
| Signal, relative to base | Likely cause | First action |
|---|---|---|
| General suite falls, task rises | Narrow data, high learning rate, many epochs | Lower strength, smaller adapter, mix in general data |
| Held-out worse than training, verbatim repeats | Overfitting, duplicates | Deduplicate, fewer epochs, stop earlier |
| Harmful-prompt refusals fall | Safety alignment weakened | Add safety examples, rerun, consider a guardrail |
| Harmless requests refused more | Over-correction | Add harmless examples near the boundary |
| Valid-JSON rate falls | Template or end-of-sequence mismatch | Fix the template, add the format check |
Worked example
Worked: reading a base-versus-tuned table
Illustrative scores on one run.
| Suite | Base | Tuned | Change |
|---|---|---|---|
| Task accuracy | 62.0 | 78.5 | +16.5 |
| General knowledge | 71.2 | 64.8 | -6.4 |
| Instruction following | 83.0 | 82.1 | -0.9 |
| Harmful-prompt refusals | 97.0 | 97.5 | +0.5 |
The headline gain is large, yet the general-knowledge drop of 6.4 points is the signal: it points at forgetting, and the lever is less movement or mixed-in general data. The small drop in instruction following may be noise and needs an interval before anyone acts on it.
Concept
Folding an adapter into its base
- A LoRA adapter is a small correction applied on frozen weights. Adding it into the base gives one ordinary model with no extra step per request.
- In the PEFT guide (main branch, read 24 October 2026)
merge_and_unload()is the way to remove the adapter’s latency. The guide calls it not an in-place operation, so keep and use the returned model. In our test on PEFT 0.21.2 it also merged the wrapped model’s layers in place: the returned object was the same base model and the originalPeftModelwrapper no longer had LoRA layers. Deep-copy first if you still need the adapter version. merge_adapter()keeps the weights so you can callunmerge_adapter()later.- The guide cautions that unmerging a quantised model may not restore the original weights exactly, because merging rounds the combined weight back to low precision and repeated cycles can pile up small errors.
- Whatever you serve is the merged artefact, so the gate runs on it.
Source[3] LoRA (PEFT developer guide: merging and combining adapters)
Code
Merging, tested on a tiny model
Python
import copy, torch # imports
from torch import nn
from peft import LoraConfig, get_peft_model
torch.manual_seed(0)
cfg = LoraConfig(r=4, lora_alpha=8, target_modules=["fc1", "fc2"], init_lora_weights=False)
peft_model = get_peft_model(Tiny(), cfg) # non-zero adapter, so it changes outputs
x = torch.randn(5, 8)
before = peft_model(x).detach()
merged = copy.deepcopy(peft_model).merge_and_unload() # returns a plain model
print(type(merged).__name__, hasattr(merged.fc1, "lora_A"))
print(float((merged(x) - before).abs().max()) < 1e-5)Tiny is a two-layer network defined for the test.
| Test (PEFT 0.21.2, torch 2.14.1, float32, CPU, 24 and 25 October 2026) | Result |
|---|---|
| Type returned, adapter layers left | Tiny, False |
| Merged output matches adapter output | True (largest difference about 2.4e-7) |
merge_adapter() then unmerge_adapter() | outputs back within about 1.2e-7 |
| Same call without the deep copy | returned the same base model object, weights changed in place, the PeftModel wrapper lost its LoRA layers |
This did not test a quantised base; the rounding warning rests on the guide alone.
Source[3] LoRA (PEFT developer guide: merging and combining adapters)
Worked example
Task arithmetic with a toy example
A task vector is the tuned weights minus the base weights. The paper shows vectors can be added to combine abilities and negated to weaken one. Six made-up parameters:
| Parameter | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| Vector A | 0.90 | -0.10 | 0.50 | -0.60 | 0.02 | 0.30 |
| Vector B | 0.70 | 0.20 | -0.50 | -0.40 | -0.03 | 0.00 |
| A + B | 1.60 | 0.10 | 0.00 | -1.00 | -0.01 | 0.30 |
| 0.5×(A+B) | 0.80 | 0.05 | 0.00 | -0.50 | -0.005 | 0.15 |
Parameters 2, 3 and 5 have opposite signs in A and B. In parameter 3 the two changes cancel exactly. The scale (0.5 here) is chosen by evaluation, and the result is base weights plus this scaled sum.
Concept
TIES and DARE
- TIES-Merging names two sources of interference: redundant parameter values and disagreement over a parameter’s sign across models. Its steps: reset parameters that changed only slightly, elect a sign per parameter, and merge only the values that agree with that sign.
- DARE observes that the deltas of fine-tuned models are small and redundant, randomly drops most of them (the authors report 90 percent or even 99 percent), and rescales the rest. It is applied before combining several models.
- The difference to remember: TIES trims by size and resolves signs, while DARE drops at random and rescales.
- Both papers report research results on particular experiments, and both merge models fine-tuned from one shared pre-trained model (DARE calls them homologous). Treat merging unrelated models as untested.
Sources[5] TIES-Merging: Resolving Interference When Merging Models[6] Language Models are Super Mario: Absorbing Abilities from Homologous Models as a Free Lunch
Worked example
Why drop-and-rescale can keep the signal
A toy check of the idea, not of the paper’s method: keep each value with probability 0.1 and multiply the survivors by 10.
| Test (1,000 made-up values, uniform from -1 to 1 and rounded to 2 decimals; numpy 2.5.4; 4,000 draws; seed 0) | Result |
|---|---|
| Fraction kept in one draw (expected 0.1) | 0.121 |
| Average of the 4,000 draws vs the original values | mean error 0.018, worst error 0.124 |
| Largest error in a single draw | 9.0, on values whose size is at most 1 |
Keeping a value with probability p and dividing by p leaves its expected value unchanged, so the average of many draws sits close to the original. Any single draw is far noisier. That is why a merged model counts as a new artefact with its own tests, not a copy of its parents.
Source[6] Language Models are Super Mario: Absorbing Abilities from Homologous Models as a Free Lunch
Concept
Combining adapters in PEFT
add_weighted_adaptertakes adapters, weights and acombination_type. The guide listssvd,linear,cat,ties,ties_svd,dare_ties,dare_linear,dare_ties_svd,dare_linear_svd,magnitude_pruneandmagnitude_prune_svd.- The guide says
catandsvdare precise, and thatlinearis efficient but a very rough approximation to avoid if you can afford better. catmakes a rank equal to the sum of the input ranks.
| Test (PEFT 0.21.2, two rank-4 adapters, weights 0.5 each) | Result |
|---|---|
linear, ties, dare_linear, dare_ties, svd | each ran; resulting rank 4 |
cat | ran; resulting rank 8 |
ties without density | TypeError |
The ties and dare_* types need density, which the guide ties to those methods. A combined adapter is a new adapter and goes through the gate.
Source[3] LoRA (PEFT developer guide: merging and combining adapters)
Compare
Merged weights or separate adapters
| Merged into the base | Separate adapters on a shared base | |
|---|---|---|
| Per-request cost | None extra | A small extra step |
| Many tenants or tasks | A full weight copy per variant | One base, many small adapters |
| Rollback | Redeploy earlier weights | Point back to the earlier adapter |
| A/B test | Two deployments | Two adapters, one server |
| Best for | One dominant model | Per-tenant or per-task variants |
The vLLM documentation (the latest docs, page footer dated 21 October 2026) says a request can name the adapter through the model parameter, and loading at startup uses --lora-modules. Runtime updating is switched on by an environment variable, and the page carries a warning against using it in production outside an isolated, fully trusted environment.
Check yourself
Check: price forty variants
A team serves 40 tenant variants of one 8-billion-parameter base held in 16-bit (2 bytes per parameter). Each tenant’s adapter file is 80 MB. Compare the weight memory of 40 separately merged models with one shared base plus 40 adapters. Which vLLM server setting does the page tie to adapter requests running in parallel?
Answer
One merged copy is 8×109×2 bytes, 16 GB, so 40 copies need 640 GB. One shared base plus 40 adapters is 16+40×0.08, which is 19.2 GB, about one thirty-third of that. This counts weights only, with no cache or activations. The vLLM page says adapter requests run in parallel when max_loras is set high enough, so the shared layout still has a capacity to plan.
Diagram
Staged rollout with a registry
Shadow traffic means the new adapter sees real inputs without answering anyone. With separate adapters, rolling back means pointing at the previous adapter; with merged weights it means redeploying the earlier weights.
The SRE workbook defines a canary as a partial, time-limited deployment that is evaluated against the rest of the service, the control. Keep a registry entry for each artefact: base model revision, adapter, data version, chat template, training settings and evaluation report. When template and adapter drift apart, quality falls with no error message.
Concept
Special case: tuning an embedding model
- Reach for it when retrieval fails because the domain’s vocabulary sits far from what the embedding model learned.
- Training data is pairs of a query and a passage that answers it. The Sentence Transformers loss overview lists MultipleNegativesRankingLoss (also named InfoNCE or the in-batch negatives loss) for pairs and for triplets, and marks it as a commonly recommended default.
- Course advice: add hard negatives (passages that look relevant but are not), and have a person check a sample of LLM-generated queries.
- What it forces downstream: old and new vectors live in different spaces, so the whole corpus is re-embedded into a new index and similarity thresholds are re-checked.
- Evaluate with retrieval metrics on held-out queries and passages that were not used to build the pairs.
Source[9] Loss Overview (Sentence Transformers documentation)
Diagram
Rolling out a new embedding model
Check yourself
Check: size the rebuild
A corpus holds 3,000,000 chunks. The new embedding model outputs 384 numbers per chunk, stored as 4-byte floats. How large is the new index’s vector data, and how much space do you need while old and new indexes both exist before the swap? What else must you check before cutting over?
Answer
One index is 3,000,000×384×4 bytes, about 4.6 GB (4.608 decimal GB), and the old and new together are about 9.2 GB, before any index structure or metadata. Before the cutover, re-check similarity thresholds because score ranges change, and compare retrieval metrics on held-out queries against the untuned embedder and against a reranker. These sizes assume the old index has the same dimensions.
Concept
Special case: tuning a reranker
- A cross-encoder reads the query and a candidate passage together and returns a relevance score. The Sentence Transformers retrieve-and-rerank page presents it as the second stage: a bi-encoder retrieves candidates, and scoring every pair with a cross-encoder would be slow, so it re-ranks only that shortlist.
- If the right passages are retrieved but ranked badly, tuning the reranker is often the smallest change: it needs no re-embedding of the corpus and does not touch the generator.
- Train on query and passage relevance labels, ideally with hard negatives drawn from your own retriever.
- Evaluate ranking quality before and after on held-out queries, and measure latency, since it runs on every query.
Source[10] Retrieve & Re-Rank
Concept
Special case: distillation
- Hinton, Vinyals and Dean describe compressing the knowledge of an ensemble into a single model. In language models the same idea trains a small student to reproduce a larger teacher on a narrow task, for lower cost and latency.
- Train on the teacher’s outputs: fine-tune the student on generated text. Simple, and it works across different tokenisers.
- Match the teacher’s output probabilities: a richer signal, but it usually needs the models to share a vocabulary so the probabilities line up.
- Three checks: score the student on the teacher’s failure slices and the long tail, compare it with the cheaper rungs of the baseline ladder, and read the terms of use for the teacher’s outputs before using them as training data.
Diagram
A distillation loop with a tail check
The check looks at the slices where the teacher failed and at rare cases, because matching the average can hide tail failures.
Concept
Interview angle
Provenance: Common industry pattern. These are questions this topic tends to draw; none is verified as asked by a named company.
- Likely prompts: define the ship or no-ship gate; the general benchmark dropped, now what; merge or serve separately; when would you tune the embedding model and what changes in production.
- A strong answer names the ladder, an interval and slices, base-versus-tune comparison on regression and safety (with over-refusal), format validity kept separate, pass rules fixed first, then shadow, canary and rollback.
- For special cases it states the downstream cost: re-embedding, reranker latency, tail failures and terms of use for distillation.
Summary
Summary
- Write the gate before training: ladder, interval, slices, four separate suites, pass rules.
- Find forgetting and safety loss by comparing tuned with base on the same suites; base results do not transfer.
- Task arithmetic adds scaled task vectors; TIES resolves sign conflicts; DARE drops at random and rescales. Test every merged model afresh.
- Merge for one dominant model; keep adapters separate for many tenants and one-step rollback.
- An embedding tune forces a full re-index; a reranker tune does not; a distilled student needs a tail check.
References
References & Sources (1 of 3)
LoRA Learns Less and Forgets Less (opens in a new tab)
Dan Biderman, Jacob Portes, Jose Javier Gonzalez Ortiz, Mansheej Paul, et al.2024TMLR 2024 (Featured Certification)Paper
arXiv 2405.09673 (opens in a new tab)https://openreview.net/forum?id=aloEru2qCG
Used for LoRA underperforms full fine-tuning in the target domain under standard low-rank settings but better maintains the base model's performance outside it.
Xiangyu Qi, Yi Zeng, Tinghao Xie, Pin-Yu Chen, et al.2024ICLR 2024Paper
arXiv 2310.03693 (opens in a new tab)https://proceedings.iclr.cc/paper_files/paper/2024/hash/83b7da3ed13f06c13ce82235c8eedf35-Abstract-Conference.html
Used for Safety erosion after tuning: 10 adversarial examples under $0.20 via the provider's API, and degradation from benign datasets to a lesser extent.
LoRA (PEFT developer guide: merging and combining adapters) (opens in a new tab)
Hugging Face2026Documentation
https://huggingface.co/docs/peft/main/en/developer_guides/lora
Used for Read on 24 October 2026 (main branch): merge_and_unload described as not in place (our PEFT 0.21.2 test also merged the wrapped model in place), the unmerge caveat on quantised models, add_weighted_adapter combination types and the density argument.
Editing Models with Task Arithmetic (opens in a new tab)
Gabriel Ilharco, Marco Tulio Ribeiro, Mitchell Wortsman, Suchin Gururangan, et al.2023ICLR 2023Paper
arXiv 2212.04089 (opens in a new tab)https://www.iclr.cc/virtual/2023/poster/12254
Used for Task vectors as tuned minus pre-trained weights, with addition to combine abilities and negation to weaken one.
TIES-Merging: Resolving Interference When Merging Models (opens in a new tab)
Prateek Yadav, Derek Tam, Leshem Choshen, Colin A. Raffel, et al.2023NeurIPS 2023Paper
arXiv 2306.01708 (opens in a new tab)https://proceedings.neurips.cc/paper_files/paper/2023/hash/1644c9af28ab7916874f6fd6228a9bcf-Abstract-Conference.html
Used for The two interference sources and the three TIES steps: reset small changes, resolve sign conflicts, merge only aligned values.
References
References & Sources (2 of 3)
Le Yu, Bowen Yu, Haiyang Yu, Fei Huang, et al.2024ICML 2024Paper
arXiv 2311.03099 (opens in a new tab)https://proceedings.mlr.press/v235/yu24p.html
Used for DARE: randomly drop delta parameters and rescale the rest by 1/(1-p); 90 or even 99 percent can be dropped; used before merging homologous models.
LoRA Adapters (vLLM documentation) (opens in a new tab)
vLLM project2026Documentation
https://docs.vllm.ai/en/latest/features/lora.html
Used for Read on 24 October 2026 (page footer dated 21 October 2026): the model parameter selects the adapter, --lora-modules at startup, runtime updating gated by an environment variable with a production warning, parallel adapter requests tied to max_loras.
Chapter 16: Canarying Releases (opens in a new tab)
Alec Warner, Štěpán Davidovič2018Book
https://sre.google/workbook/canarying-releases/
Used for A canary defined as a partial, time-limited deployment evaluated against the control.
Loss Overview (Sentence Transformers documentation) (opens in a new tab)
Sentence Transformers2026Documentation
https://sbert.net/docs/sentence_transformer/loss_overview.html
Used for MultipleNegativesRankingLoss (also named InfoNCE or in-batch negatives loss) marked as a commonly recommended default for pairs and triplets.
Retrieve & Re-Rank (opens in a new tab)
Sentence Transformers2026Documentation
https://sbert.net/examples/applications/retrieve_rerank/README.html
Used for Bi-encoder retrieval followed by a cross-encoder re-ranker over a candidate shortlist, because scoring all pairs with a cross-encoder would be slow.
References
References & Sources (3 of 3)
Distilling the Knowledge in a Neural Network (opens in a new tab)
Geoffrey Hinton, Oriol Vinyals, Jeff Dean2015Preprint
arXiv 1503.02531 (opens in a new tab)https://arxiv.org/abs/1503.02531
Used for The idea of compressing the knowledge of an ensemble into a single model that is cheaper to deploy.
Keys: ← → move, Home End first and last, F full screen.