pathoinfer 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pathoinfer/__init__.py +6 -0
- pathoinfer/_extras.py +18 -0
- pathoinfer/_logging.py +91 -0
- pathoinfer/analysis.py +68 -0
- pathoinfer/cli.py +480 -0
- pathoinfer/config.py +395 -0
- pathoinfer/convert/README.md +340 -0
- pathoinfer/convert/__init__.py +4 -0
- pathoinfer/convert/common.py +98 -0
- pathoinfer/convert/fp16.py +135 -0
- pathoinfer/convert/parity.py +484 -0
- pathoinfer/convert/ptq.py +163 -0
- pathoinfer/convert/tensorrt.py +139 -0
- pathoinfer/convert/vlm.py +359 -0
- pathoinfer/convert/vlm_parity.py +233 -0
- pathoinfer/engine/README.md +134 -0
- pathoinfer/engine/__init__.py +3 -0
- pathoinfer/engine/pipeline.py +437 -0
- pathoinfer/engine/scheduler.py +161 -0
- pathoinfer/io/README.md +79 -0
- pathoinfer/io/__init__.py +1 -0
- pathoinfer/io/interop.py +21 -0
- pathoinfer/io/objects.py +232 -0
- pathoinfer/io/writers/__init__.py +1 -0
- pathoinfer/io/writers/geojson.py +106 -0
- pathoinfer/io/writers/overlay.py +102 -0
- pathoinfer/io/writers/parquet.py +188 -0
- pathoinfer/io/writers/tiff.py +101 -0
- pathoinfer/post/README.md +116 -0
- pathoinfer/post/__init__.py +1 -0
- pathoinfer/post/instances.py +92 -0
- pathoinfer/post/nms.py +1 -0
- pathoinfer/post/smoothing.py +1 -0
- pathoinfer/post/vectorise.py +486 -0
- pathoinfer/py.typed +0 -0
- pathoinfer/registry/README.md +72 -0
- pathoinfer/registry/__init__.py +1 -0
- pathoinfer/registry/create.py +71 -0
- pathoinfer/registry/legacy.py +71 -0
- pathoinfer/registry/loader.py +171 -0
- pathoinfer/registry/model_card.py +309 -0
- pathoinfer/registry/onnx_info.py +45 -0
- pathoinfer/registry/schema/model_card.v1.json +1049 -0
- pathoinfer/runtime/README.md +119 -0
- pathoinfer/runtime/__init__.py +1 -0
- pathoinfer/runtime/base.py +86 -0
- pathoinfer/runtime/factory.py +51 -0
- pathoinfer/runtime/local/__init__.py +1 -0
- pathoinfer/runtime/local/onnx.py +155 -0
- pathoinfer/runtime/local/tensorrt.py +70 -0
- pathoinfer/runtime/local/torch.py +57 -0
- pathoinfer/runtime/local/vllm_offline.py +56 -0
- pathoinfer/runtime/remote/README.md +124 -0
- pathoinfer/runtime/remote/__init__.py +1 -0
- pathoinfer/runtime/remote/triton.py +77 -0
- pathoinfer/runtime/remote/vllm.py +137 -0
- pathoinfer/runtime/vlm.py +138 -0
- pathoinfer/serving/README.md +124 -0
- pathoinfer/serving/__init__.py +2 -0
- pathoinfer/serving/api.py +359 -0
- pathoinfer/serving/triton_repo.py +146 -0
- pathoinfer/serving/vllm.py +101 -0
- pathoinfer/stitch/README.md +209 -0
- pathoinfer/stitch/__init__.py +1 -0
- pathoinfer/stitch/base.py +133 -0
- pathoinfer/stitch/detection.py +241 -0
- pathoinfer/stitch/heatmap.py +211 -0
- pathoinfer/stitch/instance.py +232 -0
- pathoinfer/stitch/segmentation.py +247 -0
- pathoinfer/tiling/README.md +143 -0
- pathoinfer/tiling/__init__.py +4 -0
- pathoinfer/tiling/dataset.py +82 -0
- pathoinfer/tiling/grid.py +232 -0
- pathoinfer/tiling/slide_id.py +18 -0
- pathoinfer/tiling/synthetic.py +36 -0
- pathoinfer-0.2.0.dist-info/METADATA +369 -0
- pathoinfer-0.2.0.dist-info/RECORD +80 -0
- pathoinfer-0.2.0.dist-info/WHEEL +4 -0
- pathoinfer-0.2.0.dist-info/entry_points.txt +2 -0
- pathoinfer-0.2.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
"""Compare a converted model with its full-precision reference through the real stitchers.
|
|
2
|
+
|
|
3
|
+
Both models run on the same tiles: mini-slides, i.e. windows of ``window_tiles`` x
|
|
4
|
+
``window_tiles`` grid tiles around tissue on each listed slide, read once through
|
|
5
|
+
patchology. Each window's outputs go through the task's stitcher (cores, seams, polygons)
|
|
6
|
+
for both models, and the stitched results are compared per class, pooled over windows:
|
|
7
|
+
|
|
8
|
+
- segmentation: Dice of the class's polygons (``2|A n B| / (|A| + |B|)``);
|
|
9
|
+
- detection: F1 of detections matched one to one by box IoU >= ``iou``, and the
|
|
10
|
+
relative count difference ``|n_candidate - n_reference| / max(n_reference, 1)``;
|
|
11
|
+
- instance: the same two metrics for nuclei, matched one to one by polygon IoU >= ``iou``
|
|
12
|
+
(background is never written, so it is not scored);
|
|
13
|
+
- classification: one-vs-rest AUC of the candidate's core probabilities against the
|
|
14
|
+
reference's argmax labels.
|
|
15
|
+
|
|
16
|
+
The worst class of each metric is checked against its tolerance. A pass writes the
|
|
17
|
+
candidate as a new model folder whose card records the parity (``provenance.parity``);
|
|
18
|
+
a fail lists the failing metrics, the worst classes and, for two ONNX models, the layers
|
|
19
|
+
whose outputs diverge most, and writes nothing.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import shutil
|
|
26
|
+
from collections.abc import Iterator
|
|
27
|
+
from dataclasses import dataclass, field, replace
|
|
28
|
+
from datetime import UTC, datetime
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
import numpy as np
|
|
33
|
+
import shapely
|
|
34
|
+
import torch
|
|
35
|
+
from loguru import logger
|
|
36
|
+
from numpy.typing import NDArray
|
|
37
|
+
|
|
38
|
+
from patchology import open_slide
|
|
39
|
+
from pathoinfer._extras import extra, require
|
|
40
|
+
from pathoinfer._logging import log_call
|
|
41
|
+
from pathoinfer.config import ParityConfig, RuntimeConfig, expand_slides
|
|
42
|
+
from pathoinfer.convert.common import CARD_FILE
|
|
43
|
+
from pathoinfer.registry.loader import load_model
|
|
44
|
+
from pathoinfer.registry.model_card import (
|
|
45
|
+
ClassificationCard,
|
|
46
|
+
DetectionCard,
|
|
47
|
+
InstanceCard,
|
|
48
|
+
ModelCard,
|
|
49
|
+
Parity,
|
|
50
|
+
SegmentationCard,
|
|
51
|
+
parse_any_card,
|
|
52
|
+
parse_card,
|
|
53
|
+
)
|
|
54
|
+
from pathoinfer.runtime.base import Runtime, preprocess, resolve_device
|
|
55
|
+
from pathoinfer.runtime.factory import make_runtime
|
|
56
|
+
from pathoinfer.stitch.base import Stitcher, StitchResult
|
|
57
|
+
from pathoinfer.stitch.detection import DetectionStitcher
|
|
58
|
+
from pathoinfer.stitch.heatmap import HeatmapStitcher
|
|
59
|
+
from pathoinfer.stitch.instance import InstanceStitcher
|
|
60
|
+
from pathoinfer.stitch.segmentation import SegmentationStitcher
|
|
61
|
+
from pathoinfer.tiling.grid import SlideGrid, build_grid, read_tile
|
|
62
|
+
|
|
63
|
+
Window = tuple[SlideGrid, NDArray[np.uint8]] # a mini-slide grid and its tiles, NHWC
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class ParityReport:
|
|
68
|
+
passed: bool
|
|
69
|
+
metrics: dict[str, float] # worst class per metric
|
|
70
|
+
tolerances: dict[str, float]
|
|
71
|
+
per_class: dict[str, dict[str, float]] # metric -> class name -> value
|
|
72
|
+
failures: list[str]
|
|
73
|
+
tile_set_hash: str
|
|
74
|
+
tiles: int
|
|
75
|
+
worst_layers: list[tuple[str, float]] = field(default_factory=list)
|
|
76
|
+
|
|
77
|
+
def summary(self) -> str:
|
|
78
|
+
lines = [f"parity {'PASS' if self.passed else 'FAIL'} on {self.tiles} tiles"]
|
|
79
|
+
for name, value in self.metrics.items():
|
|
80
|
+
worst = min(self.per_class[name].items(), key=lambda kv: _badness(name, kv[1]))
|
|
81
|
+
lines.append(
|
|
82
|
+
f" {name} {value:.4f} (bound {self.tolerances[name]:g}; worst class {worst[0]})"
|
|
83
|
+
)
|
|
84
|
+
lines += [f" failed: {f}" for f in self.failures]
|
|
85
|
+
lines += [f" layer {n}: relative error {e:.3g}" for n, e in self.worst_layers]
|
|
86
|
+
return "\n".join(lines)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def windows(card: ModelCard, cfg: ParityConfig) -> Iterator[Window]:
|
|
90
|
+
"""Mini-slides: per slide, ``cfg.windows`` windows of up to ``window_tiles``² kept
|
|
91
|
+
tiles, each centred on a random tissue tile (seeded)."""
|
|
92
|
+
rng = np.random.default_rng(cfg.seed)
|
|
93
|
+
overlap = round(card.recommended_overlap * card.input.tile_size)
|
|
94
|
+
for path in expand_slides(cfg.slides):
|
|
95
|
+
with open_slide(path, cfg.backend) as slide:
|
|
96
|
+
grid = build_grid(
|
|
97
|
+
slide, card.input.tile_size, card.input.mpp, overlap, icc=card.input.icc
|
|
98
|
+
)
|
|
99
|
+
if not grid.tiles:
|
|
100
|
+
logger.warning("{}: no tissue tiles; skipped", path.name)
|
|
101
|
+
continue
|
|
102
|
+
half = cfg.window_tiles // 2
|
|
103
|
+
for centre in rng.choice(len(grid.tiles), size=cfg.windows, replace=False):
|
|
104
|
+
r0 = grid.tiles[centre].row - half
|
|
105
|
+
c0 = grid.tiles[centre].col - half
|
|
106
|
+
tiles = tuple(
|
|
107
|
+
s
|
|
108
|
+
for s in grid.tiles
|
|
109
|
+
if r0 <= s.row < r0 + cfg.window_tiles and c0 <= s.col < c0 + cfg.window_tiles
|
|
110
|
+
)
|
|
111
|
+
mini = replace(grid, tiles=tiles)
|
|
112
|
+
yield mini, np.stack([read_tile(slide, mini, s) for s in tiles])
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def tile_set_hash(sets: list[Window]) -> str:
|
|
116
|
+
keys = [(g.slide_id, s.x, s.y, g.tile_size, g.mpp) for g, _ in sets for s in g.tiles]
|
|
117
|
+
return hashlib.sha256(json.dumps(keys).encode()).hexdigest()[:16]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def compare(
|
|
121
|
+
card: ModelCard,
|
|
122
|
+
reference: Runtime,
|
|
123
|
+
candidate: Runtime,
|
|
124
|
+
sets: list[Window],
|
|
125
|
+
cfg: ParityConfig,
|
|
126
|
+
) -> tuple[dict[str, dict[str, float]], int]:
|
|
127
|
+
"""Per-class metrics of ``candidate`` against ``reference`` on ``sets``, and the
|
|
128
|
+
number of tiles."""
|
|
129
|
+
pooled: dict[str, Any] = {}
|
|
130
|
+
tiles = 0
|
|
131
|
+
for grid, images in sets:
|
|
132
|
+
results = []
|
|
133
|
+
for runtime in (reference, candidate):
|
|
134
|
+
stitcher = _stitcher(card, grid, cfg)
|
|
135
|
+
batch = runtime.batch_size if hasattr(runtime, "batch_size") else 16
|
|
136
|
+
for start in range(0, len(images), batch):
|
|
137
|
+
specs = list(grid.tiles[start : start + batch])
|
|
138
|
+
stitcher.add(
|
|
139
|
+
specs, runtime.predict(torch.from_numpy(images[start : start + batch]))
|
|
140
|
+
)
|
|
141
|
+
results.append(stitcher.finalize())
|
|
142
|
+
_accumulate(card, pooled, results[0], results[1], cfg.iou)
|
|
143
|
+
tiles += len(images)
|
|
144
|
+
return _finish(card, pooled), tiles
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def check(reference: str | Path, candidate: str | Path, cfg: ParityConfig) -> ParityReport:
|
|
148
|
+
"""Run both model sources on ``cfg``'s mini-slides and judge the candidate."""
|
|
149
|
+
ref_card, ref_dir = load_model(str(reference))
|
|
150
|
+
cand_card, cand_dir = load_model(str(candidate))
|
|
151
|
+
_same_contract(ref_card, cand_card)
|
|
152
|
+
ref_runtime = make_runtime(
|
|
153
|
+
ref_card,
|
|
154
|
+
ref_dir,
|
|
155
|
+
RuntimeConfig(
|
|
156
|
+
device=cfg.reference_device, batch_size=cfg.candidate.batch_size, tensorrt=False
|
|
157
|
+
),
|
|
158
|
+
)
|
|
159
|
+
cand_runtime = make_runtime(cand_card, cand_dir, cfg.candidate)
|
|
160
|
+
sets = list(windows(ref_card, cfg))
|
|
161
|
+
if not sets:
|
|
162
|
+
raise ValueError("no tissue tiles in the parity slides")
|
|
163
|
+
per_class, tiles = compare(ref_card, ref_runtime, cand_runtime, sets, cfg)
|
|
164
|
+
tolerances = cfg.tolerances.model_dump()
|
|
165
|
+
metrics = {name: _worst(name, values) for name, values in per_class.items()}
|
|
166
|
+
bounds = {name: tolerances[name] for name in metrics}
|
|
167
|
+
failures = [
|
|
168
|
+
f"{name} {value:.4f} {'>' if name.endswith('_max') else '<'} {bounds[name]:g}"
|
|
169
|
+
for name, value in metrics.items()
|
|
170
|
+
if _badness(name, value) > _badness(name, bounds[name])
|
|
171
|
+
]
|
|
172
|
+
worst_layers: list[tuple[str, float]] = []
|
|
173
|
+
if failures and ref_card.framework == cand_card.framework == "onnx":
|
|
174
|
+
images = np.concatenate([imgs for _, imgs in sets])[:8]
|
|
175
|
+
worst_layers = layer_errors(ref_card, ref_dir, cand_dir / cand_card.file, images)
|
|
176
|
+
report = ParityReport(
|
|
177
|
+
not failures, metrics, bounds, per_class, failures, tile_set_hash(sets), tiles, worst_layers
|
|
178
|
+
)
|
|
179
|
+
logger.info("{}", report.summary())
|
|
180
|
+
return report
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@log_call
|
|
184
|
+
def gate(
|
|
185
|
+
reference: str | Path,
|
|
186
|
+
candidate: str | Path,
|
|
187
|
+
cfg: ParityConfig,
|
|
188
|
+
out: Path,
|
|
189
|
+
register: tuple[str, str] | None = None,
|
|
190
|
+
tracking_uri: str | None = None,
|
|
191
|
+
) -> ParityReport:
|
|
192
|
+
"""``check``; on a pass, copy the candidate folder to the new folder ``out`` with
|
|
193
|
+
``provenance.parity`` in its card and, with ``register=(name, alias)``, register it in
|
|
194
|
+
MLflow under that alias. On a fail, write nothing."""
|
|
195
|
+
report = check(reference, candidate, cfg)
|
|
196
|
+
if not report.passed:
|
|
197
|
+
return report
|
|
198
|
+
if out.exists():
|
|
199
|
+
raise FileExistsError(f"{out} exists; choose a new folder")
|
|
200
|
+
ref_card, _ = load_model(str(reference))
|
|
201
|
+
cand_card, cand_dir = load_model(str(candidate))
|
|
202
|
+
data = cand_card.model_dump(mode="json")
|
|
203
|
+
data["provenance"]["parity"] = Parity(
|
|
204
|
+
reference=f"{ref_card.name}@{ref_card.version}",
|
|
205
|
+
tile_set_hash=report.tile_set_hash,
|
|
206
|
+
metrics=report.metrics,
|
|
207
|
+
tolerances=report.tolerances,
|
|
208
|
+
checked_at=datetime.now(UTC).isoformat(timespec="seconds"),
|
|
209
|
+
).model_dump(mode="json")
|
|
210
|
+
card = parse_card(data)
|
|
211
|
+
partial = out.with_name(out.name + ".partial")
|
|
212
|
+
shutil.rmtree(partial, ignore_errors=True)
|
|
213
|
+
shutil.copytree(cand_dir, partial)
|
|
214
|
+
(partial / CARD_FILE).write_text(card.model_dump_json(indent=2) + "\n")
|
|
215
|
+
os.replace(partial, out)
|
|
216
|
+
logger.info("parity passed: wrote {}", out)
|
|
217
|
+
if register is not None:
|
|
218
|
+
register_model(out, *register, tracking_uri=tracking_uri)
|
|
219
|
+
return report
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def register_model(folder: Path, name: str, alias: str, tracking_uri: str | None = None) -> str:
|
|
223
|
+
"""Log ``folder`` as an MLflow run's artifacts, add it as a new version of registered
|
|
224
|
+
model ``name`` and point ``alias`` at it; returns the version."""
|
|
225
|
+
mlflow = require("mlflow", extra("mlflow"))
|
|
226
|
+
client = mlflow.MlflowClient(tracking_uri=tracking_uri)
|
|
227
|
+
card = parse_any_card(json.loads((folder / CARD_FILE).read_text()))
|
|
228
|
+
experiment = client.get_experiment_by_name("pathoinfer-convert") or client.get_experiment(
|
|
229
|
+
client.create_experiment("pathoinfer-convert")
|
|
230
|
+
)
|
|
231
|
+
run = client.create_run(experiment.experiment_id, run_name=f"{card.name}-{card.version}")
|
|
232
|
+
client.log_artifacts(run.info.run_id, str(folder), "model")
|
|
233
|
+
client.set_terminated(run.info.run_id)
|
|
234
|
+
if not client.search_registered_models(filter_string=f"name = '{name}'"):
|
|
235
|
+
client.create_registered_model(name)
|
|
236
|
+
version = client.create_model_version(
|
|
237
|
+
name, f"{run.info.artifact_uri}/model", run_id=run.info.run_id
|
|
238
|
+
)
|
|
239
|
+
client.set_registered_model_alias(name, alias, version.version)
|
|
240
|
+
logger.info("registered {} version {} as @{}", name, version.version, alias)
|
|
241
|
+
return str(version.version)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def layer_errors(
|
|
245
|
+
card: ModelCard,
|
|
246
|
+
ref_dir: Path,
|
|
247
|
+
candidate: Path,
|
|
248
|
+
images: NDArray[np.uint8],
|
|
249
|
+
top: int = 5,
|
|
250
|
+
budget_bytes: int = 1 << 30,
|
|
251
|
+
) -> list[tuple[str, float]]:
|
|
252
|
+
"""The ``top`` intermediate tensors (by name, present in both ONNX graphs) whose
|
|
253
|
+
candidate values differ most from the reference's: relative L2 error on ``images``.
|
|
254
|
+
|
|
255
|
+
Tensors are fetched in groups of about ``budget_bytes`` per graph (sizes from the
|
|
256
|
+
reference graph's inferred shapes; a tensor of unknown size runs alone), one session run
|
|
257
|
+
per group, so memory stays bounded: all of HoVer-Net's tensors at once took 60 GB."""
|
|
258
|
+
onnx = require("onnx", extra("convert"))
|
|
259
|
+
ort = require("onnxruntime", extra("onnx"))
|
|
260
|
+
graphs = [onnx.load(ref_dir / card.file), onnx.load(candidate)]
|
|
261
|
+
names = [{o for n in g.graph.node for o in n.output if o} for g in graphs]
|
|
262
|
+
shared = sorted(names[0] & names[1])
|
|
263
|
+
sizes = _tensor_bytes(onnx, graphs[0], len(images))
|
|
264
|
+
x = preprocess(torch.from_numpy(images), card, resolve_device("cpu"))
|
|
265
|
+
errors = []
|
|
266
|
+
for group in _groups(shared, sizes, budget_bytes):
|
|
267
|
+
r_values, c_values = (_run_outputs(onnx, ort, g, group, x) for g in graphs)
|
|
268
|
+
for n in group:
|
|
269
|
+
r, c = r_values[n], c_values[n]
|
|
270
|
+
if r.shape != c.shape or not np.issubdtype(r.dtype, np.floating):
|
|
271
|
+
continue
|
|
272
|
+
r64, c64 = r.astype(np.float64), c.astype(np.float64)
|
|
273
|
+
errors.append((n, float(np.linalg.norm(c64 - r64) / max(np.linalg.norm(r64), 1e-12))))
|
|
274
|
+
return sorted(errors, key=lambda e: -e[1])[:top]
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _tensor_bytes(onnx: Any, model: Any, batch: int) -> dict[str, int]:
|
|
278
|
+
"""Bytes of each node output whose shape inference resolves, for ``batch`` inputs."""
|
|
279
|
+
sized = onnx.ModelProto()
|
|
280
|
+
sized.CopyFrom(model)
|
|
281
|
+
for dim in sized.graph.input[0].type.tensor_type.shape.dim[:1]:
|
|
282
|
+
if not dim.dim_value:
|
|
283
|
+
dim.dim_value = batch
|
|
284
|
+
try:
|
|
285
|
+
inferred = onnx.shape_inference.infer_shapes(sized)
|
|
286
|
+
except (onnx.shape_inference.InferenceError, ValueError): # >2 GB models: ValueError
|
|
287
|
+
return {}
|
|
288
|
+
out = {}
|
|
289
|
+
for v in [*inferred.graph.value_info, *inferred.graph.output]:
|
|
290
|
+
t = v.type.tensor_type
|
|
291
|
+
dims = [d.dim_value for d in t.shape.dim]
|
|
292
|
+
if t.elem_type and dims and all(dims):
|
|
293
|
+
itemsize = onnx.helper.tensor_dtype_to_np_dtype(t.elem_type).itemsize
|
|
294
|
+
out[v.name] = int(np.prod(dims)) * itemsize
|
|
295
|
+
return out
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _groups(names: list[str], sizes: dict[str, int], budget: int) -> Iterator[list[str]]:
|
|
299
|
+
"""``names`` in order, packed into groups whose known sizes sum to at most ``budget``."""
|
|
300
|
+
group: list[str] = []
|
|
301
|
+
used = 0
|
|
302
|
+
for n in names:
|
|
303
|
+
size = sizes.get(n, budget)
|
|
304
|
+
if group and used + size > budget:
|
|
305
|
+
yield group
|
|
306
|
+
group, used = [], 0
|
|
307
|
+
group.append(n)
|
|
308
|
+
used += size
|
|
309
|
+
if group:
|
|
310
|
+
yield group
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _run_outputs(
|
|
314
|
+
onnx: Any, ort: Any, model: Any, names: list[str], x: torch.Tensor
|
|
315
|
+
) -> dict[str, NDArray[Any]]:
|
|
316
|
+
"""``model`` run on CPU with exactly ``names`` as its outputs."""
|
|
317
|
+
probe = onnx.ModelProto()
|
|
318
|
+
probe.CopyFrom(model)
|
|
319
|
+
del probe.graph.output[:]
|
|
320
|
+
probe.graph.output.extend(onnx.helper.make_empty_tensor_value_info(n) for n in names)
|
|
321
|
+
options = ort.SessionOptions()
|
|
322
|
+
options.enable_cpu_mem_arena = False # an arena per session keeps its peak until exit
|
|
323
|
+
session = ort.InferenceSession(
|
|
324
|
+
probe.SerializeToString(), options, providers=["CPUExecutionProvider"]
|
|
325
|
+
)
|
|
326
|
+
feed = {session.get_inputs()[0].name: _as_input(x, session)}
|
|
327
|
+
return dict(zip(names, session.run(names, feed), strict=True))
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _as_input(x: torch.Tensor, session: Any) -> NDArray[Any]:
|
|
331
|
+
dtype = np.float16 if "float16" in session.get_inputs()[0].type else np.float32
|
|
332
|
+
return x.cpu().numpy().astype(dtype)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _same_contract(reference: ModelCard, candidate: ModelCard) -> None:
|
|
336
|
+
if reference.task != candidate.task or [c.name for c in reference.classes] != [
|
|
337
|
+
c.name for c in candidate.classes
|
|
338
|
+
]:
|
|
339
|
+
raise ValueError("reference and candidate differ in task or classes")
|
|
340
|
+
if (reference.input.tile_size, reference.input.mpp) != (
|
|
341
|
+
candidate.input.tile_size,
|
|
342
|
+
candidate.input.mpp,
|
|
343
|
+
):
|
|
344
|
+
raise ValueError("reference and candidate differ in tile size or mpp")
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _stitcher(card: ModelCard, grid: SlideGrid, cfg: ParityConfig) -> Stitcher:
|
|
348
|
+
if isinstance(card, SegmentationCard):
|
|
349
|
+
seg = cfg.segmentation
|
|
350
|
+
return SegmentationStitcher(
|
|
351
|
+
card,
|
|
352
|
+
grid,
|
|
353
|
+
output_mpp=seg.output_mpp or max(2.0, grid.mpp),
|
|
354
|
+
simplify_px=seg.simplify_px,
|
|
355
|
+
smooth=seg.smooth,
|
|
356
|
+
min_area_um2=seg.min_area_um2,
|
|
357
|
+
fill_holes_um2=seg.fill_holes_um2,
|
|
358
|
+
connectivity=seg.connectivity,
|
|
359
|
+
)
|
|
360
|
+
if isinstance(card, DetectionCard):
|
|
361
|
+
det = cfg.detection
|
|
362
|
+
return DetectionStitcher(
|
|
363
|
+
card, grid, score_threshold=det.score_threshold, nms_iou=det.nms_iou
|
|
364
|
+
)
|
|
365
|
+
if isinstance(card, InstanceCard):
|
|
366
|
+
return InstanceStitcher(card, grid, **cfg.instance.model_dump())
|
|
367
|
+
if not isinstance(card, ClassificationCard):
|
|
368
|
+
raise NotImplementedError(f"parity for {card.task} models is not supported yet")
|
|
369
|
+
return HeatmapStitcher(card, grid)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _accumulate(
|
|
373
|
+
card: ModelCard, pooled: dict[str, Any], ref: StitchResult, cand: StitchResult, iou: float
|
|
374
|
+
) -> None:
|
|
375
|
+
for c in card.classes:
|
|
376
|
+
acc = pooled.setdefault(
|
|
377
|
+
c.name,
|
|
378
|
+
{
|
|
379
|
+
"inter": 0.0,
|
|
380
|
+
"ref": 0.0,
|
|
381
|
+
"cand": 0.0,
|
|
382
|
+
"tp": 0,
|
|
383
|
+
"nr": 0,
|
|
384
|
+
"nc": 0,
|
|
385
|
+
"scores": [],
|
|
386
|
+
"labels": [],
|
|
387
|
+
},
|
|
388
|
+
)
|
|
389
|
+
if isinstance(card, SegmentationCard):
|
|
390
|
+
a = shapely.union_all([f.geometry for f in ref.features if f.class_id == c.id])
|
|
391
|
+
b = shapely.union_all([f.geometry for f in cand.features if f.class_id == c.id])
|
|
392
|
+
acc["inter"] += shapely.intersection(a, b).area
|
|
393
|
+
acc["ref"] += a.area
|
|
394
|
+
acc["cand"] += b.area
|
|
395
|
+
elif isinstance(card, (DetectionCard, InstanceCard)):
|
|
396
|
+
r, k = _class_shapes(ref, c.id), _class_shapes(cand, c.id)
|
|
397
|
+
acc["tp"] += _matches(r, k, iou)
|
|
398
|
+
acc["nr"] += len(r)
|
|
399
|
+
acc["nc"] += len(k)
|
|
400
|
+
else:
|
|
401
|
+
ref_probs = ref.detections.class_probs
|
|
402
|
+
cand_probs = cand.detections.class_probs
|
|
403
|
+
acc["labels"].append(ref_probs.argmax(1) == c.id)
|
|
404
|
+
acc["scores"].append(cand_probs[:, c.id])
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _finish(card: ModelCard, pooled: dict[str, Any]) -> dict[str, dict[str, float]]:
|
|
408
|
+
out: dict[str, dict[str, float]] = {}
|
|
409
|
+
background = getattr(card, "background_id", None)
|
|
410
|
+
for c in card.classes:
|
|
411
|
+
acc = pooled[c.name]
|
|
412
|
+
if c.id == background and not isinstance(card, ClassificationCard):
|
|
413
|
+
continue
|
|
414
|
+
if isinstance(card, SegmentationCard):
|
|
415
|
+
total = acc["ref"] + acc["cand"]
|
|
416
|
+
out.setdefault("dice_min", {})[c.name] = 1.0 if total == 0 else 2 * acc["inter"] / total
|
|
417
|
+
elif isinstance(card, (DetectionCard, InstanceCard)):
|
|
418
|
+
denominator = acc["nr"] + acc["nc"]
|
|
419
|
+
out.setdefault("f1_min", {})[c.name] = (
|
|
420
|
+
1.0 if denominator == 0 else 2 * acc["tp"] / denominator
|
|
421
|
+
)
|
|
422
|
+
out.setdefault("count_diff_max", {})[c.name] = abs(acc["nc"] - acc["nr"]) / max(
|
|
423
|
+
acc["nr"], 1
|
|
424
|
+
)
|
|
425
|
+
else:
|
|
426
|
+
labels = np.concatenate(acc["labels"])
|
|
427
|
+
scores = np.concatenate(acc["scores"])
|
|
428
|
+
out.setdefault("auc_min", {})[c.name] = auc(labels, scores)
|
|
429
|
+
return out
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _class_shapes(result: StitchResult, class_id: int) -> NDArray[np.object_]:
|
|
433
|
+
"""A class's objects as shapely geometries: detection boxes, or instance polygons."""
|
|
434
|
+
if result.instances is not None:
|
|
435
|
+
found = result.instances
|
|
436
|
+
return np.asarray(found.geometry[found.class_id == class_id])
|
|
437
|
+
d = result.detections
|
|
438
|
+
return np.asarray(shapely.box(*np.asarray(d.boxes[d.labels == class_id]).T))
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _matches(ref: NDArray[np.object_], cand: NDArray[np.object_], iou: float) -> int:
|
|
442
|
+
"""One-to-one matches by IoU >= ``iou``, greedy from the highest IoU."""
|
|
443
|
+
if len(ref) == 0 or len(cand) == 0:
|
|
444
|
+
return 0
|
|
445
|
+
i, j = shapely.STRtree(cand).query(ref, predicate="intersects")
|
|
446
|
+
inter = shapely.area(shapely.intersection(ref[i], cand[j]))
|
|
447
|
+
overlap = inter / (shapely.area(ref[i]) + shapely.area(cand[j]) - inter)
|
|
448
|
+
used_r: set[int] = set()
|
|
449
|
+
used_c: set[int] = set()
|
|
450
|
+
for k in np.argsort(-overlap):
|
|
451
|
+
if overlap[k] < iou:
|
|
452
|
+
break
|
|
453
|
+
if i[k] not in used_r and j[k] not in used_c:
|
|
454
|
+
used_r.add(int(i[k]))
|
|
455
|
+
used_c.add(int(j[k]))
|
|
456
|
+
return len(used_r)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def auc(labels: NDArray[np.bool_], scores: NDArray[np.floating]) -> float:
|
|
460
|
+
"""Area under the ROC curve (Mann-Whitney, ties counted half); 1.0 when one of the two
|
|
461
|
+
groups is empty, as nothing can be ranked wrongly."""
|
|
462
|
+
pos, neg = scores[labels], scores[~labels]
|
|
463
|
+
if len(pos) == 0 or len(neg) == 0:
|
|
464
|
+
return 1.0
|
|
465
|
+
ranks = _ranks(np.concatenate([pos, neg]))
|
|
466
|
+
return float((ranks[: len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _ranks(values: NDArray[np.floating]) -> NDArray[np.float64]:
|
|
470
|
+
order = np.argsort(values, kind="stable")
|
|
471
|
+
ranks = np.empty(len(values))
|
|
472
|
+
ranks[order] = np.arange(1, len(values) + 1)
|
|
473
|
+
_, inverse, counts = np.unique(values, return_inverse=True, return_counts=True)
|
|
474
|
+
sums = np.bincount(inverse, weights=ranks)
|
|
475
|
+
result: NDArray[np.float64] = (sums / counts)[inverse]
|
|
476
|
+
return result
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _worst(name: str, values: dict[str, float]) -> float:
|
|
480
|
+
return max(values.values()) if name.endswith("_max") else min(values.values())
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _badness(name: str, value: float) -> float:
|
|
484
|
+
return value if name.endswith("_max") else -value
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""INT8 / FP8 static post-training quantisation (PTQ) of an ONNX model folder.
|
|
2
|
+
|
|
3
|
+
Calibration tiles are read through patchology from the config's slides (``calibration``),
|
|
4
|
+
at the card's tile size and mpp, and preprocessed exactly as at inference
|
|
5
|
+
(``runtime.base.preprocess``). Two engines:
|
|
6
|
+
|
|
7
|
+
- ``modelopt`` (NVIDIA ModelOpt): Q/DQ graphs laid out for TensorRT, INT8 or FP8; nodes
|
|
8
|
+
kept out of quantisation run in FP16. It runs in a child process, because ModelOpt
|
|
9
|
+
patches ONNX Runtime's calibrators for the rest of the process it runs in.
|
|
10
|
+
- ``ort`` (ONNX Runtime): INT8 Q/DQ (symmetric, per-channel weights) that also runs in
|
|
11
|
+
ONNX Runtime without TensorRT; kept nodes stay FP32.
|
|
12
|
+
|
|
13
|
+
Kept nodes come from ``keep_ops``, ``keep_nodes`` and ``keep_ends`` (``QuantConfig``).
|
|
14
|
+
QAT is not done here: it belongs in training (pathotrain).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import multiprocessing
|
|
18
|
+
import tempfile
|
|
19
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import torch
|
|
25
|
+
from loguru import logger
|
|
26
|
+
from numpy.typing import NDArray
|
|
27
|
+
|
|
28
|
+
from pathoinfer._extras import extra, require
|
|
29
|
+
from pathoinfer._logging import log_call
|
|
30
|
+
from pathoinfer.config import QuantConfig, expand_slides
|
|
31
|
+
from pathoinfer.convert.common import calibration_tiles, match_nodes, write_variant
|
|
32
|
+
from pathoinfer.registry.loader import load_model
|
|
33
|
+
from pathoinfer.registry.model_card import ModelCard
|
|
34
|
+
from pathoinfer.runtime.base import preprocess, resolve_device
|
|
35
|
+
|
|
36
|
+
ORT_METHODS = {"entropy": "Entropy", "minmax": "MinMax", "percentile": "Percentile"}
|
|
37
|
+
MODELOPT_METHODS = {"entropy": "entropy", "minmax": "max", "percentile": "percentile"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@log_call
|
|
41
|
+
def quantise(source: str | Path, out: Path, cfg: QuantConfig) -> ModelCard:
|
|
42
|
+
"""Quantise the fp32 ONNX model at ``source`` into the new folder ``out``."""
|
|
43
|
+
onnx = require("onnx", extra("convert"))
|
|
44
|
+
card, model_dir = load_model(str(source))
|
|
45
|
+
if card.framework != "onnx" or card.precision != "fp32":
|
|
46
|
+
raise ValueError(f"expected an fp32 ONNX model, got {card.framework} {card.precision}")
|
|
47
|
+
cal = cfg.calibration
|
|
48
|
+
tiles, tiles_hash = calibration_tiles(
|
|
49
|
+
card, expand_slides(cal.slides), cal.tiles, cal.seed, cal.backend
|
|
50
|
+
)
|
|
51
|
+
data = preprocess(torch.from_numpy(tiles), card, resolve_device("cpu")).numpy()
|
|
52
|
+
model = onnx.load(model_dir / card.file)
|
|
53
|
+
for i, node in enumerate(model.graph.node): # exclusion lists need node names
|
|
54
|
+
node.name = node.name or f"{node.op_type}_{i}"
|
|
55
|
+
nodes = [(n.name, n.op_type) for n in model.graph.node]
|
|
56
|
+
keep = match_nodes(nodes, cfg.keep_ops, cfg.keep_nodes, cfg.keep_ends)
|
|
57
|
+
logger.info("{}: keeping {} of {} nodes in high precision", card.name, len(keep), len(nodes))
|
|
58
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
59
|
+
named, quantised = Path(tmp) / "named.onnx", Path(tmp) / "quantised.onnx"
|
|
60
|
+
onnx.save(model, named)
|
|
61
|
+
if cfg.engine == "ort":
|
|
62
|
+
_ort(named, quantised, card, data, keep, cfg)
|
|
63
|
+
else:
|
|
64
|
+
_modelopt(named, quantised, card, data, keep, cfg)
|
|
65
|
+
result = onnx.load(quantised)
|
|
66
|
+
settings = {
|
|
67
|
+
"engine": cfg.engine,
|
|
68
|
+
"method": cfg.method,
|
|
69
|
+
"tiles": len(tiles),
|
|
70
|
+
"kept_nodes": keep,
|
|
71
|
+
}
|
|
72
|
+
return write_variant(
|
|
73
|
+
card,
|
|
74
|
+
out,
|
|
75
|
+
lambda path: onnx.save(result, path),
|
|
76
|
+
precision=cfg.precision,
|
|
77
|
+
version=f"{card.version}+{cfg.precision}",
|
|
78
|
+
**{
|
|
79
|
+
"provenance.calibration_set_hash": tiles_hash,
|
|
80
|
+
"provenance.source_metadata": {
|
|
81
|
+
**card.provenance.source_metadata,
|
|
82
|
+
"quantisation": settings,
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _ort(
|
|
89
|
+
source: Path,
|
|
90
|
+
out: Path,
|
|
91
|
+
card: ModelCard,
|
|
92
|
+
data: NDArray[np.float32],
|
|
93
|
+
keep: list[str],
|
|
94
|
+
cfg: QuantConfig,
|
|
95
|
+
) -> None:
|
|
96
|
+
q = require("onnxruntime.quantization", extra("onnx"))
|
|
97
|
+
|
|
98
|
+
class Reader(q.CalibrationDataReader): # type: ignore[misc,name-defined]
|
|
99
|
+
def __init__(self) -> None:
|
|
100
|
+
self.batches = iter(np.array_split(data, max(1, len(data) // 16)))
|
|
101
|
+
|
|
102
|
+
def get_next(self) -> dict[str, NDArray[Any]] | None:
|
|
103
|
+
batch = next(self.batches, None)
|
|
104
|
+
return None if batch is None else {card.input.name: batch}
|
|
105
|
+
|
|
106
|
+
q.quantize_static(
|
|
107
|
+
source,
|
|
108
|
+
out,
|
|
109
|
+
Reader(),
|
|
110
|
+
quant_format=q.QuantFormat.QDQ,
|
|
111
|
+
activation_type=q.QuantType.QInt8,
|
|
112
|
+
weight_type=q.QuantType.QInt8,
|
|
113
|
+
per_channel=True,
|
|
114
|
+
nodes_to_exclude=keep,
|
|
115
|
+
calibrate_method=getattr(q.CalibrationMethod, ORT_METHODS[cfg.method]),
|
|
116
|
+
extra_options={
|
|
117
|
+
"ActivationSymmetric": True,
|
|
118
|
+
"WeightSymmetric": True,
|
|
119
|
+
"CalibPercentile": cfg.percentile,
|
|
120
|
+
},
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _modelopt(
|
|
125
|
+
source: Path,
|
|
126
|
+
out: Path,
|
|
127
|
+
card: ModelCard,
|
|
128
|
+
data: NDArray[np.float32],
|
|
129
|
+
keep: list[str],
|
|
130
|
+
cfg: QuantConfig,
|
|
131
|
+
) -> None:
|
|
132
|
+
"""Run ModelOpt in a fresh process: it monkey-patches ONNX Runtime's calibrators for
|
|
133
|
+
the rest of the process it runs in, which breaks later ONNX Runtime quantisation."""
|
|
134
|
+
require("modelopt.onnx.quantization", extra("convert"))
|
|
135
|
+
tiles = out.with_name("calibration.npy")
|
|
136
|
+
np.save(tiles, data)
|
|
137
|
+
with ProcessPoolExecutor(1, mp_context=multiprocessing.get_context("spawn")) as pool:
|
|
138
|
+
pool.submit(
|
|
139
|
+
_modelopt_job,
|
|
140
|
+
str(source),
|
|
141
|
+
str(out),
|
|
142
|
+
str(tiles),
|
|
143
|
+
card.input.name,
|
|
144
|
+
keep,
|
|
145
|
+
cfg.precision,
|
|
146
|
+
MODELOPT_METHODS[cfg.method],
|
|
147
|
+
).result()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _modelopt_job(
|
|
151
|
+
source: str, out: str, tiles: str, input_name: str, keep: list[str], mode: str, method: str
|
|
152
|
+
) -> None:
|
|
153
|
+
from modelopt.onnx.quantization import quantize
|
|
154
|
+
|
|
155
|
+
quantize(
|
|
156
|
+
onnx_path=source,
|
|
157
|
+
quantize_mode=mode,
|
|
158
|
+
calibration_data={input_name: np.load(tiles, mmap_mode="r")},
|
|
159
|
+
calibration_method=method,
|
|
160
|
+
nodes_to_exclude=[f"^{name}$" for name in keep],
|
|
161
|
+
high_precision_dtype="fp16",
|
|
162
|
+
output_path=out,
|
|
163
|
+
)
|