File size: 4,451 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
"""Stress test of one fold's held-out cases: lower dose and fewer views than routine.

Two routes per condition, both scored against the teacher on the routine-dose scanner image:
    raw     measurements -> fold denoiser -> back-projection -> fold encoder
    plain   measurements -> back-projection -> frozen teacher (reconstruct, then encode)
Dose levels are reached by scaling the supplied noise (proj_low - proj_full) to the target dose
fraction. View conditions keep every k-th view of the routine-dose scan.

    torchrun --nproc_per_node 8 -m proj2rep stress --data DATA --work WORK --fold 0 --teacher ct_fm.safetensors
"""

import argparse
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F

from . import dist
from .data import load_cohort, slab_rows, to_input
from .evaluate import embed
from .geometry import SIZE, Conventions, Geometry, reconstruct, sparse
from .models import denoise_scan, load_teacher, teach
from .train_denoiser import load as load_denoiser
from .train_denoiser import noise_scale
from .train_encoder import load as load_encoder

DOSES = (1.0, 0.25, 0.1, 0.05, 0.025)
VIEWS = (2, 4, 8)


def conditions(case):
    out = [("views", k) for k in VIEWS]
    if case.has("proj_low") and case.low_dose_fraction:
        out = [("dose", d) for d in DOSES] + out
    else:
        out = [("dose", 1.0)] + out
    return out


def label(kind, value):
    return f"{kind}_{value:g}"


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)
    p.add_argument("--teacher", required=True)
    a = p.parse_args(argv)

    rank, world, device = dist.init()
    work = Path(a.work)
    cohort = load_cohort(a.data, work_dir=work)
    _, held = cohort.split(a.fold)
    teacher, enc, dn = load_teacher(a.teacher, device), load_encoder(work, a.fold, device), load_denoiser(work, a.fold, device)
    conv = Conventions(work / "convention.json")
    out = work / "stress" / f"fold{a.fold}"
    out.mkdir(parents=True, exist_ok=True)

    def run_encoder(x):
        with torch.autocast("cuda", dtype=torch.bfloat16):
            return enc(x.to(device).contiguous(memory_format=torch.channels_last_3d))

    def run_teacher(x):
        return teach(teacher, x.to(device))

    for case in cohort.cases(held)[rank::world]:
        cid = case.id
        path = out / f"{cid}.npz"
        if path.exists():
            continue
        geo = Geometry(case)
        zs = geo.image_z[geo.valid()]
        z = case.grid()
        res = {"z0": z, "teacher_full": embed(run_teacher, [case.image_slab(z0) for z0 in z])[0]}
        # Where the scanner image holds padding instead of data (outside its reconstruction circle),
        # the plain route is blanked too, so both of the teacher's inputs cover the same field.
        scanner = torch.from_numpy(np.asarray(case.array("image_full")[geo.valid()], dtype=np.float32))
        blank = (F.interpolate(scanner[:, None], (SIZE, SIZE), mode="area")[:, 0] < -1500).to(device)
        full = np.asarray(case.array("proj_full"), dtype=np.float32)
        noise = np.asarray(case.array("proj_low"), dtype=np.float32) - full if case.has("proj_low") else None
        for kind, value in conditions(case):
            if kind == "dose":
                s = 0.0 if value == 1 else noise_scale(case.low_dose_fraction, value)
                g, data = geo, (full + s * noise if s else full)
            else:
                g, data = sparse(geo, value), np.ascontiguousarray(full[::value])
            for route, vol in (("raw", reconstruct(g, denoise_scan(dn, data, device), zs, device, conv(geo))),
                               ("plain", reconstruct(g, data, zs, device, conv(geo)).masked_fill(blank, -1024))):  # fmt: skip
                slabs = []
                for z0 in z:
                    rows, flip = slab_rows(zs, z0)
                    x = vol[rows].float().cpu()
                    slabs.append(to_input(x.flip(0) if flip else x))
                res[f"{route}_{label(kind, value)}"] = embed(run_encoder if route == "raw" else run_teacher, slabs)[0]
        np.savez_compressed(path, **res)
        print(f"[rank {rank}] stress fold {a.fold}: {cid}", flush=True)
    dist.done(sync=False)


if __name__ == "__main__":
    main()