File size: 3,075 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
"""Held-out evaluation of one fold: embeddings on a fixed 12 mm grid of slabs for every held-out case.

Writes WORK/eval/fold<F>/<case>.npz with
    z0                 slab centres
    teacher_full       teacher on the scanner routine-dose image (the target)
    raw_full, raw_low  encoder on denoised measurements at routine and at the supplied low dose
    teacher_low        teacher on the scanner's own low-dose image, where image_low.npy exists
(each slab embedding (n, 512); regional embeddings with suffix _regions, (n, 16, 512)).

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

import argparse
from pathlib import Path

import numpy as np
import torch

from . import dist
from .bank import bank_dir
from .data import load_cohort
from .models import load_teacher, teach
from .train_encoder import BankSlabs, load


@torch.inference_mode()
def embed(fn, xs, batch=16):
    s, r = [], []
    for i in range(0, len(xs), batch):
        u, w = fn(torch.stack(xs[i : i + batch]))
        s.append(u.float().cpu().numpy())
        r.append(w.float().cpu().numpy().astype(np.float16))
    return np.concatenate(s), np.concatenate(r)


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, model = load_teacher(a.teacher, device), load(work, a.fold, device)
    out = work / "eval" / f"fold{a.fold}"
    out.mkdir(parents=True, exist_ok=True)

    def run_encoder(x):
        with torch.autocast("cuda", dtype=torch.bfloat16):
            return model(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
        src = BankSlabs(case, bank_dir(work, a.fold, cid))
        z = case.grid()
        res = {"z0": z}
        res["teacher_full"], res["teacher_full_regions"] = embed(run_teacher, [case.image_slab(z0) for z0 in z])
        res["raw_full"], res["raw_full_regions"] = embed(run_encoder, [src.slab(z0, 0.0) for z0 in z])
        if src.has("low", 1):
            res["raw_low"], res["raw_low_regions"] = embed(run_encoder, [src.slab(z0, 1.0) for z0 in z])
        if case.has("image_low"):
            res["teacher_low"], res["teacher_low_regions"] = embed(run_teacher, [case.image_slab(z0, dose="low") for z0 in z])
        np.savez_compressed(path, **res)
        print(f"[rank {rank}] evaluated fold {a.fold}: {cid} ({len(z)} slabs)", flush=True)
    dist.done(sync=False)


if __name__ == "__main__":
    main()