Proj2Rep-CTFM / infer.py
markjiang1's picture
Optimized release: verified metadata, download instructions and package structure
76eb7b3
Raw History Blame Contribute Delete
9.46 kB
"""Proj2Rep: infer one draw of a CT projection encoder or apply its readout to archived base features."""
import argparse
import hashlib
import json
import os
import tempfile
from pathlib import Path
import numpy as np
from readout import predict
class Bundle:
def __init__(self, path):
self.path = path
self.manifest = json.loads((path / "manifest.json").read_text())
def checked(self, name):
path = self.path / name
with path.open("rb") as source:
digest = hashlib.file_digest(source, "sha256").hexdigest()
if digest != self.manifest["sha256"][name]:
raise ValueError(f"asset digest mismatch: {name}")
return path
def saved_features(args, bundle):
assets = bundle.manifest["manufacturers"][args.manufacturer]
expected = bundle.manifest["sha256"][assets["base"]]
with np.load(args.input, allow_pickle=False) as data:
if "patient" in data and len(np.unique(data["patient"])) != 1:
raise ValueError("supply one patient per input archive")
if "region" in data and str(data["region"].item()) != args.region:
raise ValueError("archived region differs from requested region")
if (
args.key in ("slab", "base_slab")
and "model" in data
and args.key != "base_slab"
):
raise ValueError("use base_slab from adapter output to apply another draw")
internal = str(data["base_sha256"].item()) if "base_sha256" in data else None
if internal and args.base_sha256 and internal != args.base_sha256:
raise ValueError("conflicting input and command-line base digests")
if (internal or args.base_sha256) != expected:
raise ValueError(
"specify the SHA-256 of the matching unadapted base encoder"
)
if (
"view_stride" in data
and int(data["view_stride"].item()) != args.view_stride
):
raise ValueError("input acquisition stride differs from requested stride")
if (
args.key.startswith("raw_views_")
and args.key != f"raw_views_{args.view_stride}"
):
raise ValueError("archive key and requested angular stride differ")
if (
args.key.startswith("raw_dose") or args.key in ("raw_full", "raw_low")
) and args.view_stride != 1:
raise ValueError("dose arrays use full angular sampling")
x, z = data[args.key], data["z0"]
return x, z
def infer_scan(args, bundle):
import torch
from proj2rep.data import Case, slab_rows, to_input
from proj2rep.geometry import Conventions, Geometry, reconstruct, sparse
from proj2rep.models import Denoiser, Encoder, denoise_scan
if args.view_stride > 1 and (args.source != "routine" or args.model != "adapter"):
raise ValueError(
"sparse-view inference requires routine projections and the adapter model"
)
if args.source == "routine-bank" and args.model != "adapter":
raise ValueError(
"refined routine inference already uses the rounded bank convention"
)
case = Case(args.case.parent, args.case.name)
vendor = case.manufacturer.upper()
args.manufacturer = next(
(
name
for name in bundle.manifest["manufacturers"]
if vendor.startswith(name.upper())
),
None,
)
if args.manufacturer is None:
raise ValueError(f"no packaged model for {vendor}")
assets = bundle.manifest["manufacturers"][args.manufacturer]
encoder_name = (
assets["base"] if args.model == "adapter" else assets["refined"][str(args.draw)]
)
device = torch.device(args.device)
if device.type != "cuda" or not torch.cuda.is_available():
raise ValueError("scan inference requires a CUDA device supporting bfloat16")
with torch.cuda.device(device):
if not torch.cuda.is_bf16_supported():
raise ValueError("scan inference requires CUDA bfloat16 support")
def load(module, name):
module.load_state_dict(
torch.load(bundle.checked(name), map_location="cpu", weights_only=True)
)
return module.to(device).eval().requires_grad_(False)
with torch.inference_mode():
dn = load(Denoiser(), assets["denoiser"])
enc = load(Encoder(), encoder_name).to(memory_format=torch.channels_last_3d)
geo = Geometry(case)
zs, z = geo.image_z[geo.valid()], case.grid()
if not len(z):
raise ValueError("scan covers no complete 36-mm slab")
if args.slab_index is not None:
z = z[args.slab_index]
convention = Conventions(bundle.checked("convention.json"))(geo)
views = case.array("proj_low" if args.source == "supplied" else "proj_full")
if views.shape != (len(geo.angle), geo.rows, geo.cols) or len(geo.z) != len(
geo.angle
):
raise ValueError("projections and original per-view geometry disagree")
stride = args.view_stride
geometry = sparse(geo, stride) if stride > 1 else geo
measurements = np.ascontiguousarray(views[::stride], dtype=np.float32)
denoised = denoise_scan(dn, measurements, device)
del measurements
vol = reconstruct(geometry, denoised, zs, device, convention)
if args.model == "refined" or args.source in ("supplied", "routine-bank"):
vol = vol.clamp(-2000, 6000).round().short()
out = []
for centre in z:
rows, flip = slab_rows(zs, centre)
slab = vol[rows].float()
x = to_input(slab.flip(0) if flip else slab)[None].contiguous(
memory_format=torch.channels_last_3d
)
with torch.autocast("cuda", dtype=torch.bfloat16):
out.append(enc(x)[0][0].cpu().numpy())
return np.stack(out), z, encoder_name
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--root",
type=Path,
default=Path(__file__).resolve().parent,
help="unpacked model bundle",
)
shared = argparse.ArgumentParser(add_help=False)
shared.add_argument("--region", choices=("chest", "abdomen"), required=True)
shared.add_argument("--draw", type=int, choices=(0, 1), required=True)
shared.add_argument("--view-stride", type=int, choices=(1, 2, 4, 8), required=True)
shared.add_argument("--output", type=Path, required=True)
modes = parser.add_subparsers(dest="mode", required=True)
scan = modes.add_parser("scan", parents=[shared])
scan.add_argument("--case", type=Path, required=True)
scan.add_argument(
"--source", choices=("routine", "supplied", "routine-bank"), default="routine"
)
scan.add_argument("--model", choices=("adapter", "refined"), required=True)
scan.add_argument("--device", default="cuda:0")
scan.add_argument(
"--slab-index",
type=int,
nargs="+",
help="optional zero-based indices on the full physical grid",
)
features = modes.add_parser("features", parents=[shared])
features.add_argument("--input", type=Path, required=True)
features.add_argument("--key", required=True)
features.add_argument(
"--base-sha256", help="required for archives without embedded base_sha256"
)
features.add_argument("--manufacturer", choices=("GE", "Siemens"), required=True)
args = parser.parse_args()
if args.output.exists():
parser.error(f"output already exists: {args.output}")
bundle = Bundle(args.root)
if args.mode == "scan":
x, z, encoder = infer_scan(args, bundle)
else:
args.model = "adapter"
x, z = saved_features(args, bundle)
encoder = bundle.manifest["manufacturers"][args.manufacturer]["base"]
values = {
"z0": z,
"manufacturer": args.manufacturer,
"region": args.region,
"model": args.model,
"draw": args.draw,
"view_stride": args.view_stride,
"encoder_sha256": bundle.manifest["sha256"][encoder],
}
if z.shape != (len(x),) or not np.isfinite(z).all() or not np.isfinite(x).all():
raise ValueError("invalid slab features or z0")
if args.mode == "scan":
values.update(case_id=args.case.name, source=args.source)
if args.model == "adapter":
assets = bundle.manifest["manufacturers"][args.manufacturer]
key = assets["heads"][args.region][str(args.draw)]
with np.load(bundle.checked(key), allow_pickle=False) as head:
metadata = json.loads(head["metadata"].item())
if metadata["sha256"] != values["encoder_sha256"]:
raise ValueError("readout and base encoder digests disagree")
values.update(
slab=predict(head, x, args.view_stride),
base_slab=x,
base_sha256=values["encoder_sha256"],
readout_sha256=bundle.manifest["sha256"][key],
)
else:
values["slab"] = x
args.output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=args.output.parent, suffix=".npz") as tmp:
np.savez_compressed(tmp, **values)
tmp.flush()
os.link(tmp.name, args.output)
print(f"{args.output}: {len(x)} slabs")
if __name__ == "__main__":
main()