#!/usr/bin/env python3 """PathQA end-to-end demo. Runs the whole second-reader pipeline on one command: 1. load patches (PCam public data, or --synthetic for a no-download demo) 2. fine-tune the classifier 3. calibrate confidences (temperature scaling on the val split) 4. simulate a sign-out queue with a realistic pathologist error rate 5. run the QA second reader and print + save a prioritized re-check worklist Examples -------- # Fast, no download (verifies the pipeline): python demo.py --synthetic --epochs 1 # Real public data (downloads PatchCamelyon on first run): python demo.py --pcam --subset 4000 --epochs 2 --budget 0.05 """ from __future__ import annotations import argparse import copy import random from pathlib import Path import torch from pathqa.data import get_pcam_loaders, get_synthetic_loaders from pathqa.engine import (evaluate, expected_calibration_error, fit_temperature, train_one_epoch) from pathqa.model import TemperatureScaler, build_model from pathqa.qa import SecondReader def _inject_pathologist_labels(loader, error_rate: float, seed: int = 0): """Build a 'sign-out' set: true labels with a small fraction flipped to simulate the rare human misses a QA layer is meant to catch. Returns (batches, truth): `batches` is a list of (image_batch, path_label_batch) preserving the original batching so QA review stays fast, and `truth` is the flat list of ground-truth labels in the same order. """ rng = random.Random(seed) batches, truth = [], [] for x, y in loader: path_labels = y.clone() for i in range(x.size(0)): true_label = int(y[i]) if rng.random() < error_rate: path_labels[i] = 1 - true_label # simulated human error truth.append(true_label) batches.append((x, path_labels)) return batches, truth def main() -> None: ap = argparse.ArgumentParser(description="PathQA second-reader demo") src = ap.add_mutually_exclusive_group() src.add_argument("--pcam", action="store_true", help="use PatchCamelyon (downloads)") src.add_argument("--synthetic", action="store_true", help="use synthetic patches (no download)") ap.add_argument("--data-root", default="./data") ap.add_argument("--subset", type=int, default=4000, help="PCam samples per split") ap.add_argument("--syn-train", type=int, default=1024, help="synthetic train size") ap.add_argument("--syn-eval", type=int, default=512, help="synthetic val/test size") ap.add_argument("--epochs", type=int, default=2) ap.add_argument("--lr", type=float, default=1e-4) ap.add_argument("--batch-size", type=int, default=64) ap.add_argument("--max-train-batches", type=int, default=None) ap.add_argument("--tau", type=float, default=0.9, help="flag confident disagreements above this") ap.add_argument("--budget", type=float, default=None, help="flag only top-X%% disagreements (overrides tau)") ap.add_argument("--path-error-rate", type=float, default=0.05, help="simulated pathologist error rate") ap.add_argument("--outdir", default="./qa_out") ap.add_argument("--no-pretrained", action="store_true") args = ap.parse_args() if not args.pcam and not args.synthetic: args.synthetic = True # safe default device = torch.device("cuda" if torch.cuda.is_available() else "cpu") torch.manual_seed(0) print(f"[PathQA] device={device} source={'PCam' if args.pcam else 'synthetic'}") # 1. data if args.pcam: train_dl, val_dl, test_dl = get_pcam_loaders( root=args.data_root, batch_size=args.batch_size, num_workers=2, subset=args.subset) else: train_dl, val_dl, test_dl = get_synthetic_loaders( n_train=args.syn_train, n_eval=args.syn_eval, batch_size=args.batch_size) # 2. model + fine-tune model = build_model("resnet18", pretrained=not args.no_pretrained).to(device) optim = torch.optim.Adam(model.parameters(), lr=args.lr) for ep in range(args.epochs): loss = train_one_epoch(model, train_dl, optim, device, args.max_train_batches) res = evaluate(model, val_dl, device, max_batches=args.max_train_batches) print(f"[train] epoch {ep+1}/{args.epochs} loss={loss:.3f} " f"val_acc={res.accuracy:.3f} val_auroc={res.auroc:.3f}") # 3. calibrate T = fit_temperature(model, val_dl, device, max_batches=args.max_train_batches) scaler = TemperatureScaler(); scaler.set_temperature(T) raw = evaluate(model, val_dl, device, max_batches=args.max_train_batches) cal = evaluate(model, val_dl, device, scaler=scaler, max_batches=args.max_train_batches) print(f"[calibrate] temperature T={T:.3f} val_loss raw={raw.loss:.3f} -> cal={cal.loss:.3f}") # 4. build a sign-out queue with simulated human error signout, truth = _inject_pathologist_labels(test_dl, args.path_error_rate, seed=7) class _ListLoader: def __init__(self, items): self.items = items def __iter__(self): return iter(self.items) # 5. QA second reader reader = SecondReader(model, scaler=scaler, device=device) report = reader.review_loader(_ListLoader(signout), tau=args.tau, workload_budget=args.budget) print("\n" + report.summary()) # How well did flagging catch the *injected* human errors? truth_t = torch.tensor(truth) caught = sum(1 for r, t in zip(report.reviews, truth) if r.flagged and r.pathologist_label != t) n_errors = int((truth_t != torch.tensor([r.pathologist_label for r in report.reviews])).sum()) if n_errors: print(f"\n[QA effectiveness] of {n_errors} simulated sign-out errors, " f"the second reader flagged {caught} ({caught/n_errors:.0%}) for re-check.") out = Path(args.outdir); out.mkdir(parents=True, exist_ok=True) report.to_json(str(out / "qa_report.json")) report.worklist_to_csv(str(out / "worklist.csv")) print(f"\n[saved] {out/'qa_report.json'} and {out/'worklist.csv'}") print("Reminder: PathQA outputs re-check recommendations only. It does not " "diagnose and does not change any sign-out. The pathologist decides.") if __name__ == "__main__": main()