File size: 6,084 Bytes
da6986a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Loaded-model wrapper + classify helpers. All in-process; no subprocess."""
from __future__ import annotations
from pathlib import Path
from typing import Dict

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

from heg_brep.model import HalfEdgeGNN, resolve_reject_label
from heg_brep.graph_data import load_coedge_arrays, make_heterodata


def _align_2d(x: np.ndarray, target_dim: int) -> np.ndarray:
    cur = int(x.shape[1])
    if cur == target_dim:
        return x
    if cur > target_dim:
        return x[:, :target_dim]
    pad = np.zeros((x.shape[0], target_dim - cur), dtype=x.dtype)
    return np.concatenate([x, pad], axis=1)


def _align_1d(x: np.ndarray, target_dim: int) -> np.ndarray:
    cur = int(x.shape[0])
    if cur == target_dim:
        return x
    if cur > target_dim:
        return x[:target_dim]
    pad = np.zeros((target_dim - cur,), dtype=x.dtype)
    return np.concatenate([x, pad], axis=0)


class LoadedModel:
    """A pass1 / elbow / tee checkpoint loaded into memory once."""

    def __init__(self, ckpt_path: Path, device: str = "cpu"):
        try:
            ckpt = torch.load(str(ckpt_path), map_location="cpu", weights_only=False)
        except TypeError:
            ckpt = torch.load(str(ckpt_path), map_location="cpu")
        if "global_in" not in ckpt or "gating_dim" not in ckpt:
            raise RuntimeError(f"Checkpoint {ckpt_path} missing gating metadata.")
        stats = ckpt["stats"]
        if not all(k in stats for k in ("coedge", "face", "edge")):
            raise RuntimeError(f"Checkpoint {ckpt_path} missing heterograph stats.")
        coedge_in = ckpt.get("coedge_in", ckpt.get("node_in"))
        face_in = ckpt.get("face_in")
        edge_in = ckpt.get("edge_in")
        if coedge_in is None or face_in is None or edge_in is None:
            raise RuntimeError(f"Checkpoint {ckpt_path} missing input dims.")
        labels = ckpt["labels"]
        model = HalfEdgeGNN(
            coedge_in=coedge_in, face_in=face_in, edge_in=edge_in,
            global_in=ckpt["global_in"], hidden=ckpt["hp"]["hidden"],
            layers=ckpt["hp"]["layers"], dropout=ckpt["hp"]["dropout"],
            num_classes=len(labels), gating_dim=ckpt["gating_dim"],
        ).to(device)
        model.load_state_dict(ckpt["state_dict"])
        model.eval()
        self.model = model
        self.device = device
        self.coedge_in = int(coedge_in)
        self.face_in = int(face_in)
        self.edge_in = int(edge_in)
        self.global_in = int(ckpt["global_in"])
        self.stats = stats
        self.labels = labels
        self.inv_labels = {v: k for k, v in labels.items()}
        self.reject_label = resolve_reject_label(labels, None)

    @torch.no_grad()
    def predict(self, npz_path: Path, min_conf: float = 0.0, tau: float = 0.0) -> Dict[str, object]:
        g = load_coedge_arrays(npz_path)
        g["coedge_x"] = _align_2d(g["coedge_x"], self.coedge_in)
        g["face_x"]   = _align_2d(g["face_x"],   self.face_in)
        g["edge_x"]   = _align_2d(g["edge_x"],   self.edge_in)
        g["global_x"] = _align_1d(g["global_x"], self.global_in)
        data = make_heterodata(
            g["coedge_x"], g["face_x"], g["edge_x"],
            g["next"], g["mate"], g["coedge_face"], g["coedge_edge"],
            g["global_x"], label=None, norm_stats=self.stats,
        )
        data["coedge"].batch = torch.zeros(data["coedge"].x.size(0), dtype=torch.long)
        data["global"].batch = torch.zeros(1, dtype=torch.long)
        data["face"].batch   = torch.zeros(data["face"].x.size(0), dtype=torch.long)
        data["edge"].batch   = torch.zeros(data["edge"].x.size(0), dtype=torch.long)
        logits = self.model(data.to(self.device))
        probs = F.softmax(logits, dim=-1).cpu().numpy()[0]
        pred = int(probs.argmax())
        conf = float(probs[pred])
        argmax_label = self.inv_labels[pred]
        effective_tau = max(tau, min_conf)
        if conf < effective_tau and self.reject_label is not None:
            predicted_label = self.reject_label
        else:
            predicted_label = argmax_label
        return {
            "argmax_label": argmax_label,
            "argmax_conf": conf,
            "predicted_label": predicted_label,
        }


ELBOW_ROUTES = {"elbow"}
TEE_ROUTES = {"tee"}


class TwoPassClassifier:
    """Convenience wrapper that owns all three models and routes pass1 → pass2."""

    def __init__(self, pass1: LoadedModel,
                 elbow: "LoadedModel | None",
                 tee:   "LoadedModel | None",
                 pass2_min_conf: float = 0.85,
                 pass2_tau: float = 0.0):
        self.pass1 = pass1
        self.elbow = elbow
        self.tee = tee
        self.pass2_min_conf = pass2_min_conf
        self.pass2_tau = pass2_tau

    def classify_npz(self, npz_path: Path) -> Dict[str, object]:
        p1 = self.pass1.predict(npz_path, min_conf=0.0, tau=0.0)
        route = str(p1["argmax_label"]).strip().lower()
        out = {
            "pass1_argmax": p1["argmax_label"],
            "pass1_conf": float(p1["argmax_conf"]),
            "route": route,
            "pass2_argmax": "",
            "pass2_predicted": "",
            "pass2_conf": None,
            "final_label": "",
            "final_conf": None,
        }
        if route in ELBOW_ROUTES and self.elbow is not None:
            specialist = self.elbow
        elif route in TEE_ROUTES and self.tee is not None:
            specialist = self.tee
        else:
            # pipe / miscellaneous: no specialist, passthrough as random
            out["final_label"] = "random"
            out["final_conf"] = out["pass1_conf"]
            return out
        p2 = specialist.predict(npz_path, min_conf=self.pass2_min_conf, tau=self.pass2_tau)
        out["pass2_argmax"] = p2["argmax_label"]
        out["pass2_predicted"] = p2["predicted_label"]
        out["pass2_conf"] = float(p2["argmax_conf"])
        out["final_label"] = p2["predicted_label"]
        out["final_conf"] = out["pass2_conf"]
        return out