Slides · Fine-tuning

Evaluation, deployment and special cases

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

  1. 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.
  2. A task metric with an interval, matched to the task (exact match, schema-valid rate plus field accuracy, pass rate, validated pairwise judge).
  3. Slices: the groups that matter, each with a minimum size.
  4. Separate suites for regression, safety and format.
  5. Pass rules, written first. One failed rule fails the gate.

Diagram

The baseline is a ladder

Diagram: Four rungs run in order: the base model zero-shot, the best prompt with examples, prompt plus retrieval, and a cheaper small model.

Base, zero-shot

Best prompt, examples

Prompt plus retrieval

Cheaper small model

The tune must beat the top rung you could ship

Diagram summary: Four rungs run in order: the base model zero-shot, the best prompt with examples, prompt plus retrieval, and a cheaper small model. The last node says the tune must beat the top rung you could ship.

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.

StepArithmeticResult
Baseline standard error0.70×0.30/1000\sqrt{0.70 \times 0.30 / 1000}0.0145
Tuned standard error0.75×0.25/1000\sqrt{0.75 \times 0.25 / 1000}0.0137
Standard error of the difference0.01452+0.01372\sqrt{0.0145^{2} + 0.0137^{2}}0.0199
95 percent half-width1.96×0.01991.96 \times 0.01990.039
Gain0.75−0.700.75 - 0.700.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 scoreshalf-width about 0.061
Identical score listsinterval (0.0, 0.0)
Lists of different length, empty lists, or resamples=0each 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/n1.96 \times \sqrt{2 \times 0.8 \times 0.2 / n}. Setting it to 0.03 gives nn 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

Diagram: The candidate is scored in four independent suites: task, regression, safety and format.

Candidate

Task

Regression

Safety

Format

Every rule met?

Diagram summary: The candidate is scored in four independent suites: task, regression, safety and format. All four feed one decision, which asks whether every pass rule is met.

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)

SuiteRule written in advance
TaskInterval on the gain excludes zero and sits above the best ladder rung
SlicesNo slice with enough items falls below its baseline by more than the set margin
RegressionGeneral suite within a set drop of the base model, same prompts
SafetyRefusal rate on harmful prompts at or above the base; answer rate on harmless prompts not lower by more than a set margin
FormatSchema-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.

Source1 LoRA Learns Less and Forgets Less

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.

Source2 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 baseLikely causeFirst action
General suite falls, task risesNarrow data, high learning rate, many epochsLower strength, smaller adapter, mix in general data
Held-out worse than training, verbatim repeatsOverfitting, duplicatesDeduplicate, fewer epochs, stop earlier
Harmful-prompt refusals fallSafety alignment weakenedAdd safety examples, rerun, consider a guardrail
Harmless requests refused moreOver-correctionAdd harmless examples near the boundary
Valid-JSON rate fallsTemplate or end-of-sequence mismatchFix the template, add the format check

Worked example

Worked: reading a base-versus-tuned table

Illustrative scores on one run.

SuiteBaseTunedChange
Task accuracy62.078.5+16.5
General knowledge71.264.8-6.4
Instruction following83.082.1-0.9
Harmful-prompt refusals97.097.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 original PeftModel wrapper no longer had LoRA layers. Deep-copy first if you still need the adapter version.
  • merge_adapter() keeps the weights so you can call unmerge_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.

Source3 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 leftTiny, False
Merged output matches adapter outputTrue (largest difference about 2.4e-7)
merge_adapter() then unmerge_adapter()outputs back within about 1.2e-7
Same call without the deep copyreturned 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.

Source3 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:

Parameter123456
Vector A0.90-0.100.50-0.600.020.30
Vector B0.700.20-0.50-0.40-0.030.00
A + B1.600.100.00-1.00-0.010.30
0.5×(A+B)0.5 \times (A + B)0.800.050.00-0.50-0.0050.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.

Source4 Editing Models with Task Arithmetic

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.

Sources5 TIES-Merging: Resolving Interference When Merging Models6 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 valuesmean error 0.018, worst error 0.124
Largest error in a single draw9.0, on values whose size is at most 1

Keeping a value with probability pp and dividing by pp 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.

Source6 Language Models are Super Mario: Absorbing Abilities from Homologous Models as a Free Lunch

Concept

Combining adapters in PEFT

  • add_weighted_adapter takes adapters, weights and a combination_type. The guide lists svd, linear, cat, ties, ties_svd, dare_ties, dare_linear, dare_ties_svd, dare_linear_svd, magnitude_prune and magnitude_prune_svd.
  • The guide says cat and svd are precise, and that linear is efficient but a very rough approximation to avoid if you can afford better.
  • cat makes 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, svdeach ran; resulting rank 4
catran; resulting rank 8
ties without densityTypeError

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.

Source3 LoRA (PEFT developer guide: merging and combining adapters)

Compare

Merged weights or separate adapters

Merged into the baseSeparate adapters on a shared base
Per-request costNone extraA small extra step
Many tenants or tasksA full weight copy per variantOne base, many small adapters
RollbackRedeploy earlier weightsPoint back to the earlier adapter
A/B testTwo deploymentsTwo adapters, one server
Best forOne dominant modelPer-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.

Source7 LoRA Adapters (vLLM documentation)

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×28 \times 10^{9} \times 2 bytes, 16 GB, so 40 copies need 640 GB. One shared base plus 40 adapters is 16+40×0.0816 + 40 \times 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.

Source7 LoRA Adapters (vLLM documentation)

Diagram

Staged rollout with a registry

Diagram: The flow runs from shadow traffic to a canary with a small share to a full rollout.

problem

problem

Shadow traffic

Canary, small share

Full rollout

Roll back

Diagram summary: The flow runs from shadow traffic to a canary with a small share to a full rollout. Dotted edges lead from both the canary and the full rollout to a roll-back node when a problem appears.

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.

Source8 Chapter 16: Canarying Releases

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.

Source9 Loss Overview (Sentence Transformers documentation)

Diagram

Rolling out a new embedding model

Diagram: Training changes the vector space, so the corpus is re-embedded into a new index, similarity thresholds are re-checked, and retrieval...

Query and passage pairs

Contrastive training

Re-embed whole corpus

Recheck thresholds

Evaluate, then swap

Diagram summary: Training changes the vector space, so the corpus is re-embedded into a new index, similarity thresholds are re-checked, and retrieval metrics are compared on held-out queries before switching traffic to the new index.

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×43{,}000{,}000 \times 384 \times 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.

Source10 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.

Source11 Distilling the Knowledge in a Neural Network

Diagram

A distillation loop with a tail check

Diagram: The teacher produces outputs on task inputs and the small student trains on them.

yes

no

Large teacher

Teacher outputs on task inputs

Train small student

Teacher failure slices ok?

Compare with cheaper rungs

Fix data or recipe, retrain

Diagram summary: The teacher produces outputs on task inputs and the small student trains on them. A check asks whether the teacher’s failure slices are handled: if yes, the student is compared with cheaper rungs; if no, the data or recipe is fixed and the student is retrained.

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)

  1. 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

    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.

  2. Fine-tuning Aligned Language Models Compromises Safety, Even When Users Do Not Intend To! (opens in a new tab)

    Xiangyu Qi, Yi Zeng, Tinghao Xie, Pin-Yu Chen, et al.2024ICLR 2024Paper

    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.

  3. LoRA (PEFT developer guide: merging and combining adapters) (opens in a new tab)

    Hugging Face2026Documentation

    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.

  4. Editing Models with Task Arithmetic (opens in a new tab)

    Gabriel Ilharco, Marco Tulio Ribeiro, Mitchell Wortsman, Suchin Gururangan, et al.2023ICLR 2023Paper

    Used for Task vectors as tuned minus pre-trained weights, with addition to combine abilities and negation to weaken one.

  5. 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

    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)

  1. Language Models are Super Mario: Absorbing Abilities from Homologous Models as a Free Lunch (opens in a new tab)

    Le Yu, Bowen Yu, Haiyang Yu, Fei Huang, et al.2024ICML 2024Paper

    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.

  2. LoRA Adapters (vLLM documentation) (opens in a new tab)

    vLLM project2026Documentation

    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.

  3. Chapter 16: Canarying Releases (opens in a new tab)

    Alec Warner, Štěpán Davidovič2018Book

    Used for A canary defined as a partial, time-limited deployment evaluated against the control.

  4. Loss Overview (Sentence Transformers documentation) (opens in a new tab)

    Sentence Transformers2026Documentation

    Used for MultipleNegativesRankingLoss (also named InfoNCE or in-batch negatives loss) marked as a commonly recommended default for pairs and triplets.

  5. Retrieve & Re-Rank (opens in a new tab)

    Sentence Transformers2026Documentation

    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)

  1. Distilling the Knowledge in a Neural Network (opens in a new tab)

    Geoffrey Hinton, Oriol Vinyals, Jeff Dean2015Preprint

    Used for The idea of compressing the knowledge of an ensemble into a single model that is cheaper to deploy.