"""Train the measurement encoder for one cross-validation fold. Input: a 36 mm slab of the denoised back-projection (from `proj2rep bank`) at a random dose level and view fraction. Target: the frozen teacher's slab and regional embeddings of the scanner's routine-dose image of the same slab. The encoder starts from the teacher's weights. Both inputs get the same random mirror, in-plane zoom and shift. Half of the slabs are placed with an edge on a slice position, as the evaluation grid is (--snap-z). Multi-GPU: DistributedDataParallel with synchronised BatchNorm; each GPU draws its own slabs. Training state is saved every --save-every steps and resumed automatically. torchrun --nproc_per_node 8 -m proj2rep train-encoder --data DATA --work WORK --fold 0 --teacher ct_fm.safetensors """ import argparse import json import time from pathlib import Path import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader, Dataset from . import dist from .bank import bank_dir from .data import HALF, group_of, load_cohort, slab_rows, to_input from .models import Encoder, load_teacher, teach class BankSlabs: """Denoised back-projections of one case at the levels and view fractions on disk.""" def __init__(self, case, folder): self.case, self.dir, self.z, self.files = case, folder, np.load(folder / "z_mm.npy"), {} def vol(self, level, k): if (level, k) not in self.files: self.files[level, k] = np.load(self.dir / f"{level}_v{k}.npy", mmap_mode="r") return self.files[level, k] def has(self, level, k): return (self.dir / f"{level}_v{k}.npy").exists() def slab(self, z0, u=0.0, k=1, mirror=False): """Dose position u: 0 routine, 1 supplied low dose, 2 lowest level; linear in between.""" rows, flip = slab_rows(self.z, z0) def get(level): return torch.from_numpy(np.array(self.vol(level, k)[rows], dtype=np.float32)) if u <= 0: x = get("full") elif u <= 1: x = get("full") x = x + u * (get("low") - x) else: x = get("low") x = x + (u - 1) * (get("min") - x) x = to_input(x.flip(0) if flip else x) return x.flip(-1) if mirror else x class Slabs(Dataset): def __init__(self, sources, n, seed, a, offset=0): """Sample i is drawn from seed and offset + i, so a resumed run continues the same stream.""" self.sources, self.n, self.seed, self.a, self.offset = sources, n, seed, a, offset def __len__(self): return self.n def __getitem__(self, i): a, rng = self.a, np.random.default_rng((*self.seed, self.offset + i)) src = self.sources[rng.integers(len(self.sources))] lo, hi = src.case.slab_range z0, mirror = snap(rng.uniform(lo, hi), src.z, lo, hi, rng.random() < a.snap_z), bool(rng.integers(2)) views = [k for k in a.views if src.has("full", k)] if not group_of(src.case, a.no_thin) else [1] views = views or [1] k = int(rng.choice(views, p=view_weights(views))) top = a.max_dose_level if k == 1 else min(a.max_dose_level, 1.0) if not src.has("low", k): top = 0.0 if top > 1 and not src.has("min", 1): top = 1.0 u = 0.0 if rng.random() < a.clean else float(rng.uniform(0, top)) return src.slab(z0, u, k, mirror), src.case.image_slab(z0, mirror) def snap(z0, z, lo, hi, on=True): """Nearest slab centre whose edge lies exactly on a slice position. Evaluation slabs start at the first slice, so their edges fall on slices whenever the slice spacing divides the slab length, and such a slab holds one slice more than a slab at a random position. Training half of the slabs this way keeps both kinds in distribution. """ if not on: return z0 edge = np.concatenate([z + HALF, z - HALF]) edge = edge[(edge >= lo) & (edge <= hi)] return float(edge[np.abs(edge - z0).argmin()]) if len(edge) else z0 def view_weights(views): """All views (k = 1) on 40% of slabs, the thinned fractions sharing the rest.""" if len(views) == 1: return None w = np.array([0.4 if k == 1 else 0.6 / (len(views) - (1 in views)) for k in views]) return w / w.sum() def field_of_view(x, y, gen, zoom=(0.8, 1.2), move=0.2): """Same random in-plane zoom and shift for input and target; half of the batch unchanged.""" n = len(x) scale = torch.where(torch.rand(n, generator=gen) < 0.5, torch.ones(n), torch.empty(n).uniform_(*zoom, generator=gen)) shift = (torch.rand(n, 2, generator=gen) - 0.5) * move * (scale != 1)[:, None] theta = torch.zeros(n, 3, 4) theta[:, 0, 0], theta[:, 1, 1], theta[:, 2, 2] = scale, scale, 1 theta[:, 0, 3], theta[:, 1, 3] = shift[:, 0], shift[:, 1] g = F.affine_grid(theta.to(x.device), x.shape, align_corners=False) return F.grid_sample(x, g, align_corners=False), F.grid_sample(y, g, align_corners=False) def target_stats(teacher, sources, n, device, seed): """Mean and spread of the teacher embeddings, for a balanced loss across features.""" rng = np.random.default_rng(seed) s, r = [], [] for _ in range(n // 8): xs = [] for _ in range(8): src = sources[rng.integers(len(sources))] lo, hi = src.case.slab_range xs.append(src.case.image_slab(rng.uniform(lo, hi))) u, w = teach(teacher, torch.stack(xs).to(device)) s.append(u) r.append(w.flatten(0, 1)) s, r = torch.cat(s), torch.cat(r) return torch.stack([s.mean(0), s.std(0).clamp_min(1e-4), r.mean(0), r.std(0).clamp_min(1e-4)]) def main(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--data", required=True) p.add_argument("--work", required=True) p.add_argument("--fold", type=int, required=True, help="cross-validation fold; -1 trains on every case") p.add_argument("--teacher", required=True, help="CT-FM feature extractor weights (.safetensors)") p.add_argument("--steps", type=int, default=16000) p.add_argument("--batch", type=int, default=16, help="global batch (split across GPUs)") p.add_argument("--lr", type=float, default=1e-4) p.add_argument("--views", type=int, nargs="+", default=[1, 2, 4, 8], help="view fractions to train on") p.add_argument("--max-dose-level", type=float, default=1.0, help="1: down to the supplied low dose; 2: down to the bank's min level") p.add_argument("--clean", type=float, default=0.15, help="share of slabs at routine dose") p.add_argument("--no-thin", nargs="*", default=[], help="REGION:MANUFACTURER groups trained at all views only") p.add_argument("--snap-z", type=float, default=0.5, help="share of slabs placed with an edge exactly on a slice") p.add_argument("--stats", type=int, default=800, help="slabs used for the target statistics") p.add_argument("--save-every", type=int, default=500) p.add_argument("--workers", type=int, default=8) a = p.parse_args(argv) rank, world, device = dist.init() work = Path(a.work) cohort = load_cohort(a.data, work_dir=work) train, _ = cohort.split(a.fold) sources = [BankSlabs(c, bank_dir(work, a.fold, c.id)) for c in cohort.cases(train)] missing = [s.case.id for s in sources if not s.has("full", 1)] if missing: raise SystemExit(f"no bank for {len(missing)} training cases (e.g. {missing[0]}); run `proj2rep bank --fold {a.fold}` first") if 1 not in a.views: raise SystemExit("--views must include 1 (all views)") out = work / "encoder" out.mkdir(parents=True, exist_ok=True) name, resume = f"fold{a.fold}", out / f"fold{a.fold}.resume.pt" teacher = load_teacher(a.teacher, device) stats = torch.zeros(4, 512, device=device) if rank == 0: stats = target_stats(teacher, sources, max(a.stats, 64), device, a.fold + 1) sm, ss, rm, rs = dist.broadcast(stats) torch.manual_seed(a.fold + 1) model = Encoder(a.teacher).to(device) if world > 1: model = nn.SyncBatchNorm.convert_sync_batchnorm(model) model = model.to(memory_format=torch.channels_last_3d) opt = torch.optim.AdamW(model.parameters(), a.lr, weight_decay=0.01) sched = torch.optim.lr_scheduler.OneCycleLR(opt, a.lr, total_steps=a.steps, pct_start=0.05) gen = torch.Generator() first = 0 if resume.exists(): state = torch.load(resume, map_location=device, weights_only=False) if state.get("steps", a.steps) != a.steps or state.get("batch", a.batch) != a.batch: raise SystemExit( f"{resume} was saved with --steps {state.get('steps')} --batch {state.get('batch')}; use the same or delete it" ) model.load_state_dict(state["model"]) opt.load_state_dict(state["opt"]) sched.load_state_dict(state["sched"]) first = state["step"] dist.log(rank, f"resumed {resume} at step {first}") net = DDP(model, device_ids=[device.index]) if world > 1 else model per = max(a.batch // world, 1) data = Slabs(sources, (a.steps - first) * per, (a.fold + 1, rank), a, offset=first * per) loader = DataLoader( data, per, num_workers=a.workers, drop_last=True, persistent_workers=a.workers > 0, prefetch_factor=4 if a.workers else None ) dist.log(rank, f"encoder fold {a.fold}: {len(sources)} training cases, {world} GPU(s), batch {per}/GPU, steps {first}..{a.steps}") net.train() start, hist = time.time(), [] for step, (x, image) in enumerate(loader, start=first): gen.manual_seed(1_000_003 * (a.fold + 1) + 1000 * step + rank) # per-step seed: identical after a resume x, image = field_of_view(x.to(device), image.to(device), gen) ts, tr = teach(teacher, image) with torch.autocast("cuda", dtype=torch.bfloat16): ps, pr = net(x) loss = F.mse_loss((ps - sm) / ss, (ts - sm) / ss) + F.mse_loss((pr - rm) / rs, (tr - rm) / rs) opt.zero_grad(set_to_none=True) loss.backward() nn.utils.clip_grad_norm_(net.parameters(), 5.0) opt.step() sched.step() hist.append(loss.item()) if step % 100 == 99: dist.log(rank, f"encoder fold {a.fold} step {step + 1} loss {np.mean(hist[-100:]):.4f} {time.time() - start:.0f}s") if (step + 1) % a.save_every == 0 and step + 1 < a.steps and rank == 0: torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "sched": sched.state_dict(), "step": step + 1, "steps": a.steps, "batch": a.batch}, resume.with_suffix(".tmp")) # fmt: skip resume.with_suffix(".tmp").replace(resume) if rank == 0: # SyncBatchNorm keeps BatchNorm's parameter names, so the weights load into a plain Encoder torch.save(model.state_dict(), out / f"{name}.pt") resume.unlink(missing_ok=True) meta = {k: v for k, v in vars(a).items() if k not in ("data", "work", "teacher")} (out / f"{name}.json").write_text( json.dumps({**meta, "cases": len(sources), "gpus": world, "seconds": time.time() - start}, indent=1) + "\n" ) dist.done() def load(work, fold, device): model = Encoder().to(device) model.load_state_dict(torch.load(Path(work) / "encoder" / f"fold{fold}.pt", map_location=device, weights_only=True)) return model.eval().to(memory_format=torch.channels_last_3d) if __name__ == "__main__": main()