File size: 7,752 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
"""Reproducible real-checkpoint parity check against published study results.

Inputs are a fixture manifest [{"dataset": "philips_97", "study": <JSON record>}]
and CSVs from the original five-fold evaluation. DICOM paths are relative to
the manifest directory. No source files or checkpoints are modified.
"""
import argparse
import ast
import csv
import hashlib
import json
import os
import time
from pathlib import Path
from types import SimpleNamespace

from . import classify, infer


def canonical_cpu(study, base, source_root):
    """Execute the original source class/dataset, only disabling an unused download.

    Lightning training dependencies are substituted by nn.Module; the source
    constructor, checkpoint loading, forward, and dataset are unchanged.
    """
    import importlib.util
    import torch
    import typing
    import torch.nn.functional as F
    from safetensors.torch import load_file
    from torch import nn
    import torchvision.models.video as tvmv
    from torchvision.transforms import Resize
    from torchvision.transforms._transforms_video import ToTensorVideo
    from .weights import MANIFEST, weight_file
    class InferenceLightning(nn.Module):
        def save_hyperparameters(self):
            pass
    model_path = source_root / "full_model/rnn_model.py"
    source = model_path.read_text()
    tree = ast.parse(source)
    class_node = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "SyntaxLightningModule")
    torch.set_num_threads(max(1, int(os.environ.get("SYNTAX_CPU_THREADS", "2"))))
    namespace = {"pl": SimpleNamespace(LightningModule=InferenceLightning), "torch": torch, "nn": nn, "Any": typing.Any,
                 "F": F, "load_file": load_file,
                 "tvmv": SimpleNamespace(r3d_18=lambda **kw: tvmv.r3d_18(weights=None),
                                         R3D_18_Weights=tvmv.R3D_18_Weights)}
    exec(compile(ast.Module(body=[class_node], type_ignores=[]), str(model_path), "exec"), namespace)
    spec = importlib.util.spec_from_file_location("canonical_dataset", source_root / "full_model/rnn_dataset.py")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    def transform(x):
        x = Resize((256, 256), antialias=True)(ToTensorVideo()(x))
        return (x - torch.tensor([.485, .456, .406])[:, None, None, None]) / torch.tensor([.229, .224, .225])[:, None, None, None]
    predictions = {}
    with torch.inference_mode():
        for side in ("left", "right"):
            # __getitem__ only needs these attributes; avoid writing a temporary JSON.
            dataset = object.__new__(module.SyntaxDataset)
            dataset.dataset, dataset.base_dir = [study], base
            dataset.train, dataset.inference = False, True
            dataset.label, dataset.artery = "", side
            dataset.length, dataset.transform = 32, transform
            clips = dataset[0][0].unsqueeze(0)
            values = []
            for weight in [w for w in MANIFEST["score_weights"] if w["side"] == side]:
                model = namespace["SyntaxLightningModule"](num_classes=2, lr=1e-5, variant="lstm_mean",
                                                          pl_weight_path=weight_file(weight)).eval()
                output = model(clips)
                values.append(float(torch.exp(output[0, 1])) - 1.0)
                del model
            predictions[side] = values
    predictions["source_sha256"] = hashlib.sha256(source.encode()).hexdigest()
    return predictions


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--fixtures", type=Path, required=True)
    parser.add_argument("--predictions", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--classifier", action="store_true")
    parser.add_argument("--reference-source", type=Path)
    parser.add_argument("--resume", action="store_true", help="Reuse completed engine results and validate original CPU code")
    args = parser.parse_args()
    cases = json.loads(args.fixtures.read_text())
    previous = json.loads(args.output.read_text()) if args.resume and args.output.exists() else []
    report = []
    for case in cases:
        study = case["study"]
        base = args.fixtures.parent
        left = [str(base / v["path"]) for v in study["videos_left"]]
        right = [str(base / v["path"]) for v in study["videos_right"]]
        vendor = case["dataset"].split("_")[0]
        expected = next(row for row in csv.DictReader((args.predictions / f"{vendor}_predictions.csv").open())
                        if row["study_uid"] == study["study_uid"])
        start = time.monotonic()
        def progress(stage, detail):
            if stage == "infer" and detail["current"] % (len(left) + len(right)) == 0:
                print(f"{case['dataset']}: {detail['current']}/{detail['total']} projections", flush=True)
        saved = next((item for item in previous if item["study_uid"] == study["study_uid"]), None)
        result = saved["result"] if saved else infer(left, right, progress=progress)
        delta = abs(result["calibrated"] - float(expected["new_prediction"]))
        item = {**(saved or {}), "dataset": case["dataset"], "study_uid": study["study_uid"],
                "expected_calibrated": float(expected["new_prediction"]),
                "actual_calibrated": result["calibrated"], "absolute_difference": delta,
                "inference_seconds": saved["inference_seconds"] if saved else time.monotonic() - start, "result": result,
                "pass": delta < 0.01}
        print(json.dumps({k: v for k, v in item.items() if k != "result"}), flush=True)
        if args.reference_source:
            reference = canonical_cpu(study, base, args.reference_source)
            errors = [abs(a - b) for side in ("left", "right")
                      for a, b in zip(reference[side], result[side]["per_fold"])]
            item["canonical_cpu"] = reference
            item["canonical_cpu_max_fold_difference"] = max(errors)
            item["canonical_cpu_parity"] = max(errors) < 0.0001
            item["pass"] = item["pass"] and item["canonical_cpu_parity"]
            print(f"{case['dataset']}: original CPU max fold delta={max(errors)}", flush=True)
        if args.classifier:
            from .weights import MANIFEST
            paths = [str(base / v["path"]) for v in study["videos"]]
            classified = classify(paths)
            comparisons = []
            for source, actual in zip(study["videos"], classified):
                expected_side = "left" if source["artery_prob"] <= .1 else "right" if source["artery_prob"] >= .9 else "unassigned"
                comparisons.append({"filename": Path(source["path"]).name,
                                    "expected_probability_right": source["artery_prob"],
                                    "actual_probability_right": actual["probability_right"],
                                    "expected_artery": expected_side, "actual_artery": actual["artery"]})
            item["classifier"] = comparisons
            item["classifier_preprocessing"] = MANIFEST["preprocessing"]["classifier"]
            item["classifier_groups_match"] = all(c["expected_artery"] == c["actual_artery"] for c in comparisons)
            print(f"{case['dataset']}: classifier groups match={item['classifier_groups_match']}", flush=True)
        report.append(item)
        args.output.write_text(json.dumps(report, indent=2))
    if not all(item["pass"] and item.get("classifier_groups_match", True) for item in report):
        raise SystemExit("Reference parity failed; review the JSON report.")


if __name__ == "__main__":
    main()