small-model-lab · Part 2 · Post-training

From a toy to a tool

In Part 1 we built a tiny GPT from scratch and hit its ceiling: it learned the shape of language but never anything useful. This chapter is the other half of the arc: how real models are made useful. We take a pretrained open model and fine-tune it into TrialScout: a small expert that turns an oncology clinical-trial record into a structured, investor-relevant readout, running on a laptop, for free.

The whole idea: a giant model already knows language; we don't re-teach that. We just specialise it for one narrow, structured task, by showing it ~1,500 worked examples and nudging a tiny set of its parameters. The result beats a sensible baseline by a mile and nearly matches the expensive model that taught it.

And none of this is new machinery. The model is the same animal you built in Part 1 — a transformer, attention blocks and all, just ~1,200× bigger — and fine-tuning is the same training loop (tokens, the loss, gradient descent), now in service of something that does a job.

How to read this. Same as Part 1: the idea first, then the real code, then a plain-English gloss. Part 2 is more pipeline than algorithm, so the code boxes show the excerpts that do the real work (pulled straight from the repo) rather than every line. Haven't read Part 1 yet? Start there; this chapter assumes its vocabulary.

Stage 1 · Orientation

0

The shift: don't build, adapt

Part 1 ended on an honest ceiling: a from-scratch model, trained on a laptop, produces believable words but no real knowledge or reasoning. Closing that gap from scratch would take what the giants spent: trillions of tokens, thousands of GPU-hours. So we don't.

Instead we start from a model that has already paid that price: a pretrained open model (here, Alibaba's Qwen3-4B, 4 billion parameters, freely downloadable). It already knows English, clinical jargon, JSON, the lot. Our job is narrow: specialise it for one task it isn't yet reliable at: reading a trial record and emitting a clean, structured readout. That's post-training, and it's how almost every useful model you've met was made.

Stage 2 · Teaching the model the task

1

The task, and the contract

First, the domain, for anyone new to it. A clinical trial is a study that tests whether a treatment (here, a cancer drug) is safe and actually works. Drug companies run thousands of them, and to an investor each one is a potential catalyst: an upcoming result that can move a company's value. The trouble is the raw information: every trial is written up in long, inconsistent prose, and there are tens of thousands of them. So TrialScout's job is to turn each trial into a short, uniform structured summary, so a whole population of trials becomes something you can scan, filter, compare, and screen at a glance, instead of reading registry pages one at a time.

Concretely: every trial has a public record on ClinicalTrials.gov, the US government registry of studies. Each record is semi-structured data (a title, phase, status, lead sponsor, the conditions and drugs under test, the primary outcome measure, key dates, enrollment, trial design) plus free text. We fetch it from the registry's API and trim it to the ~20 fields that matter: that trimmed record is TrialScout's input. Its output is a compact ten-field JSON readout: nct_id, phase, indication, intervention_class (is this even a drug trial?), modalities (what kinds of drug, as a list), primary_endpoint_type, sponsor_type, est_readout (its expected readout as a half-year, e.g. “H2 2026”), risk_flags, and a ≤2-sentence investor_note. Most output fields are enums (a fixed menu of allowed values), so the readouts are directly comparable across trials, and easy to score.

The work is turning verbose, inconsistent registry data into normalised judgement: reading “Merck Sharp & Dohme LLC” and writing large pharma, or a raw 2021-06-08 completion date into H1 2021. That's why it needs a model, not a parser. Here is a real held-out trial (NCT03631407), with TrialScout's actual output:

the input: NCT03631407's record from ClinicalTrials.gov (trimmed)
{
  "brief_title": "Safety and Efficacy of Vicriviroc (MK-7690) in Combination With
                  Pembrolizumab (MK-3475) in Advanced/Metastatic Microsatellite
                  Stable (MSS) Colorectal Cancer (CRC)",
  "phases": ["PHASE2"],          "overall_status": "COMPLETED",
  "lead_sponsor": "Merck Sharp & Dohme LLC", "lead_sponsor_class": "INDUSTRY",
  "primary_completion_date": "2021-06-08",
  "conditions": ["Colorectal Neoplasms"],
  "interventions": [{"type": "DRUG", "name": "Vicriviroc"},
                    {"type": "BIOLOGICAL", "name": "Pembrolizumab"}],
  "primary_outcomes": [{"measure": "Objective Response Rate (ORR) per RECIST 1.1"}],
  "enrollment": 41, "allocation": "RANDOMIZED", "masking": "NONE", "n_arms": 2
}
TrialScout's actual output for this real trial
{
  "nct_id": "NCT03631407",
  "phase": "Phase 2",
  "indication": "Microsatellite stable (MSS) advanced/metastatic colorectal cancer",
  "intervention_class": "drug/biologic",
  "modalities": ["monoclonal antibody", "targeted small molecule"],
  "primary_endpoint_type": "objective response rate (ORR)",
  "sponsor_type": "large pharma",
  "est_readout": "H1 2021",
  "risk_flags": ["open-label", "surrogate endpoint", "biomarker-restricted",
                 "small enrollment (<50)"],
  "investor_note": "This randomized Phase 2 trial tests whether adding vicriviroc (a CCR5
                    inhibitor) to pembrolizumab (anti-PD-1) improves ORR over pembrolizumab
                    alone in MSS-CRC, a population historically excluded from checkpoint
                    benefit. A positive result could support a new combination in this
                    immunotherapy-resistant subgroup. Key caveats are the small actual
                    enrollment of 41, ORR as a surrogate endpoint, and the biomarker-restricted
                    (MSS only) population limiting addressable market breadth."
}
trial_readout.schema.json
    "intervention_class": {
      "type": "string",
      "enum": [
        "drug/biologic",
        "external-beam radiation",
        "procedure/surgery",
        "device",
        "behavioral/supportive care",
        "diagnostic/imaging",
        "other"
      ],
      "description": "What kind of intervention this trial actually tests. Decide this BEFORE modalities. 'drug/biologic' if any drug or biologic is given as anticancer therapy under study; otherwise the non-drug category that fits. Not every oncology trial has a drug asset - surgical-technique, radiotherapy-technique, device and supportive-care trials do not."
    },
    "modalities": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": [
          "targeted small molecule",
          "cytotoxic chemotherapy",
          "hormonal/endocrine therapy",
          "monoclonal antibody",
          "bispecific/multispecific antibody",
          "antibody-drug conjugate",
          "other protein or peptide therapeutic",
          "oligonucleotide/RNA therapeutic",
          "cell therapy",
          "gene therapy",
          "oncolytic virus",
          "cancer vaccine",
          "radiopharmaceutical",
          "other"
        ]
      },
      "description": "The DISTINCT therapeutic modalities present among the drugs/biologics this trial gives as anticancer therapy, as an unordered set sorted alphabetically. One entry per distinct modality, however many agents share it. MUST be an empty array [] when intervention_class is not 'drug/biologic'. This field says WHICH modalities are present, never how many agents there are and never which agent leads."
    },
    "primary_endpoint_type": {
      "type": "string",
      "enum": [
        "overall survival (OS)",
        "progression-free survival (PFS)",
        "objective response rate (ORR)",
        "disease-free survival (DFS)",
        "pathologic complete response (pCR)",
        "safety/tolerability",
        "pharmacokinetics",
        "other"
      ],
      "description": "Category of the primary outcome measure(s)."
    },
    "sponsor_type": {
      "type": "string",
      "enum": [
        "large pharma",
        "biotech",
        "academic/cooperative group",
        "government",
        "other"
      ],
      "description": "Classify the lead sponsor. 'large pharma' = top-20 global pharma; 'biotech' = smaller commercial sponsor; map sponsor_class OTHER/NIH/NETWORK to academic/government appropriately."
    },
    "est_readout": {
      "type": "string",
      "description": "Estimated primary readout window derived from primary_completion_date, as 'H1 YYYY' / 'H2 YYYY', or 'unknown' if absent."
    },
    "risk_flags": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": [
          "single-arm",
          "no comparator",
          "small enrollment (<50)",
          "surrogate endpoint",
          "early-phase",
          "open-label",
          "non-randomized",
          "PK/dose-finding only",
          "status: terminated/withdrawn/suspended",
          "long timeline (>4y)",
          "biomarker-restricted"
        ]
      },
      "description": "DERIVED, not generated. The pipeline computes the seven arithmetic flags from the record (schema/derive.py) and unions them with the model's `risk_flags_judgement`. Present in the served readout; never requested from a model. See ADR-0022: the teacher got `enrollment < 50` wrong 20 times in 150, and the student learned the mistake.",
      "x-derived": true
    },
    "risk_flags_judgement": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": [
          "surrogate endpoint",
          "biomarker-restricted",
          "PK/dose-finding only",
          "no comparator"
        ]
      },
      "description": "Risk flags that require READING the trial, as an unordered set sorted alphabetically. Only these four. Everything else in `risk_flags` is arithmetic on fields already in the record and is computed by the pipeline, not asked of you. Empty array if none apply."
The output contract (excerpt): controlled vocabularies the model must pick from.
what this says

What this is: a JSON Schema, the contract for the model's output. Each enum (modality, primary_endpoint_type, sponsor_type, risk_flags) is a closed list of allowed strings. Constraining the output this way does two jobs at once: it makes a small model's task tractable (pick from a menu, don't free-write), and it lets us measure correctness later by simple comparison, with no human grading the bulk of it.

2

Distillation: a strong model writes the textbook

To fine-tune the student we need a pile of correct examples (1,500 here): trial in, perfect readout out. Writing those by hand would take an analyst weeks. So we distill: a strong, expensive model (Claude Sonnet 5) reads each trial and writes the gold answer, and the small student then learns to reproduce those answers. The teacher's judgement becomes the student's training data.

Step back and name it: this is plain supervised learning, training on labeled (input → correct output) pairs. Part 1 was self-supervised: the next character was a free label already sitting in the text, so nobody had to annotate anything. Here there is no free label; we must supply the right readout for each trial. (Done to an already-pretrained model, this is called supervised fine-tuning.) The only unusual part is where the labels come from: not human annotators, but a stronger model. Training a small model on a big model's outputs is knowledge distillation.

Oncology trials ClinicalTrials.gov 1,500 records Claude Sonnet 5 the teacher forced tool-use Gold labels structured JSON one per trial Qwen3-4B the student learns to reproduce read writes answers fine-tune
Fig. 1Distillation: the expensive teacher (Claude) writes structured answers for 1,500 trials; those become the gold labels the cheap student (Qwen) is fine-tuned to reproduce.
make_gold.py
            r = client.messages.create(
                model=model,
                system=SYS, tools=TOOLS,
                tool_choice={"type": "tool", "name": "emit_readout"},
                messages=[{"role": "user", "content": f"TRIAL:\n{json.dumps(trial, ensure_ascii=False)}\nReturn the readout."}],
The teacher call: Claude is forced to answer through the schema, so every label is valid.
what this says

The key moves:

  • tool_choice={"type": "tool", "name": "emit_readout"}: forced tool-use. The teacher can't free-write; it must call the emit_readout tool, whose arguments are the schema. So every answer comes back already valid and parseable, with no JSON wrangling.
  • temperature=0: deterministic, no creative drift; we want the teacher's single best call.
  • system=SYS: the rules + worked examples, marked prompt-cached so the big static prefix is billed once, not per trial. That (plus a cap and a pilot gate) kept the whole labeling run to about $12.
3

The data pipeline (and not burning money)

Generating labels with a paid API, unattended, demands guardrails. The labeling script fetches trials from the free ClinicalTrials.gov API, then calls the teacher with three safety nets: a hard cost cap, a 10-trial pilot gate (abort before the bulk run if quality is poor), and resumable writes (a crash loses nothing).

make_gold.py
    pilot = todo[:10]
    print("\n--- PILOT (10 trials) ---")
    pilot_ok = 0
    for t in pilot:
        res = label_one(t, stop, args.model, args.effort)
        if res and not res.get("error") and valid(res["readout"])[0]:
            pilot_ok += 1
        record(res)
    print(f"pilot valid: {pilot_ok}/10  | spent ${cost[0]:.3f}")
    if pilot_ok < 8:
        print("ABORT: pilot quality below 8/10 — not starting bulk run. Inspect data/gold/all.jsonl.")
        out_f.close(); return
The pilot gate: label 10, check validity, and refuse the bulk spend if they're not good.
what this says

What this says: label the first 10 trials, count how many come back schema-valid, and if fewer than 8 pass, stop before spending on the other 1,490: a broken prompt fails cheap, not at full cost. The bulk loop (not shown) adds the hard dollar cap and appends each result to disk as it arrives. The clean gold is then split 80/10/10 into train / validation / test sets.

Stage 3 · Fine-tuning

4

LoRA: a small patch on a big model

Now the fine-tune. The naïve way (update all 4 billion of Qwen's parameters) needs far more memory than a laptop has, and risks the model forgetting everything else it knows. The standard fix is LoRA (Low-Rank Adaptation): freeze the entire base model and train only a small set of extra “adapter” weights that sit alongside it. You learn a tiny patch, not a new model.

Two questions worth answering before the command. Where does the adapter come from? It's created, not chosen: when the run starts, the trainer bolts small blank matrices alongside the frozen weights, initialised so they have zero effect, and gradient descent writes into them — they are the only parameters allowed to move. The 28 MB file this run produces is the adapter; it didn't exist before training, and on its own it's useless — it only means something snapped onto its base model. And is there a menu of adapters to pick from? Not for a new task. What you pick are its dials: how many of the model's layers get a patch (we adapt the top 16) and how wide each patch is (the rank, which we leave at the trainer's default). Ready-made adapters do get shared around for existing tasks — a downloadable “LoRA” for an image model is exactly this kind of file — but nobody has trained one for trial readouts, which is rather the point of this chapter.

Qwen3-4B (base) frozen · 4-bit · ~2 GB billions of parameters, left untouched ❄ + LoRA adapter 28 MB of weight deltas the only part trained TrialScout base + adapter
Fig. 2LoRA: the billions of base-model parameters stay frozen; training only adjusts a small adapter (~28 MB of weight deltas). At runtime you load the base and snap the adapter on top.
run_phase3.py
    cmd = ["nice", "-n", "15", sys.executable, "-m", "mlx_lm", "lora", "--model", model, "--train",
           "--data", str(MLX_DATA), "--fine-tune-type", "lora",
           "--num-layers", str(num_layers), "--batch-size", str(BATCH), "--iters", str(ITERS),
           "--learning-rate", LR, "--max-seq-length", str(MAXSEQ),
           "--steps-per-report", "50", "--steps-per-eval", "200", "--val-batches", "20",
           "--adapter-path", str(adapter), "--grad-checkpoint", "--mask-prompt", "--seed", "0"]
The actual fine-tune command (MLX's LoRA trainer).
what this says

Reading the flags: --fine-tune-type lora picks the adapter approach; --num-layers 16 attaches adapters to the top 16 layers; --iters 700, --batch-size 4, --learning-rate 1e-4 are the same training-loop dials from Part 1 (steps, batch, step-size): gradient descent, unchanged, just pointed at this task. --mask-prompt means the loss is computed only on the answer tokens, not the trial text, so the model learns to produce readouts, not echo inputs.

The result: train loss fell 2.56 → 0.16 in ~50 minutes on the Mac, producing a 28 MB adapter. That's the whole trained model: a small delta you apply on top of the public base.

5

Evaluation: the part that makes it real

In Part 1 we judged the model by reading its output: fine for “does this look like English?”, useless for “is this correct?”. A useful model needs a real scorecard. So the eval harness is a first-class deliverable, not an afterthought: it runs the student over the 1,444 held-out trials and scores each field against the gold answer.

Gold test set 1,444 held-out trials TrialScout predicts a readout 7 structured fields → accuracy / F1 per field investor_note (free text) → Claude-as-judge Overall score 0.476 → 0.932 vs baseline
Fig. 3The eval: for every held-out trial, the student predicts a readout; structured fields are scored by accuracy/F1, the free-text note by a Claude judge, and rolled into one overall score vs the baseline.
infer_and_score.py
        model, tok = load(args.model, adapter_path=args.adapter)
    else:
        print(f"[{args.label}] loading {args.model} (UNTUNED base, no adapter) ...", flush=True)
        model, tok = load(args.model)

    # v4 prompts from the facts tier, built by the SAME function training used. Importing it
    # rather than re-implementing is deliberate: a prompt that drifts between train and eval
    # shows up as an unexplained score drop, never as an error.
    FACTS: dict = {}
    if args.schema == "v4":
        from schema.facts import extract, project_for_prompt
        from format_for_mlx import build_prompt_v4
        for _l in (ROOT / "data" / "raw" / "studies_full.jsonl").read_text().splitlines():
            if _l.strip():
                _f = project_for_prompt(extract(json.loads(_l)))
                if _f.get("nct_id"):
                    FACTS.setdefault(_f["nct_id"], _f)

    def prompt_for(g):
        if args.schema == "v4":
            user = build_prompt_v4(FACTS[g["nct_id"]])
            return tok.apply_chat_template([{"role": "user", "content": user}],
                                           add_generation_prompt=True, tokenize=False)
        user = build_prompt(RAW[g["nct_id"]]) + (enum_appendix() if args.with_enums else "")
        return tok.apply_chat_template([{"role": "user", "content": user}],
                                       add_generation_prompt=True, tokenize=False)

    def record(nct_id, text):
        obj = extract_json(text)
        if obj:
            preds[nct_id] = snap_to_enum({"nct_id": nct_id, **obj})
            return 1
        return 0

    # Resume: generations are ~4-8 s each, so an interrupted run must not lose them. Every
    # parsed readout is appended to disk as it is produced, and an existing file is picked up.
    out_dir = ROOT / "eval"
    preds_path = out_dir / f"preds_{args.label}.jsonl"
    preds, parsed_ok, t0 = {}, 0, time.time()
    if preds_path.exists() and not args.restart:
        for line in preds_path.read_text().splitlines():
            if line.strip():
                r = json.loads(line)
                preds[r["nct_id"]] = r
        parsed_ok = len(preds)
        print(f"[{args.label}] resuming: {parsed_ok} readouts already on disk "
              f"(--restart to discard them)", flush=True)
    todo = [g for g in test_set if g["nct_id"] not in preds]
    preds_f = preds_path.open("a")

    bs = max(1, args.batch_size)
    for start in range(0, len(todo), bs):
        chunk = todo[start:start + bs]
        prompts = [prompt_for(g) for g in chunk]
        if bs == 1:
            texts = [generate(model, tok, prompt=prompts[0], max_tokens=args.max_tokens, verbose=False)]
        else:
            resp = batch_generate(model, tok, prompts=[tok.encode(p) for p in prompts],
                                  max_tokens=args.max_tokens, verbose=False)
            texts = resp.texts
        for g, text in zip(chunk, texts):
            before = len(preds)
            parsed_ok += record(g["nct_id"], text)
            if len(preds) > before:                       # flush immediately: kill-safe
                preds_f.write(json.dumps(preds[g["nct_id"]]) + "\n")
        preds_f.flush()
        done = min(start + bs, len(todo))
        rate = (time.time() - t0) / max(done, 1)
        print(f"  [{args.label}] {done}/{len(todo)}  parsed_ok={parsed_ok}  "
              f"({rate:.2f}s/trial, ~{rate*(len(todo)-done)/60:.0f} min left)", flush=True)
    preds_f.close()

    res = (score(test_set, preds, CATEGORICAL_V4, SET_VALUED_V4, include_est_readout=False)
           if args.schema == "v4" else score(test_set, preds))
Load base + adapter, generate a readout per test trial, parse it, and score it.
what this says

What this says: load(model, adapter_path=...) loads the frozen base and snaps the LoRA adapter on top (that's how LoRA is consumed). For each trial it builds the same prompt used in training, generates text, pulls the first {…} object out, and snaps any near-miss enum value to the closest legal one (so eval matches what the deployed server does). score() then compares the seven scoreable fields to gold (accuracy and macro-F1 for the four single-value enums, exact match for est_readout, and set-F1 for the two list fields, modalities and risk_flags; F1 is a 0–1 score balancing false positives against misses, 1.0 perfect), exactly the metrics the baseline was measured with, so the comparison is fair.

Stage 4 · The result

6

The result

Here is the payoff, on 1,444 trials the model never saw — a fresh, randomly-sampled held-out set, not the small one we started with. Four comparisons matter, and they say different things. The majority-class baseline (always guess the most common value for each field) is the floor. Untuned Qwen is the same open model on the same prompt before any fine-tuning, told the list of allowed values but nothing else. The frontier model is Claude Sonnet 5 — the expensive model that wrote the training labels — handed the schema and nothing else, no rules and no worked examples. That last column is the one that makes the headline honest: it is the bar a small local model has to clear.

FieldBaseline (floor)Untuned QwenFrontier modelQwen studentFine-tuning gainShipped tool
overall structured0.4760.6970.8970.932+0.2350.939
valid JSON—1.0001.0001.000—1.000
phase read0.4470.9871.0000.997+0.0101.000
intervention_class0.8270.6400.9330.944+0.3040.944
modalities (set-F1)0.3300.6950.8590.862+0.1670.862
primary_endpoint_type0.3800.6400.9330.936+0.2960.936
sponsor_type computed0.6670.8330.9330.976+0.1431.000
est_readout computed0.0400.4200.8270.976+0.5561.000
risk flags (set-F1)0.6430.6620.7940.831+0.1690.831

In the Shipped tool column the three marked rows are no longer generated: read is copied from the registry record, computed is arithmetic on it. The four unmarked rows are what the fine-tuned model is actually asked for, and they are identical to the Qwen student column — it is the same adapter.

One caveat on reading across a row. The Qwen student column is scored on the 1,444-trial held-out set. The three comparison arms were scored on the frozen 150-trial set and have not been re-run at the larger size. The student scores 0.936 on that smaller set — within noise of the 0.932 above — so the columns are fair to read side by side, but they are not the same measurement, and the gain column inherits that.

The last column: what shipped, and why it differs

The Qwen student column is the model on its own. The Shipped tool column is what you would actually call — and the gap between them is not a better model. It is the same model, asked to do less.

Three of those seven fields never needed a model at all. phase is a string sitting in the registry record. sponsor_type is a lookup on the sponsor’s own registered class. est_readout is arithmetic on a date: months 01–06 are H1, 07–12 are H2. The model answered all three well — 0.997, 0.976, 0.976 — but well is the wrong bar when the answer is already written down. The pipeline reads or computes them now, and that is the whole of the +0.007.

The other four genuinely need reading: naming the disease, deciding what kind of intervention is under study, working out which drug modalities are present, judging the risk flags. Knowing that trastuzumab emtansine is an antibody-drug conjugate is pharmacology, not parsing. Those four are unchanged to three decimal places — it is the same adapter — and on them the model scores 0.893. Both numbers are worth stating: the readout got more accurate, the model did not get better.

Two caveats. The three 1.000s mean deterministic, not independently checked: phase is a verbatim copy, est_readout applies its rule exactly (though the rule is itself a simplification), and sponsor_type is only as reliable as the registry’s own sponsor class, which occasionally files a commercial biotech under “other”. And the larger change is not in the table at all: the shipped readout also carries the full title, the dates, recruitment status, enrolment, a one-line design descriptor, every study arm, each intervention with its dose and schedule, and the primary outcome measures. None of that is generated and none of it is scored — it is simply read from the record. It also turned out to be most of what a reader actually wanted.

7

Decide by eval, not by faith

Which base model to fine-tune, Qwen3-4B or Google's Gemma 4 E2B? We didn't argue about it; we ran both through the same harness and let the score decide. That's the discipline: model choice is a measurement, not a preference.

In the end Qwen won by default and by margin. Gemma 4 E2B failed to train at all: the only available checkpoint is a multimodal (vision+text) build whose weights the LoRA trainer couldn't target. And Qwen's score is so near the ceiling that even a perfectly-trained Gemma would have to beat it to flip the call, implausible on this task. So the measured decision is Qwen, robustly.

8

Can you beat the teacher? (The error-mining loop)

The weakest field was modality. The natural next move is a recursive improvement loop, a general pattern worth naming: mine the model's errors → generate targeted new training data for exactly those cases → retrain → measure → repeat, each pass trying to climb a little higher. It's the honest, buildable kernel of the “self-improving AI” idea. We ran one turn of it: snapped near-miss enum values for free, then added 300 fresh gold examples of the rare modalities the model kept missing.

It barely moved: a statistical wash. We concluded the residual errors were label noise — cases where the teacher's own answers disagreed — and that you can't loop your way out of that with more data.

That conclusion was half wrong, and finding out why is the most useful thing in this chapter. Going back through the errors months later, the biggest cluster wasn't the model being unsure. It was our schema being unanswerable. The modality field offered ten real modalities plus combination — which is not a modality at all, but a statement about how many there are. Nearly six errors in ten sat on that seam, running in both directions, because the question had no stable answer. Worse: one oncology trial in six tests no drug at all — a surgical technique, a radiotherapy schedule, a device — and the schema forced a drug modality onto every one of them.

So we rebuilt the field: modalities became a list (a trial pairing an antibody with chemotherapy says both), combination was deleted, and a new intervention_class field lets a trial answer “there is no drug here.” Then we regenerated every label and retrained from scratch. The “how many” argument fell from 59% of modality errors to 36%. Two-thirds of what we had written off as irreducible noise was our own specification, and it was fixable.

What remains is the other half of the original diagnosis: rarity. The scorecard said the model was still missing antibody-drug conjugates (0.40) and oncolytic viruses (0.33), so we bought 300 more examples of exactly those classes, retrained, and measured again. Nothing moved. Both figures came back identical, to two decimal places.

They came back identical because the test set could not see the difference. Those 150 held-out trials contain 5 antibody-drug conjugates and 3 oncolytic viruses. One trial is worth 20 and 33 recall points. “0.40” was two trials out of five. We had built a scorecard that was excellent for a headline number and blind to precisely the thing we were trying to fix — and we had already drawn a confident conclusion from it once before.

So we built a second, larger test set weighted toward the rare classes — 402 trials, 45 per modality. On that one the extra data had worked all along. But that set had its own flaw, and it is worth seeing: we had found those trials by searching for the class name, and a search for “bispecific antibody” can only return trials that say “bispecific antibody”. It was stacked with the easy cases and could not, by construction, contain the hard ones. Two test sets, two different biases, both confidently wrong.

The third attempt was the boring one that worked: 1,444 fresh trials, sampled at random, no enrichment, matching the real mix to within a percentage point. On that, the model reads antibody-drug conjugates at 0.91 and bispecifics at 0.79. Not 0.40. Not 0.77. The model had been fine the whole time and we had measured it three ways before getting one worth trusting.

Stage 5 · Ship it

9

Packaging it as a callable expert

A trained adapter on disk isn't useful yet. The last step makes TrialScout callable: wrapped as an MCP tool (Model Context Protocol, the standard way to expose a tool to an AI client like Claude). Now any assistant can ask it for a readout by trial ID, and it answers locally, no API spend.

trial_readout_server.py
@mcp.tool(
    name="trial_readout",
    annotations={
        "title": "TrialScout: read out a trial by NCT ID",
        "readOnlyHint": True,
        "destructiveHint": False,
        "idempotentHint": True,
        "openWorldHint": True,  # fetches from ClinicalTrials.gov
    },
)
async def trial_readout(
    nct_id: Annotated[str, Field(
        description="ClinicalTrials.gov identifier, e.g. 'NCT02942290' (case-insensitive).",
        pattern=r"^[Nn][Cc][Tt]\d{8}$")],
    response_format: Annotated[ResponseFormat, Field(
        description="'markdown' (human-readable) or 'json' (structured object + schema validity).",
    )] = ResponseFormat.MARKDOWN,
) -> str:
The MCP tool: give it an NCT id, get back a schema-validated readout.
what this says

What this says: the @mcp.tool decorator registers trial_readout as a callable tool with a typed input (an NCT id, validated by a regex) and a choice of markdown or JSON output. Under the hood it fetches the trial from ClinicalTrials.gov, runs the fine-tuned model locally, and validates the result against the schema before returning it. The annotations (readOnlyHint, idempotentHint) tell the calling assistant it's a safe, repeatable read. This is the “callable expert” the whole pipeline was for.

10

The arc, closed: running it yourself

That's the full arc. Part 1 built a language model from nothing to understand the machinery; Part 2 took a pretrained one and specialised it into a measurably useful expert, for the price of some patience and about $12 of teacher calls. The giants are not different in kind; they are this, at scale. And the techniques here (distillation, LoRA, eval-driven decisions) are exactly how a small team turns a big open model into something that does their job.

README.md
# 1. Fetch trials (free, public API)
uv run python track-b-trialscout/data/fetch_trials.py --target 1500

# 2. Distill gold labels with the Claude teacher (SPENDS MONEY — needs ANTHROPIC_API_KEY)
#    Hard cost cap + 10-trial pilot gate; resumable.
uv run python track-b-trialscout/train/make_gold.py --target 1500 --cap 24

# 3. Establish the baseline the fine-tuned model must beat
uv run python track-b-trialscout/eval/harness.py --baseline majority

# (Phase 3) fine-tune, then score the student:
uv run python track-b-trialscout/eval/harness.py --pred <student_preds.jsonl>
Reproduce it (read-along note below): the four commands of the pipeline.

Reference appendix

↪

Python primer

Part 2's code is pipeline code, so its recurring patterns differ from Part 1's. (New to Python entirely? Part 1's primer covers the basics: variables, functions, classes, loops.) These six cover most of what appears in this chapter's code boxes.

{"phase": "Phase 2", "enrollment": 41}
A dictionary: named slots holding values, Python's all-purpose record. It's also exactly the shape of JSON, the text format APIs speak, which is why trial records and readouts move through this whole chapter as dictionaries.
client.messages.create(model=..., temperature=0)
Keyword arguments. Each name=value names the setting it fills, so a call with many options stays readable. The teacher call in §2 is mostly this.
cmd = ["mlx_lm", "lora", "--iters", "700"]
A command as a list. Each item is one word of a terminal command; Python hands the list to the operating system to run. The fine-tune in §4 is launched exactly this way, which is why its code box reads like flags rather than maths.
todo[:10]
Slicing: take the first ten items of a list. The pilot gate in §3 labels todo[:10] and checks the results before risking money on the other 1,490.
@mcp.tool(...)
A decorator: an @ line just above a function that wraps or registers it. In §9 it's the line that tells the MCP server “this function is a callable tool.”
def trial_readout(nct_id: str) -> str:
Type hints. The : str and -> str declare what kind of value goes in and comes out (text, here). Python doesn't enforce them; they're documentation that tools and readers rely on.