AirborneOps Learning Labs · Walkthrough

Fine-tuning lab — when to fine-tune (vs prompt), dataset prep, LoRA/PEFT walkthrough, evaluation, and cost

A hands-on walkthrough that takes a fine-tuner from the when-to-fine-tune gate (per-slice cost-vs-score decision table driven by the same stratified golden set the eval pipeline already produces) through dataset preparation in the Alpaca/ShareGPT/plain-JSONL shapes pinned to a SHA the loader validates against, a LoRA/PEFT walkthrough configuring peft.LoraConfig and SFTConfig alongside SFTTrainer on a 4-bit bitsandbytes base model, evaluation after fine-tuning that replays the golden-set sweep and diffs the per-slice table against the hash-pinned pre-fine-tune capture with a side-by-side slice-level diff viewer, and a fully-priced per-run cost model (compute-hours × $/hr + token licensing + iteration sweeps + storage + bandwidth, amortised over the chosen refresh window) that lives next to the checkpoint SHA in the hosted tracking server. Includes reference patterns for IAM scoping per concern (dataset writer vs LoRA writer vs cost-modeller), private-link training posture, and tracking-server SHA pinning alongside the eval pipeline's manifest.

AI Engineer

Last updated 2026-08-08 · 23 min read

Where this lab fits

Existing role and certification connections for this hands-on work.

IT roles

  • AI Engineer
Prerequisites
  • A Polsia AI proxy route exposed via @/lib/ai/client with `chat` and `generateObject` primitives wired — you must never call an OpenAI/Anthropic SDK directly from the fine-tuning driver, because every direct call ships dead (the platform does not inject a provider key).
  • A stratified golden set + raw-output capture cycle wired by the eval pipeline walkthrough at /labs/evals-pipe — the same JSONL shape, the same scoring harness, and the same slice-weighted sampling power the when-to-fine-tune decision table and the post-fine-tune slice diff.
  • A hosted tracking server (MLflow, Vertex Experiments, SageMaker Experiments) reachable over a private link as covered by /labs/mlops-toolchain — the LoRA config SHA, the dataset SHA, the sweep SHA, and the cost-model row all land here so the fine-tuning run is reproducible from artefacts, not from prose.

Step 1 — Decide whether to fine-tune via a per-slice cost-vs-score table

Decide whether to fine-tune *quantitatively*, not by feel. The cleanest gate is a per-slice cost-vs-score table solved against the same stratified golden set the eval pipeline already drives (see /labs/evals-pipe): for each rubric slice where the prompt-engineered baseline scores below an acceptable threshold, compute the marginal USD/call savings a fine-tuned smaller model could deliver by replacing a long-context larger model, and only commit a fine-tuning budget when payback covers the training cost plus the per-iteration recapture overhead inside the chosen refresh window. Capture the baseline once with hash-pinned per-row payloads under the same raw-output JSONL the eval pipeline replays from so any later "did this fine-tune actually deliver?" diff is reproducible from artefacts, not from prose. Pin the decision table in the hosted tracking server (see /labs/mlops-toolchain) next to the prompt SHA so a "we should fine-tune" headline becomes a deliberate SHA-tagged change.

Sample command
# scripts/decision_table.py — when-to-fine-tune gate. Reads the same
# golden-set slice table the eval pipeline produces and only authorises a
# fine-tuning budget when the smaller-model savings clear the training
# amortisation inside the chosen refresh window. Pin the run SHA next to
# the prompt SHA so the decision is reproducible from artefacts.
import json
from pathlib import Path

baseline   = json.loads(Path("evals/baseline_long_context.jsonl").read_text())
golden     = json.loads(Path("evals/golden_set.jsonl").read_text())
TRAIN_USD  = 4200    # money.loops at ~$4.2k for 8h on 4×A100 80GB
REFRESH_HR = 24 * 14 # two-week amortisation window

slices = {}
for row in golden:
    s = row["slice"]
    if s not in slices:
        slices[s] = {"examples": 0, "baseline_pass": 0, "fine_tune_pass": 0}
    slices[s]["examples"] += 1

for row in baseline:
    s = row["slice"]
    if row["pass"]:
        slices[s]["baseline_pass"] += 1

# The "fine_tune_pass" column is the predicted pass-rate after training on
# labelled exemplars for this slice — populate it from the held-out sweep
# that the training harness runs against the same golden set.
for row in golden:
    s = row["slice"]
    if row.get("predicted_pass_after_ft"):
        slices[s]["fine_tune_pass"] += 1

decision_rows = []
for s, d in slices.items():
    long_ctx_cost   = 0.018 * d["examples"]   # $/call @ long-context model
    small_ft_cost   = 0.002 * d["examples"]   # $/call @ fine-tuned small model
    saved_per_call  = long_ctx_cost - small_ft_cost
    calls_to_payback= TRAIN_USD / saved_per_call if saved_per_call > 0 else None
    payback_days    = (calls_to_payback or float("inf")) / (24 * d["examples"])
    decision_rows.append({
        "slice": s,
        "baseline_pass": d["baseline_pass"] / d["examples"],
        "ft_pass":       d["fine_tune_pass"]  / d["examples"],
        "saved_per_call":saved_per_call,
        "payback_days":  payback_days,
        "authorise":     payback_days <= 14,
    })

Path("evals/decision_table.jsonl").write_text(
    "\n".join(json.dumps(r, sort_keys=True) for r in decision_rows) + "\n"
)
Things to double-check
  • Hash-pin the per-row baseline payload before any training budget lands, so a later "did the fine-tune actually deliver?" diff is reproducible from the manifest, not from chat.
  • Authorise a training budget per slice, not in aggregate — a single slice whose payback exceeds the refresh window is a slice the fine-tune should not have been scoped for.

Step 2 — Format the dataset in a single, explicit schema (Alpaca / ShareGPT / plain JSONL)

Format the dataset in a single, explicit schema — Alpaca for single-turn, ShareGPT for multi-turn, JSONL of plain `{prompt, completion}` for the narrowest contract — and pin that schema to a SHA the loader validates against before any tokenisation starts. A SFT run that loads a mixed bag of Alpaca rows and free-text completions is a run that quietly paid for half-trained exemplars; the loader must reject any row whose schema SHA does not match the manifest, and the manifest must live next to the prompt SHA in the hosted tracking server (see /labs/mlops-toolchain) so a dataset reshuffle shows up as a SHA diff, not as a Slack thread. Deduplicate by per-row payload SHA, not by raw text, because two rows that differ only in whitespace are still two rows the trainer will treat as separate updates.

Sample command
# dataset_format.py — Alpaca + ShareGPT + plain JSONL schemas, each pinned
# to a SHA the SFT loader validates against before tokenisation starts.
# Any row whose schema SHA does not match the manifest is rejected.
import hashlib, json
from pathlib import Path

ALPACA_SCHEMA = {
    "type": "object",
    "required": ["instruction", "input", "output"],
    "properties": {
        "instruction": {"type": "string"},
        "input":       {"type": "string"},
        "output":      {"type": "string"},
    },
}

SHAREGPT_SCHEMA = {
    "type": "object",
    "required": ["conversations"],
    "properties": {
        "conversations": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["from", "value"],
                "properties": {
                    "from":  {"type": "string", "enum": ["system", "human", "gpt"]},
                    "value": {"type": "string"},
                },
            },
        },
    },
}

PLAIN_PC_SCHEMA = {
    "type": "object",
    "required": ["prompt", "completion"],
    "properties": {
        "prompt":     {"type": "string"},
        "completion": {"type": "string"},
    },
}

def schema_sha(schema: dict) -> str:
    return hashlib.sha256(
        json.dumps(schema, sort_keys=True).encode()
    ).hexdigest()

# Pin the chosen schema's SHA in manifest.json and reject any row whose
# declared schema_sha doesn't match. This stops an Alpaca reshuffle
# from silently feeding a ShareGPT loader.
manifest = {
    "alpaca":    schema_sha(ALPACA_SCHEMA),
    "sharegpt":  schema_sha(SHAREGPT_SCHEMA),
    "plain_pc":  schema_sha(PLAIN_PC_SCHEMA),
}
Path("datasets/manifest.json").write_text(json.dumps(manifest, indent=2))
Things to double-check
  • Pin the loader's schema SHA in the manifest and reject any row whose declared `schema_sha` does not match — a reshuffle that mixes Alpaca and ShareGPT rows is a reshuffle that silently corrupts the tokeniser.
  • Deduplicate by per-row payload SHA, not by raw text — two rows that differ only in whitespace are still two rows the trainer will treat as separate updates.

Step 3 — Configure LoRA via peft.LoraConfig + SFTTrainer on a 4-bit base model

Configure LoRA via `peft.LoraConfig` rather than touching the underlying nn.Module so a model upgrade that ships a different parameter layout still loads the same adapter. Pin `r`, `alpha`, `target_modules`, and `lora_dropout` in a YAML next to the dataset manifest; record the YAML SHA in the hosted tracking server (see /labs/mlops-toolchain) so a "we changed LoRA settings last sprint" claim is verifiable from artefacts. The taxonomy of modules the adapter hooks (`q_proj`, `v_proj`, `qkv_proj`, etc.) is a vendor-by-vendor decision — encode it in the YAML, do not hard-code it in the trainer, because a checkpoint that pretends to be a different adapter family will load as garbage at serving time.

Sample command
# train_lora.py — peft.LoraConfig + SFTTrainer on a 4-bit bitsandbytes base
# model. The YAML is the source of truth — checksum the file and pin the
# SHA in the run manifest so a different "r"/"alpha"/"target_modules"
# combination cannot silently relabel a previous experiment.
import hashlib, yaml, torch
from pathlib import Path
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from transformers import (
    AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
)
from trl import SFTConfig, SFTTrainer

CONFIG = yaml.safe_load(Path("train/lora_v3.yaml").read_text())
CONFIG_SHA = hashlib.sha256(
    Path("train/lora_v3.yaml").read_bytes()
).hexdigest()

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
)

model = AutoModelForCausalLM.from_pretrained(
    CONFIG["base_model"],
    quantization_config=bnb_config,
    device_map="auto",
)
model = prepare_model_for_kbit_training(model)

lora = LoraConfig(
    r=CONFIG["r"],
    lora_alpha=CONFIG["alpha"],
    lora_dropout=CONFIG["lora_dropout"],
    target_modules=CONFIG["target_modules"],
    bias="none",
    task_type="CAUSAL_LM",
)
model = get_peft_model(model, lora)
model.print_trainable_parameters()

trainer = SFTTrainer(
    model=model,
    args=SFTConfig(
        output_dir=CONFIG["output_dir"],
        num_train_epochs=CONFIG["epochs"],
        per_device_train_batch_size=CONFIG["batch_size"],
        gradient_accumulation_steps=CONFIG["grad_accum"],
        learning_rate=CONFIG["lr"],
        logging_steps=10,
        save_strategy="epoch",
        bf16=True,
        optim="paged_adamw_8bit",
        report_to="none",
    ),
    train_dataset=load_dataset(CONFIG["dataset_path"], CONFIG["schema_sha"]),
)
trainer.train()
trainer.save_model(CONFIG["output_dir"])
Path("train/RUN_MANIFEST.json").write_text(json.dumps({
    "config_sha": CONFIG_SHA, "base_model": CONFIG["base_model"],
    "dataset_sha": CONFIG["dataset_sha"],
}, indent=2))
Things to double-check
  • Encode `target_modules` in the YAML not in the trainer; a hard-coded target list that pretends to be a different adapter family will load as garbage at serving time.
  • Pin the YAML SHA in the run manifest next to the base model SHA so a different `r`/`alpha`/`target_modules` combination cannot silently relabel a previous experiment.

Step 4 — Pin the bitsandbytes 4-bit config so the memory budget matches the quote

Pin the quantisation config to a YAML committed alongside the LoRA config. `bnb_4bit_quant_type=nf4` plus `bnb_4bit_compute_dtype=bfloat16` is the conventional pairing for adapter training on a single A100/H100; without the double-quant flag the memory savings are roughly half what the run-quote assumed. Use `prepare_model_for_kbit_training` before wrapping the model in `get_peft_model` so gradient checkpointing knows to stop at the `Linear4bit` boundary — a run that skips this step pays for an OOM that the YAML's VRAM budget did not anticipate. Record the bitsandbytes version in the manifest so a version bump that changes the kernel does not silently re-train under different numerics.

Sample command
# train/bnb_v3.yaml — bitsandbytes 4-bit config committed to the repo.
# SHA this file alongside the LoRA config; the run manifest records the
# pair so a quantisation regression cannot ride in under a "we only
# changed one parameter" claim.
bnb_4bit_quant_type:        "nf4"
bnb_4bit_compute_dtype:     "bfloat16"
bnb_4bit_use_double_quant:  true
# Optimiser choice matters at 4-bit — paged_adamw_8bit keeps the optimiser
# state out of GPU memory. If you swap to plain adamw, the optim state
# alone will OOM a 4-bit base model on a single A100 80GB.
optim:                      "paged_adamw_8bit"
gradient_checkpointing:     true
# Pin the bitsandbytes + transformers + peft versions in requirements.txt
# and record the resolved versions in the run manifest.
Things to double-check
  • Use `bnb_4bit_use_double_quant: true` — without it the memory savings are roughly half what the run-quote assumed, and the OOM surfaces mid-epoch.
  • Call `prepare_model_for_kbit_training` BEFORE `get_peft_model`, so gradient checkpointing knows to stop at the `Linear4bit` boundary; a run that skips this step pays for an OOM the YAML did not budget for.

Step 5 — Re-run the eval pipeline's golden set under the fine-tuned endpoint

Re-run the same stratified golden set the eval pipeline already drives (see /labs/evals-pipe) — under the *fine-tuned* endpoint, not the baseline one — and diff the per-slice table against the pre-fine-tune hash-pinned capture. A fine-tune that lifts the factual slice by 8 points and drops the refusal slice by 3 is a fine-tune that ships worse refusal behaviour than the baseline, and a paper EM gain masks that regression. Gate CI on the slice-level delta, never on the overall EM, so a slice regression cannot slip through; pin the sweep SHA plus the model checkpoint SHA in the hosted tracking server (see /labs/mlops-toolchain) so the gate cannot be silently re-tagged.

Sample command
# scripts/eval_finetune.py — replay the eval pipeline's golden set through
# the fine-tuned endpoint and diff the per-slice table against the
# pre-fine-tune hash-pinned capture. Gate CI on slice-level deltas, not
# overall EM, so a refusal regression cannot ride in under a factual gain.
import hashlib, json
from pathlib import Path
from openai import OpenAI  # the Polsia proxy is OpenAI-compatible.

client    = OpenAI()
golden    = [json.loads(l) for l in Path("evals/golden_set.jsonl").read_text().splitlines() if l]
baseline  = {r["prompt_id"]: r for r in json.loads(Path("evals/baseline_zero_shot.jsonl").read_text())}
FT_MODEL  = "ft:tempus-lab/handbook-assistant:2026-08-08::sha-a1b2c3"

runs, scores = [], []
for g in golden:
    response = client.responses.create(
        model=FT_MODEL,
        input=[{"role": "user", "content": g["query"]}],
        tools=g.get("tools"),
    )
    payload = {
        "prompt_id":    g["id"],
        "slice":        g["slice"],
        "model":        FT_MODEL,
        "response":     response.output_text,
        "tokens":       response.usage.total_tokens,
        "passed":       bool(re.search(re.escape(g["expected"]), response.output_text, re.I)),
    }
    payload["payload_sha"] = hashlib.sha256(
        json.dumps(payload, sort_keys=True).encode()
    ).hexdigest()
    runs.append(payload)
    scores.append(payload["passed"] & 1)

Path("evals/finetune_runs.jsonl").write_text(
    "\n".join(json.dumps(r, sort_keys=True) for r in runs) + "\n"
)
Things to double-check
  • Gate CI on slice-level deltas, not on overall EM — a single-slice regression masked by an EM gain is the canonical migration pattern for a fine-tune that overfit to one rubric.
  • Pin the sweep SHA next to the model checkpoint SHA in the hosted tracking server so the gate cannot be silently re-tagged.

Step 6 — Build a side-by-side slice-level diff viewer before reading the EM headline

Build a side-by-side slice-level diff viewer, not an overall EM delta, so the reviewer sees which slice gained ground and which slice lost ground alongside the prompt change. A fine-tune that improves format adherence by 12 points and degrades factual accuracy by 9 points is the textbook failure mode of a single-epoch run that overfit to the formatter rewards; surfacing them as adjacent bars in the same table is the cheapest way to prevent the "looks like we made it better" headline the EM number invites. Store reviewer notes as a JSONL column on the eval run so a CI gate that disagrees with the model output can be re-graded later from artefacts, not from a meeting.

Sample command
# evals/side_by_side.jsonl — one row per (slice, prompt_id). The
# baseline column points at the SHA-pinned pre-fine-tune row; the
# ft column points at the same prompt_id captured under the new model.
# The diff column makes the reviewer story explicit before any human
# reads the EM headline.
[
  {
    "slice": "factual",
    "prompt_id": "exemplar-factual-001",
    "baseline": { "pass": true,  "response_sha": "a3f1..." },
    "ft":       { "pass": true,  "response_sha": "7c2b..." },
    "diff":     "no_change"
  },
  {
    "slice": "refusal",
    "prompt_id": "exemplar-refusal-002",
    "baseline": { "pass": true,  "response_sha": "9b40..." },
    "ft":       { "pass": false, "response_sha": "d2e1..." },
    "diff":     "ft_broke_refusal"
  },
  {
    "slice": "format",
    "prompt_id": "sweep-procedural-004",
    "baseline": { "pass": false, "response_sha": "0a55..." },
    "ft":       { "pass": true,  "response_sha": "be3d..." },
    "diff":     "ft_fixed_format"
  }
]
Things to double-check
  • A single-epoch run that overfit to formatter rewards is the textbook source of a format gain masked by a factual drop — surface them as adjacent bars in the same table.
  • Store reviewer notes as a JSONL column on the eval run so a CI gate that disagreed with the model output can be re-graded later from artefacts, not from a meeting.

Step 7 — Price the run the way finance prices it: $/hr + tokens + iterations + storage

Build a per-run cost model that prices the training job the way finance would price it: compute-hours × on-demand $/hr for the chosen instance family, plus token-licensing where it applies, plus the iteration cost of every failed sweep the team ran to land on the kept checkpoint, plus storage and bandwidth for the artefact store the team is committing to. A training run that cost $4.2k headline but consumed $14k of failed sweeps is a fine-tune whose TCO is three-times the budget number, and the post-mortem will be the first place that surfaces it. Project the per-call savings of the fine-tuned endpoint against the call-volume forecast for the next refresh window, then amortise the total training spend over that window. Pin the cost model itself in the hosted tracking server (see /labs/mlops-toolchain) next to the model checkpoint SHA so a "the training run was cheap" headline becomes a deliberate dollar-and-centres diff, not prose.

Sample command
# train/cost_model.py — price the run the way finance prices it: compute
# hours × $/hr, token licensing, iteration sweeps, storage, bandwidth.
# Pin the resulting JSON next to the model checkpoint SHA so the
# post-mortem cannot quietly re-quote the budget.
import json
from pathlib import Path

INSTANCE_FAMILY = "a100_80gb_spot"
HOURLY_USD      = { "a100_80gb_spot": 1.85, "h100_80gb_od": 4.10 }[INSTANCE_FAMILY]

training_run = {
    "compute_hours": 8.4,
    "instance":      INSTANCE_FAMILY,
    "hourly_usd":    HOURLY_USD,
    "compute_usd":   8.4 * HOURLY_USD,
    "token_license_usd": 320,
    "iteration_sweeps": [
        { "name": "r=8-only-qkv",   "compute_hours": 6.1, "scratch": False },
        { "name": "r=16-qkv+mlp",   "compute_hours": 7.8, "scratch": False },
        { "name": "r=16-nf4-dq",    "compute_hours": 8.4, "scratch": False, "kept": True },
    ],
    "storage_gb": 42,
    "storage_usd_per_gb_month": 0.023,
    "egress_gb": 0,
}

training_run["iteration_usd"] = sum(
    s["compute_hours"] * HOURLY_USD for s in training_run["iteration_sweeps"]
)
training_run["storage_usd"] = (
    training_run["storage_gb"] * training_run["storage_usd_per_gb_month"]
)
training_run["total_tco_usd"] = (
    training_run["compute_usd"]
    + training_run["token_license_usd"]
    + training_run["iteration_usd"]
    + training_run["storage_usd"]
)

# Per-call saving assumes the fine-tuned model swaps out a long-context
# larger model at $0.018/call for the same kind of handbook query. The
# refresh window is the amortization period the finance team agreed to.
fine_tuned_cost_per_call = 0.002
long_context_cost_per_call = 0.018
refresh_window_days = 14
forecast_calls_per_day = 12_000
saved_per_window_usd = (
    (long_context_cost_per_call - fine_tuned_cost_per_call)
    * forecast_calls_per_day * refresh_window_days
)
training_run["saved_per_window_usd"] = round(saved_per_window_usd, 2)
training_run["tco_recovered_in_window"] = (
    saved_per_window_usd >= training_run["total_tco_usd"]
)

Path("train/cost_model.json").write_text(
    json.dumps(training_run, indent=2, sort_keys=True)
)
Things to double-check
  • The iteration-sweep delta is the line the headline compute cost hides — a $4.2k headline whose failed sweeps cost another $10k is a run whose post-mortem number will be the first place this shows up.
  • Amortise over the chosen refresh window and pin the cost model next to the checkpoint SHA so a "the training run was cheap" headline becomes a dollar-and-centres diff.
Prompt vs fine-tune

Prompt vs fine-tune — score the gate per slice, not in aggregate

Bind the fine-tuning budget to a single IAM principal scoped narrowly to the training instance family and the artefact bucket — never grant blanket training-cluster access, because a fine-tuning run that can write the artefact bucket can also rewrite the baseline checkpoint the eval pipeline diffs against. Require every training run to attach a manifest (dataset SHA, LoRA config SHA, quantisation SHA, eval sweep SHA) before the principal can issue the spot-instance launch command; a run that ships without a manifest is a run whose reject block the reviewer cannot reproduce. Pin the manifest in the same hosted tracking server the eval pipeline writes to (see /labs/mlops-toolchain) so a refused training run is recoverable from artefacts, not from a Slack scroll. When the run ships, gate the deploy on the slice-level sweep — a fine-tune whose EM delta is positive but whose refusal slice regressed must not deploy without manual override.

Run fine-tuning jobs on a private instance pool reachable only from the dataset bucket and the hosted tracking server — never from the public internet, and never from the same subnet the inference fleet serves from, because a leaked training token with a single hop into production is a single hop away from shipping a compromised adapter to every customer endpoint. Pin egress from the training runtime to the same hosted tracking server as the eval runs (see /labs/mlops-toolchain) so a training worker that tries to phone a tracking row with a stolen signature cannot smuggle a poisoned checkpoint under the legitimate run id. Mirror the dataset bucket to a second region asynchronously so a region outage does not strand an in-flight training job mid-epoch; promote checkpoints across regions only via an explicit stored procedure that writes the same manifest SHA into both regions.

Prompt vs fine-tune sample
# train/decision_table.jsonl — produced by scripts/decision_table.py and
# promoted to training only when the payback days ≤ the chosen refresh
# window. Each row carries the slice and the fine_tune_pass rate that
# was measured on the held-out sweep.
[
  {
    "slice": "factual",
    "baseline_pass": 0.71,
    "ft_pass": 0.93,
    "saved_per_call": 0.016,
    "payback_days": 9.7,
    "authorise": true
  },
  {
    "slice": "refusal",
    "baseline_pass": 0.96,
    "ft_pass": 0.91,
    "saved_per_call": 0.016,
    "payback_days": 11.4,
    "authorise": true
  },
  {
    "slice": "format",
    "baseline_pass": 0.62,
    "ft_pass": 0.97,
    "saved_per_call": 0.016,
    "payback_days": 7.2,
    "authorise": true
  }
]
Things to double-check
  • Bind the fine-tuning budget principal to the training instance family + the artefact bucket ONLY — never grant blanket training-cluster access, because a fine-tuning run that can write the artefact bucket can also rewrite the baseline checkpoint the eval diffs against.
  • Run fine-tuning jobs on a private instance pool reachable only from the dataset bucket and the hosted tracking server — never from the public internet, and never on the same subnet as the inference fleet.
Dataset

Dataset — schema-pinned rows per curator with row-level PII audit

Grant the dataset curator write access to the dataset bucket only — never to the training runtime or the hosted tracking server, because a curator that can rewrite the tracking row can also rewrite the manifest SHA the eval pipeline diffs against. Require every PII redaction to be paired with a row-level audit entry (`row_sha`, `redactor_principal`, `replacement_strategy`, timestamp) and to land in the same transaction the curated row is committed under so a disputed redaction is reconstructable from a SQL query, not from a Slack scroll. Gate the bucket on a labelled-license tag for every source dataset; a training run that loads an unlicensed source set is a run whose fine-tuned checkpoint license is incompatible with the inference surface, and the post-mortem will name "the dataset curator was off-scope". When the bucket ships, gate it on the schema SHA so any row whose declared schema does not match the manifest is rejected before tokenisation consumes compute-hours against an unsanctioned input.

Mirror the dataset bucket to a second region under a separate principal, with an asynchronous projector that writes the same per-row SHA into both regions so a cross-region comparison catches a curator identity that quietly rewrote a row on one side only — a divergent mirror is a divergent curator and the gate fires before training consumes compute against the bad copy. Pin the dataset SHA in the hosted tracking server (see /labs/mlops-toolchain) and route the training runtime to read the SHA-pinned version over a private link, never from a public CDN endpoint, because a public CDN that serves the dataset under a stale cache is a CDN that has poisoned the training input with last week's schema. Schedule redaction audits on a deploy-cadence-independent job so a redaction regression that ships outside the regular window still triggers the policy gate on its own webhook.

Dataset sample
# datasets/checks.jsonl — one row per (manifest_sha, row_count,
# redaction_strategy, license_tag, pii_count). The gate refuses any run
# whose manifest_sha is not present here.
[
  {
    "manifest_sha": "f8c3...",
    "row_count":    12480,
    "redaction":    "regex_pii_v2",
    "license_tag":  "internal-handbook-cc-by-4.0",
    "pii_count":    0,
    "audit_url":    "s3://handbook-curator/audit/2026-08-08.tar.gz"
  }
]
Things to double-check
  • Grant the curator bucket-only write access; never the training runtime or the hosted tracking server — the audit story fails the moment the curator can rewrite the tracking row.
  • Mirror the bucket to a second region under a separate principal with a per-row SHA projector, so a divergent mirror is a divergent curator caught before training consumes compute.
LoRA / PEFT

LoRA / PEFT — YAML committed with a SHA, gates on slice-level sweep

Bind the LoRA hyperparameter writer to a narrow principal scoped to the YAML file in the train/ folder — never to the trainer runtime, because a writer that can rewrite the trainer can also rewrite the manifest SHA the eval gate hashes against. Require every LoRA config change to leave an audit row (`yaml_sha`, `requester`, `approver`, before/after `r`/`alpha`/`target_modules`) in the same transaction the YAML is committed under, so a debated hyperparameter change is traceable without scraping Slack. Pin the YAML file SHA in the hosted tracking server (see /labs/mlops-toolchain) so a reviewer who disagrees with the `r=16` choice can trace the disagreement to a deliberate SHA diff, not to a "we always use 16" habit. When the run ships, gate it on the slice-level delta — a fine-tune that boosts the format slice but breaks refusal must not deploy without an explicit override.

Pin the LoRA checkpoint to a private artefact bucket reachable only from the training runtime and the inference surface that will serve it — never from the public internet, because a public-bucket LoRA adapter with a stolen signature is a one-line pretrain replacement. Mirror the checkpoint to a second region asynchronously so a region outage does not strand the inference fleet against a single-region artefact; promote across regions only via the same stored procedure as the dataset bucket so the manifest SHA stays coherent. Pin the bitsandbytes version, the PEFT version, and the transformers version in requirements.txt next to the YAML so a model upgrade that quietly changes a kernel does not silently re-train under different numerics. Route the side-by-side sweep through the same private-link eval cluster the prompt-engineering diff uses (see /labs/evals-pipe) so a regression that surfaces under the fine-tuned model surfaces the same way under the prompt-engineered baseline.

LoRA / PEFT sample
# train/lora_v3.yaml — the YAML is the source of truth. Pin its SHA
# in run_manifest.json next to the base model + dataset sha so a model
# upgrade that changes target_modules surfaces as a deliberate diff,
# not as a silently relabelled experiment.
base_model:        "tempus-lab/handbook-assistant-7b"
r:                 16
alpha:             32
lora_dropout:      0.05
target_modules:
  - q_proj
  - k_proj
  - v_proj
  - o_proj
epochs:            3
batch_size:        4
grad_accum:        4
lr:                2.0e-4
output_dir:        "checkpoints/handbook-assistant-lora-v3"
dataset_path:      "datasets/handbook_qa_v3.jsonl"
dataset_sha:       "f8c3..."
quantisation:      "bnb_4bit_nf4_dq"
# The manifest commits both the YAML SHA and the resolved package versions.
Things to double-check
  • Bind the LoRA writer to a narrow principal scoped to the YAML file — never to the trainer runtime, because a writer that can rewrite the trainer can also rewrite the manifest the gate hashes against.
  • Pin the checkpoint to a private artefact bucket reachable only from the training runtime and the inference surface that serves it; a public-bucket LoRA adapter with a stolen signature is a one-line pretrain replacement.
Evaluation

Evaluation — slice-level sweep gates the deploy, EM is informational only

Grant the sweep runner a principal scoped to the golden-set bucket and the slice-weighted sampler, never to the artefact bucket or the model registry, because a runner that can rewrite the registry can also rewrite the response SHA the sweep diffs against. Require every sweep run to land an `eval_run` row carrying the model checkpoint SHA, the sweep config SHA, and the slice-level score table BEFORE the runner reports success so a successful CI build whose eval_run row is missing is a CI build that did not actually run. Pin the eval_run row in the hosted tracking server (see /labs/mlops-toolchain) so a regression that surfaces three weeks later can be traced back to a deliberate sweep SHA, not to a "we re-ran this yesterday" assumption. When the deploy goes out, gate it on the slice-level delta; a single-slice regression above the configured threshold blocks the deploy regardless of the headline EM.

Route the eval sweep through the same OIDC-on-private-link job the prompt-engineering diff already uses (see /labs/evals-pipe) so a fine-tune regression that surfaces under the slice sweep surfaces the same way under the prompt diff. Pin the per-slice side-by-side heatmap to the dashboard so a refusal regress and a format gain land in the same reviewer queue, not in two separate post-mortems; the heatmap is the artefact the finance team reads first when the cost model says the fine-tune is paying for itself. Schedule the rejection sweep on a deploy cadence independent of the fine-tuning job so a retrain that ships outside the regular window still triggers the regression gate on its own webhook.

Evaluation sample
# evals/finetune_slice_diff.jsonl — per-slice delta; the deploy gate
# refuses a merged PR unless every slice delta sits inside the configured
# threshold for both directions.
[
  { "slice": "factual", "baseline_pass": 0.71, "ft_pass": 0.93, "delta":  +0.22, "gate": "pass" },
  { "slice": "refusal", "baseline_pass": 0.96, "ft_pass": 0.91, "delta":  -0.05, "gate": "fail" },
  { "slice": "format",  "baseline_pass": 0.62, "ft_pass": 0.97, "delta":  +0.35, "gate": "pass" }
]
Things to double-check
  • Every sweep run must land an `eval_run` row with the model checkpoint SHA + sweep config SHA + slice table BEFORE the runner reports success — a successful CI whose eval_run row is missing did not actually run.
  • Schedule the rejection sweep on a deploy-cadence-independent cron so a retrain that ships outside the regular window still triggers the regression gate on its own webhook.
Cost

Cost — amortise TCO over the chosen refresh window; defer if it does not recover

Grant the cost-modeller write access to the cost-tracking write-side table and the hosted tracking server, never to the trainer runtime or the artefact bucket, because a modeller that can rewrite the manifest can also rewrite the dollar-and-centres number the run is amortising against. Require every cost model to land a row carrying the run SHA, the headline compute cost, the iteration sweep delta, the storage cost, the bandwidth cost, and the amortised TCO BEFORE the run is marked complete so a run whose cost row is missing is a run that did not actually price itself. Pin the cost-model row in the hosted tracking server (see /labs/mlops-toolchain) so the post-mortem cannot quietly re-quote the budget after the run has shipped. When the run ships, gate the deploy on TCO recovery inside the chosen refresh window; a fine-tune whose TCO does not recover inside the window is a fine-tune whose deploy should be deferred until the call-volume forecast improves.

Pin the cost-tracking write-side table to a private subnet reachable only from the run-runtime and the finance dashboard, never from the training instance itself, because a training worker with cost-write access is a worker that can lower its own post-mortem number. Mirror the cost row to a second region asynchronously with a per-row SHA so a cross-region comparison catches a modeller identity that quietly rewrote a run's dollar figure. Schedule the cost-row freshness check on a deploy-cadence-independent cron so a stale row that ships with a checkpoint is caught by the gate before the deploy window closes.

Cost sample
# train/cost_model.json — the per-run cost model lives next to the
# checkpoint and is mirrored to the cost-tracking write-side table in
# the same transaction the model_checkpoint_sha is recorded under.
# The deploy gate refuses any checkpoint whose cost row is missing.
{
  "compute_hours": 8.4,
  "instance":      "a100_80gb_spot",
  "compute_usd":   15.54,
  "token_license_usd":   320.0,
  "iteration_usd": 412.74,
  "storage_usd":   0.97,
  "total_tco_usd": 749.25,
  "saved_per_window_usd": 2688.0,
  "tco_recovered_in_window": true,
  "model_checkpoint_sha": "a1b2c3...",
  "run_manifest_sha":     "d4e5f6..."
}
Things to double-check
  • Grant the cost-modeller write access to the cost-tracking write-side table ONLY — never to the trainer runtime or the artefact bucket, because a modeller that can rewrite the manifest can also rewrite the dollar-and-centres number the run is amortising against.
  • Pin the cost row to a private subnet reachable only from the run-runtime and the finance dashboard — a training worker with cost-write access is a worker that can lower its own post-mortem number.
Cohort notes

Questions from the cohort

See what other learners are clarifying as they work through this walkthrough.

Next labs

Pair this fine-tuning walkthrough with the MLOps toolchain lab so the LoRA config SHA, the dataset SHA, the sweep SHA, and the cost-model row all land in the same hosted tracking server the eval gate scores against, and with the eval pipe lab so the post-fine-tune slice diff replays the exact same raw-output JSONL the scoring harness scores against.

MLOps toolchain labAll labsDiscuss the fine-tuning lab in /community →

AI certification roadmap

Connect hands-on practice with certification preparation by mapping lab work to exam domains.

Explore the certification roadmap