File size: 5,924 Bytes
76eb7b3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | """Train the measurement denoiser for one cross-validation fold.
Reduced-dose line integrals -> routine-dose line integrals of the same acquisition. Training
spans a continuous dose range by scaling the supplied noise (proj_low - proj_full) to a random
dose fraction, and optionally keeps only every 2nd, 4th or 8th view (sparse acquisitions).
Loss: L1 on the line integrals plus L1 after a ramp filter along detector columns.
torchrun --nproc_per_node 8 -m proj2rep train-denoiser --data DATA --work WORK --fold 0
"""
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 .data import load_cohort
from .models import CLIP, Denoiser, ramp_columns, short_ramp
CROP = (24, 32, 512) # views, rows, columns
def noise_scale(supplied, fraction):
"""Multiple of the supplied noise whose variance matches `fraction` of routine dose."""
return float(np.sqrt((1 / fraction - 1) / (1 / supplied - 1)))
class Crops(Dataset):
"""Random crops of one fixed shape from every case, so scanners with different detectors batch together."""
def __init__(self, cases, n, seed, min_dose, views):
self.cases, self.n, self.seed, self.min_dose, self.views = cases, n, tuple(seed), min_dose, views
shapes = np.array([c.array("proj_full").shape for c in cases])
cols = min(CROP[2], int(shapes[:, 2].min()))
self.shape = (CROP[0], min(CROP[1], int(shapes[:, 1].min())), cols - cols % 2)
def __len__(self):
return self.n
def __getitem__(self, i):
rng = np.random.default_rng((*self.seed, i))
case = self.cases[rng.integers(len(self.cases))]
full, low = case.array("proj_full"), case.array("proj_low")
nv, nr, nc = self.shape
k = int(rng.choice([k for k in self.views if nv * k <= full.shape[0]] or [1]))
v = int(rng.integers(0, full.shape[0] - nv * k + 1))
r, c = int(rng.integers(0, full.shape[1] - nr + 1)), int(rng.integers(0, full.shape[2] - nc + 1))
s = (slice(v, v + nv * k, k), slice(r, r + nr), slice(c, c + nc))
y, x = torch.from_numpy(full[s].astype(np.float32)), torch.from_numpy(low[s].astype(np.float32))
f = float(np.exp(rng.uniform(np.log(self.min_dose), np.log(0.6))))
a = 0.0 if rng.random() < 0.1 else noise_scale(case.low_dose_fraction, f)
x = y + a * (x - y)
for d in (0, 1, 2):
if rng.random() < 0.5:
x, y = x.flip(d), y.flip(d)
return x[None], y[None]
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("--steps", type=int, default=8000)
p.add_argument("--batch", type=int, default=8, help="global batch (split across GPUs)")
p.add_argument("--lr", type=float, default=3e-4)
p.add_argument("--min-dose", type=float, default=0.02, help="lowest simulated dose fraction")
p.add_argument("--views", type=int, nargs="+", default=[1, 1, 2, 4, 8], help="view-keeping factors to draw from")
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)
cases = [c for c in cohort.cases(train, image=False) if c.has("proj_low") and c.low_dose_fraction]
if not cases:
raise SystemExit("no training case has proj_low and low_dose_fraction")
out = work / "denoiser"
out.mkdir(parents=True, exist_ok=True)
torch.manual_seed(a.fold + 1)
model = Denoiser().to(device)
if world > 1:
model = DDP(model, device_ids=[device.index])
opt = torch.optim.AdamW(model.parameters(), a.lr, weight_decay=1e-4)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, a.lr, total_steps=a.steps, pct_start=0.05)
per = max(a.batch // world, 1)
data = Crops(cases, a.steps * per, (a.fold + 1, rank), a.min_dose, a.views)
loader = DataLoader(data, per, num_workers=a.workers, drop_last=True, persistent_workers=a.workers > 0)
kernel = short_ramp(device)
dist.log(rank, f"fold {a.fold}: {len(cases)} training cases, {world} GPU(s), batch {per}/GPU")
start, hist = time.time(), []
for step, (x, y) in enumerate(loader):
x, y = x.to(device), y.to(device).clamp(-1, CLIP)
with torch.autocast("cuda", dtype=torch.bfloat16):
pred = model(x).float()
loss = F.l1_loss(pred, y) + F.l1_loss(ramp_columns(pred, kernel), ramp_columns(y, kernel))
opt.zero_grad(set_to_none=True)
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
sched.step()
hist.append(loss.item())
if step % 100 == 99:
dist.log(rank, f"denoiser fold {a.fold} step {step + 1} loss {np.mean(hist[-100:]):.4f} {time.time() - start:.0f}s")
if rank == 0:
net = model.module if world > 1 else model
torch.save(net.state_dict(), out / f"fold{a.fold}.pt")
(out / f"fold{a.fold}.json").write_text(json.dumps({"steps": a.steps, "batch": a.batch, "cases": len(cases),
"seconds": time.time() - start}, indent=1) + "\n") # fmt: skip
dist.done()
def load(work, fold, device):
model = Denoiser().to(device)
model.load_state_dict(torch.load(Path(work) / "denoiser" / f"fold{fold}.pt", map_location=device, weights_only=True))
return model.eval()
if __name__ == "__main__":
main()
|