Spaces:
Sleeping
Sleeping
File size: 8,861 Bytes
1024e04 | 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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | """One model at a time; preserve projection order and fail on incomplete ensembles."""
import gc
import math
import os
import threading
import torch
from safetensors.torch import load_file
from .architecture import SyntaxModel, artery_model, classifier_stream
from .dicom import InferenceError, inspect, read_video, validate_study
from .preprocessing import preprocess_classifier, preprocess_score, to_uint8
from .weights import MANIFEST, calibration, weight_file
_lock = threading.Lock()
def _device():
requested = os.environ.get("SYNTAX_DEVICE", "cpu").lower()
if requested == "cpu":
torch.set_num_threads(max(1, int(os.environ.get("SYNTAX_CPU_THREADS", "2"))))
return torch.device("cpu")
if requested == "cuda" and torch.cuda.is_available():
return torch.device("cuda")
# Projected LSTM support differs across MPS builds; no silent device fallback.
raise InferenceError("The configured inference device is unavailable. Use cpu or an available cuda device.")
def _load(factory, record, device, progress):
path = weight_file(record, progress)
model = factory()
try:
model.load_state_dict(load_file(str(path), device="cpu"), strict=True)
model.to(device).eval()
except Exception as exc:
raise InferenceError(f"The required checkpoint could not be loaded: {record['path']}.") from exc
return model
def _release(device):
gc.collect()
if device.type == "cuda":
torch.cuda.empty_cache()
def classify(paths, progress=None):
paths = [str(path) for path in paths]
records = [inspect(path) for path in paths]
eligible = [r for r in records if r["eligible"]]
outputs = []
if not eligible:
return [{"path": r["path"], "artery": "exclude", "probability": None,
"probability_right": None, "reason": "Unsupported DICOM or fewer than 10 usable frames"}
for r in records]
with _lock, torch.inference_mode():
device = _device()
model = _load(artery_model, MANIFEST["classifier"], device, progress)
try:
for index, record in enumerate(records):
if not record["eligible"]:
outputs.append({"path": record["path"], "artery": "exclude", "probability": None,
"probability_right": None, "reason": "Unsupported DICOM or fewer than 10 usable frames"})
continue
if progress:
progress("classify", {"current": index, "total": len(records),
"fraction": index / len(records), "message": "Identifying coronary artery"})
video = to_uint8(read_video(record["path"]))
logits = classifier_stream(model, len(video),
lambda start, stop: preprocess_classifier(video[start:stop]), device=device)
probability = float(torch.sigmoid(logits)[0, 0].cpu())
del video, logits
if not math.isfinite(probability):
raise InferenceError("The artery classifier returned a non-finite result.")
side = "left" if probability <= 0.1 else "right" if probability >= 0.9 else "unassigned"
outputs.append({"path": record["path"], "artery": side, "probability": probability,
"probability_right": probability,
"preprocessing": MANIFEST["preprocessing"]["classifier"],
"reason": "Review uncertain artery" if side == "unassigned" else None})
finally:
del model
_release(device)
if progress:
progress("classify", {"current": len(records), "total": len(records), "fraction": 1.0})
return outputs
def combine_folds(left, right, coefficients):
if len(left) != 5 or len(right) != 5 or len(coefficients) != 5:
raise InferenceError("The complete five-fold ensemble is required for each artery.")
if not all(math.isfinite(float(value)) for value in left + right):
raise InferenceError("The model returned a non-finite score.")
folds = []
for index, (lval, rval, coeff) in enumerate(zip(left, right, coefficients)):
raw = lval + rval
adjusted = coeff["a"] * raw + coeff["b"]
if not math.isfinite(adjusted):
raise InferenceError("Calibration returned a non-finite score.")
folds.append({"fold": index, "left": lval, "right": rval, "raw": raw,
"calibrated": adjusted, "a": coeff["a"], "b": coeff["b"]})
return {
"raw": max(0.0, sum(f["raw"] for f in folds) / 5),
"calibrated": max(0.0, sum(f["calibrated"] for f in folds) / 5),
"per_fold": folds,
}
def infer(left_paths, right_paths, progress=None):
left_paths, right_paths = list(map(str, left_paths)), list(map(str, right_paths))
records = validate_study(left_paths + right_paths)
complete = bool(left_paths and right_paths)
provenance = {
"repo_id": MANIFEST["repo_id"], "revision": MANIFEST["revision"],
"architecture": MANIFEST["architecture"], "precision": "float32",
"preprocessing": "32 center frames; repeat short clips; RGB grayscale; 256x256; ImageNet normalization",
"projection_order": "input order within each artery",
"calibration": "max(0, mean_i(a_i * (left_i + right_i) + b_i))",
"calibration_source": {"path": MANIFEST["calibration"]["path"],
"sha256": MANIFEST["calibration"]["sha256"],
"folds": MANIFEST["calibration"]["folds"]},
"ordered_inputs": {
"left": [{key: record[key] for key in ("sop_uid", "series_uid", "frames")}
for record in records[:len(left_paths)]],
"right": [{key: record[key] for key in ("sop_uid", "series_uid", "frames")}
for record in records[len(left_paths):]],
},
"weights": [],
}
predictions = {"left": [], "right": []}
total_steps = 5 * (len(left_paths) + len(right_paths))
completed_steps = 0
with _lock, torch.inference_mode():
device = _device()
provenance["device"] = str(device)
coefficients = calibration(progress)
for side, paths in (("left", left_paths), ("right", right_paths)):
if not paths:
continue
# One preprocessed clip at a time bounds activation memory. Each backbone
# is in eval mode, so per-projection feature extraction is equivalent to a batch.
for record in [r for r in MANIFEST["score_weights"] if r["side"] == side]:
model = _load(SyntaxModel, record, device, progress)
fold = record["fold"]
def report(current):
if progress:
progress("infer", {"side": side, "fold": fold, "current": completed_steps + current,
"total": total_steps, "fraction": (completed_steps + current) / total_steps,
"message": f"Processing {side} artery · model {fold + 1} of 5"})
try:
clips = (preprocess_score(read_video(path)) for path in paths)
output = model.forward_stream(clips, device=device, progress=report)
# Match canonical float32 torch.exp then float subtraction exactly.
value = float(torch.exp(output[0, 1]).cpu()) - 1.0
if not math.isfinite(value):
raise InferenceError("A model returned a non-finite artery score.")
predictions[side].append(value)
provenance["weights"].append({"path": record["path"], "sha256": record["sha256"]})
completed_steps += len(paths)
finally:
del model
_release(device)
result = combine_folds(predictions["left"], predictions["right"], coefficients) if complete else {
"raw": None, "calibrated": None, "per_fold": [],
}
result.update({
"complete": complete, "study_uid": records[0]["study_uid"],
"left": {"raw": sum(predictions["left"]) / 5 if left_paths else None,
"per_fold": predictions["left"], "projections": len(left_paths)},
"right": {"raw": sum(predictions["right"]) / 5 if right_paths else None,
"per_fold": predictions["right"], "projections": len(right_paths)},
"projection_count": len(records), "provenance": provenance,
"message": None if complete else "Incomplete study: both left and right coronary projections are required for a total SYNTAX estimate.",
})
return result
|