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
pathoinfer/config.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""Run settings: one YAML file per run, validated here (examples in ``examples/``).
|
|
2
|
+
|
|
3
|
+
Relative paths (model, slides, output folder) are relative to the working directory.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import glob
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Literal, NamedTuple
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
14
|
+
|
|
15
|
+
from patchology import ArtifactConfig, Backend, TissueConfig
|
|
16
|
+
from pathoinfer.registry.model_card import Byte, SegmentationCard, TileTask
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _Strict(BaseModel):
|
|
20
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TilingConfig(_Strict):
|
|
24
|
+
"""How patchology opens, masks and tiles a slide.
|
|
25
|
+
|
|
26
|
+
Tile size and mpp come from the model. ``overlap`` is a fraction of the tile; None uses
|
|
27
|
+
the card's ``recommended_overlap``. A tile is kept when its tissue fraction is above 0
|
|
28
|
+
and at least ``min_tissue_fraction``. There is deliberately no slide mpp override: a
|
|
29
|
+
slide without a resolution in its metadata is refused, never inferred on.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
backend: Backend = "openslide"
|
|
33
|
+
icc: bool = True
|
|
34
|
+
overlap: float | None = Field(None, ge=0, lt=1)
|
|
35
|
+
min_tissue_fraction: float = Field(0.0, ge=0, le=1)
|
|
36
|
+
tissue: TissueConfig = TissueConfig()
|
|
37
|
+
artifacts: ArtifactConfig = ArtifactConfig()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RuntimeConfig(_Strict):
|
|
41
|
+
"""How the model executes, in this process. ``device`` is ``auto`` (CUDA when
|
|
42
|
+
available), ``cpu``, ``cuda`` or ``cuda:N``. ``tensorrt`` lets ONNX models use the
|
|
43
|
+
TensorRT EP when its libraries load. ``autocast`` runs PyTorch models in ``bf16`` or
|
|
44
|
+
``fp16``; otherwise a model runs at its card's precision. ``triton_url`` (gRPC, e.g.
|
|
45
|
+
``triton:8001``) runs the model on a Triton server instead, under ``triton_model``
|
|
46
|
+
(default: the card's name); the model folder is still read for its card."""
|
|
47
|
+
|
|
48
|
+
device: str = Field("auto", pattern=r"^(auto|cpu|cuda(:\d+)?)$")
|
|
49
|
+
batch_size: int = Field(32, gt=0)
|
|
50
|
+
tensorrt: bool = True
|
|
51
|
+
autocast: Literal["bf16", "fp16"] | None = None
|
|
52
|
+
triton_url: str | None = None
|
|
53
|
+
triton_model: str | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class LoaderConfig(_Strict):
|
|
57
|
+
"""Tile reading. ``num_workers`` 0 reads in the main process."""
|
|
58
|
+
|
|
59
|
+
num_workers: int = Field(4, ge=0)
|
|
60
|
+
prefetch_factor: int = Field(2, gt=0)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class SegmentationOptions(_Strict):
|
|
64
|
+
"""Segmentation stitching (``stitch/README.md``). ``output_mpp`` None polygonises at
|
|
65
|
+
2.0 mpp, or at the model's mpp when that is coarser. ``smooth`` rounds of Chaikin
|
|
66
|
+
corner cutting round off pixel steps (each doubles the vertices); 0 keeps outlines
|
|
67
|
+
on pixel edges. Holes under ``fill_holes_um2`` are filled (unless another class lies
|
|
68
|
+
inside) and regions under ``min_area_um2`` dropped; ``.inf`` fills every hole.
|
|
69
|
+
``connectivity`` 8 keeps parts touching only at a pixel corner in one region (a
|
|
70
|
+
MultiPolygon meeting at that point); 4 makes them separate regions.
|
|
71
|
+
|
|
72
|
+
``background_classes`` (names) count as background. ``class_map`` renames and merges:
|
|
73
|
+
each key is an output class name, its value the model class it renames or a list of
|
|
74
|
+
model classes it merges, e.g. ``{tumor: invasive tumor, stroma: [inflamed stroma,
|
|
75
|
+
tumor-associated stroma]}``. Classes not named keep their names. Probabilities move
|
|
76
|
+
before each pixel's class is chosen: a pixel 30% stroma, 30% inflamed stroma and 40%
|
|
77
|
+
tumour becomes stroma (60%) when the two stromas merge. Every output then shows the
|
|
78
|
+
result: label map, polygons, summary, overlay."""
|
|
79
|
+
|
|
80
|
+
output_mpp: float | None = Field(None, gt=0)
|
|
81
|
+
simplify_px: float = Field(1.5, ge=0)
|
|
82
|
+
smooth: int = Field(2, ge=0, le=5)
|
|
83
|
+
min_area_um2: float = Field(0.0, ge=0)
|
|
84
|
+
fill_holes_um2: float = Field(0.0, ge=0)
|
|
85
|
+
connectivity: Literal[4, 8] = 8
|
|
86
|
+
background_classes: list[str] = []
|
|
87
|
+
class_map: dict[str, str | list[str]] = {}
|
|
88
|
+
|
|
89
|
+
def class_remap(self, card: SegmentationCard) -> "ClassRemap":
|
|
90
|
+
"""What ``background_classes`` and ``class_map`` do to ``card``'s classes, by id.
|
|
91
|
+
A merged class keeps the id of its lowest-numbered source. Raises ValueError for
|
|
92
|
+
unknown or empty sources, a class used twice or named as the background, background
|
|
93
|
+
classes without a background, and output names that clash."""
|
|
94
|
+
ids = {c.name: c.id for c in card.classes}
|
|
95
|
+
groups = {
|
|
96
|
+
new: [old] if isinstance(old, str) else old for new, old in self.class_map.items()
|
|
97
|
+
}
|
|
98
|
+
empty = sorted(new for new, old in groups.items() if not old)
|
|
99
|
+
if empty:
|
|
100
|
+
raise ValueError(f"class_map entries without a source class: {empty}")
|
|
101
|
+
sources = [*self.background_classes, *(n for old in groups.values() for n in old)]
|
|
102
|
+
unknown = sorted({n for n in sources if n not in ids})
|
|
103
|
+
if unknown:
|
|
104
|
+
raise ValueError(
|
|
105
|
+
f"segmentation names unknown classes {unknown}; the model has {sorted(ids)}"
|
|
106
|
+
)
|
|
107
|
+
twice = sorted({n for n in sources if sources.count(n) > 1})
|
|
108
|
+
if twice:
|
|
109
|
+
raise ValueError(
|
|
110
|
+
f"classes used more than once in background_classes and class_map: {twice}"
|
|
111
|
+
)
|
|
112
|
+
background = card.background_id
|
|
113
|
+
if background is not None and any(ids[n] == background for n in sources):
|
|
114
|
+
raise ValueError("background_classes and class_map cannot use the background class")
|
|
115
|
+
if self.background_classes and background is None:
|
|
116
|
+
raise ValueError("background_classes needs a model with a background class")
|
|
117
|
+
unmapped = [c.name for c in card.classes if c.name not in sources]
|
|
118
|
+
names = [*groups, *unmapped]
|
|
119
|
+
clash = sorted({n for n in names if names.count(n) > 1})
|
|
120
|
+
if clash:
|
|
121
|
+
raise ValueError(f"class_map output names clash with other classes: {clash}")
|
|
122
|
+
targets = {ids[n]: background for n in self.background_classes if background is not None}
|
|
123
|
+
rename = {}
|
|
124
|
+
for new, old in groups.items():
|
|
125
|
+
keep, *rest = sorted(ids[n] for n in old)
|
|
126
|
+
targets |= {i: keep for i in rest}
|
|
127
|
+
rename[keep] = new
|
|
128
|
+
return ClassRemap(targets, rename)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class ClassRemap(NamedTuple):
|
|
132
|
+
"""``targets``: class id -> the id its probability moves to. ``names``: id -> its new
|
|
133
|
+
name, for the classes ``class_map`` names."""
|
|
134
|
+
|
|
135
|
+
targets: dict[int, int]
|
|
136
|
+
names: dict[int, str]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class DetectionOptions(_Strict):
|
|
140
|
+
"""Detection stitching. ``score_threshold`` None uses the card's. ``nms_iou`` None
|
|
141
|
+
turns cross-tile NMS off. ``geometry`` is what writers output per detection."""
|
|
142
|
+
|
|
143
|
+
score_threshold: float | None = Field(None, ge=0, le=1)
|
|
144
|
+
nms_iou: float | None = Field(None, gt=0, le=1)
|
|
145
|
+
geometry: Literal["point", "box"] = "box"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class InstanceOptions(_Strict):
|
|
149
|
+
"""Instance (nucleus) stitching, HoVer-Net's watershed (``stitch/instance.py``):
|
|
150
|
+
nuclei are pixels whose nucleus probability is at least ``threshold``; the HV maps'
|
|
151
|
+
gradient energy below ``marker_threshold`` seeds them; blobs and seeds under
|
|
152
|
+
``min_size_px`` model pixels are dropped. Polygons are simplified at ``simplify_px``
|
|
153
|
+
model pixels and smoothed by ``smooth`` rounds of Chaikin (0 keeps pixel edges).
|
|
154
|
+
The defaults are the values pathotrain validates with. ``workers`` processes run the
|
|
155
|
+
per-tile watershed (0: on the stitcher thread); it never changes the output."""
|
|
156
|
+
|
|
157
|
+
threshold: float = Field(0.5, gt=0, lt=1)
|
|
158
|
+
marker_threshold: float = Field(0.4, gt=0, lt=1)
|
|
159
|
+
min_size_px: int = Field(10, ge=1)
|
|
160
|
+
simplify_px: float = Field(1.0, ge=0)
|
|
161
|
+
smooth: int = Field(2, ge=0, le=5)
|
|
162
|
+
workers: int = Field(4, ge=0)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class ClassificationOptions(_Strict):
|
|
166
|
+
"""Tile classification heatmaps (``stitch/heatmap.py``): each tile core gets the
|
|
167
|
+
overlap-weighted mean of the probabilities of the tiles over it. ``sigma_tiles`` > 0
|
|
168
|
+
smooths that grid with a Gaussian (sigma in tiles). ``thresholds`` maps class names to
|
|
169
|
+
the probability their region polygons start at (none: tiles only). Region options are
|
|
170
|
+
as in segmentation, with pixels being tile cores."""
|
|
171
|
+
|
|
172
|
+
sigma_tiles: float = Field(0.0, ge=0)
|
|
173
|
+
thresholds: dict[str, float] = {}
|
|
174
|
+
simplify_px: float = Field(1.0, ge=0)
|
|
175
|
+
smooth: int = Field(2, ge=0, le=5)
|
|
176
|
+
min_area_um2: float = Field(0.0, ge=0)
|
|
177
|
+
fill_holes_um2: float = Field(0.0, ge=0)
|
|
178
|
+
connectivity: Literal[4, 8] = 8
|
|
179
|
+
|
|
180
|
+
@model_validator(mode="after")
|
|
181
|
+
def _thresholds_are_probabilities(self) -> "ClassificationOptions":
|
|
182
|
+
bad = {k: v for k, v in self.thresholds.items() if not 0 < v <= 1}
|
|
183
|
+
if bad:
|
|
184
|
+
raise ValueError(f"thresholds must be in (0, 1], got {bad}")
|
|
185
|
+
return self
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class OutputConfig(_Strict):
|
|
189
|
+
"""What to write per slide into ``dir`` (``docs/outputs.md``). ``parquet`` writes the
|
|
190
|
+
objects table and the per-class summary, as Parquet or ``summary_format: json``.
|
|
191
|
+
``tiff`` writes the segmentation label map, or a ``prob_<class>`` heatmap per class
|
|
192
|
+
for classification; ``overlay`` a PNG of the slide at
|
|
193
|
+
``overlay_mpp`` with the segmentation polygons filled in their class colours."""
|
|
194
|
+
|
|
195
|
+
dir: Path = Path("outputs")
|
|
196
|
+
geojson: bool = True
|
|
197
|
+
gzip: bool = True
|
|
198
|
+
per_class: bool = False
|
|
199
|
+
parquet: bool = True
|
|
200
|
+
summary_format: Literal["parquet", "json"] = "parquet"
|
|
201
|
+
geoparquet: bool = False
|
|
202
|
+
tiff: bool = False
|
|
203
|
+
overlay: bool = True
|
|
204
|
+
overlay_mpp: float = Field(6.0, gt=0)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class RunConfig(_Strict):
|
|
208
|
+
"""One run. ``slides`` is a path, a glob, a list file (``.txt`` one path per line,
|
|
209
|
+
``.csv`` or ``.parquet`` with a ``path`` column), or a list of any of these.
|
|
210
|
+
``resume`` skips slides whose outputs exist from a run with the same settings.
|
|
211
|
+
``class_colors`` replaces the colour of any class, by class name."""
|
|
212
|
+
|
|
213
|
+
task: TileTask
|
|
214
|
+
model: str
|
|
215
|
+
slides: str | list[str]
|
|
216
|
+
tiling: TilingConfig = TilingConfig()
|
|
217
|
+
runtime: RuntimeConfig = RuntimeConfig()
|
|
218
|
+
loader: LoaderConfig = LoaderConfig()
|
|
219
|
+
segmentation: SegmentationOptions = SegmentationOptions()
|
|
220
|
+
detection: DetectionOptions = DetectionOptions()
|
|
221
|
+
instance: InstanceOptions = InstanceOptions()
|
|
222
|
+
classification: ClassificationOptions = ClassificationOptions()
|
|
223
|
+
outputs: OutputConfig = OutputConfig()
|
|
224
|
+
class_colors: dict[str, tuple[Byte, Byte, Byte]] = {}
|
|
225
|
+
resume: bool = True
|
|
226
|
+
|
|
227
|
+
def settings_hash(self, card_json: str) -> str:
|
|
228
|
+
"""Hash of everything that changes a slide's outputs: these settings minus the
|
|
229
|
+
slide list, reading and device, plus the model's card."""
|
|
230
|
+
settings = self.model_dump(
|
|
231
|
+
mode="json",
|
|
232
|
+
exclude={
|
|
233
|
+
"slides": True,
|
|
234
|
+
"resume": True,
|
|
235
|
+
"loader": True,
|
|
236
|
+
"runtime": {"device", "batch_size"},
|
|
237
|
+
"instance": {"workers"},
|
|
238
|
+
},
|
|
239
|
+
)
|
|
240
|
+
blob = json.dumps({"settings": settings, "card": json.loads(card_json)}, sort_keys=True)
|
|
241
|
+
return hashlib.sha256(blob.encode()).hexdigest()[:16]
|
|
242
|
+
|
|
243
|
+
def slide_paths(self) -> list[Path]:
|
|
244
|
+
"""Every slide the ``slides`` entry names, in order, duplicates removed."""
|
|
245
|
+
return expand_slides(self.slides)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def expand_slides(slides: str | list[str]) -> list[Path]:
|
|
249
|
+
"""Paths from a path, a glob, a list file or a list of these, duplicates removed."""
|
|
250
|
+
entries = [slides] if isinstance(slides, str) else slides
|
|
251
|
+
return list(dict.fromkeys(p for entry in entries for p in _expand(entry)))
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _expand(entry: str) -> list[Path]:
|
|
255
|
+
path = Path(entry)
|
|
256
|
+
if path.suffix in (".txt", ".csv", ".parquet") and path.is_file():
|
|
257
|
+
import polars as pl
|
|
258
|
+
|
|
259
|
+
if path.suffix == ".parquet":
|
|
260
|
+
column = pl.read_parquet(path, columns=["path"])["path"]
|
|
261
|
+
elif path.suffix == ".csv":
|
|
262
|
+
column = pl.read_csv(path, columns=["path"])["path"]
|
|
263
|
+
else:
|
|
264
|
+
column = pl.read_csv(path, has_header=False, new_columns=["path"])["path"]
|
|
265
|
+
return [path.parent / p for p in column.drop_nulls().str.strip_chars() if p]
|
|
266
|
+
if glob.has_magic(entry):
|
|
267
|
+
return sorted(Path(p) for p in glob.glob(entry, recursive=True))
|
|
268
|
+
return [path]
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def load_config(path: str | Path) -> RunConfig:
|
|
272
|
+
with open(path) as f:
|
|
273
|
+
return RunConfig.model_validate(yaml.safe_load(f))
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class CalibrationConfig(_Strict):
|
|
277
|
+
"""Calibration tiles, read through patchology at the model's tile size and mpp.
|
|
278
|
+
List slides across scanners, stains and tissue types; tiles are spread evenly over
|
|
279
|
+
them."""
|
|
280
|
+
|
|
281
|
+
slides: str | list[str]
|
|
282
|
+
tiles: int = Field(512, gt=0)
|
|
283
|
+
seed: int = 0
|
|
284
|
+
backend: Backend = "openslide"
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
class QuantConfig(_Strict):
|
|
288
|
+
"""Static post-training quantisation (``pathoinfer convert ptq``).
|
|
289
|
+
|
|
290
|
+
``engine`` ``modelopt`` (NVIDIA ModelOpt) targets TensorRT, keeps excluded layers in
|
|
291
|
+
FP16 and does INT8 and FP8; ``ort`` (ONNX Runtime) does INT8 that runs in ONNX
|
|
292
|
+
Runtime too, keeping excluded layers in FP32. Kept in high precision: nodes whose op
|
|
293
|
+
type is in ``keep_ops``, whose name matches a glob in ``keep_nodes`` (lower case), and
|
|
294
|
+
with ``keep_ends`` the first and last Conv/MatMul/Gemm. The defaults suit CNNs and
|
|
295
|
+
ViT backbones (LayerNorm, Softmax, attention)."""
|
|
296
|
+
|
|
297
|
+
precision: Literal["int8", "fp8"] = "int8"
|
|
298
|
+
engine: Literal["modelopt", "ort"] = "modelopt"
|
|
299
|
+
method: Literal["entropy", "minmax", "percentile"] = "entropy"
|
|
300
|
+
percentile: float = Field(99.999, gt=50, lt=100)
|
|
301
|
+
calibration: CalibrationConfig
|
|
302
|
+
keep_ops: list[str] = ["LayerNormalization", "Softmax"]
|
|
303
|
+
keep_nodes: list[str] = ["*attn*", "*attention*"]
|
|
304
|
+
keep_ends: bool = True
|
|
305
|
+
|
|
306
|
+
@model_validator(mode="after")
|
|
307
|
+
def _fp8_needs_modelopt(self) -> "QuantConfig":
|
|
308
|
+
if self.precision == "fp8" and self.engine != "modelopt":
|
|
309
|
+
raise ValueError("fp8 needs engine: modelopt")
|
|
310
|
+
return self
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class ParityTolerances(_Strict):
|
|
314
|
+
"""Bounds a converted model must meet against its reference, per task: segmentation
|
|
315
|
+
Dice per class (polygon level), detection F1 per class and relative count difference,
|
|
316
|
+
classification one-vs-rest AUC per class (the reference's argmax as labels)."""
|
|
317
|
+
|
|
318
|
+
dice_min: float = Field(0.97, ge=0, le=1)
|
|
319
|
+
f1_min: float = Field(0.97, ge=0, le=1)
|
|
320
|
+
count_diff_max: float = Field(0.03, ge=0)
|
|
321
|
+
auc_min: float = Field(0.99, ge=0, le=1)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
class ParityConfig(_Strict):
|
|
325
|
+
"""``pathoinfer convert parity``: both models run on the same mini-slides (windows of
|
|
326
|
+
``window_tiles`` x ``window_tiles`` grid tiles around tissue, ``windows`` per slide)
|
|
327
|
+
through the real stitchers, with this config's stitch settings."""
|
|
328
|
+
|
|
329
|
+
slides: str | list[str]
|
|
330
|
+
window_tiles: int = Field(6, gt=0)
|
|
331
|
+
windows: int = Field(2, gt=0)
|
|
332
|
+
seed: int = 0
|
|
333
|
+
backend: Backend = "openslide"
|
|
334
|
+
reference_device: str = Field("auto", pattern=r"^(auto|cpu|cuda(:\d+)?)$")
|
|
335
|
+
candidate: RuntimeConfig = RuntimeConfig()
|
|
336
|
+
iou: float = Field(0.5, gt=0, le=1)
|
|
337
|
+
tolerances: ParityTolerances = ParityTolerances()
|
|
338
|
+
segmentation: SegmentationOptions = SegmentationOptions()
|
|
339
|
+
detection: DetectionOptions = DetectionOptions()
|
|
340
|
+
instance: InstanceOptions = InstanceOptions()
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
class VqaDataConfig(_Strict):
|
|
344
|
+
"""Image + question pairs: a ``.jsonl``, ``.csv`` or ``.parquet`` table with columns
|
|
345
|
+
``image`` (a path, relative to the table's folder) and ``question``, plus ``answer``
|
|
346
|
+
and optionally ``box`` (``[x0, y0, x1, y1]`` in image pixels) for evaluation. Pathology
|
|
347
|
+
crops at the model's tile size and mpp, not generic images. ``samples`` None uses
|
|
348
|
+
every row; otherwise a seeded random subset."""
|
|
349
|
+
|
|
350
|
+
path: Path
|
|
351
|
+
samples: int | None = Field(256, gt=0)
|
|
352
|
+
seed: int = 0
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
class VlmQuantConfig(_Strict):
|
|
356
|
+
"""``pathoinfer convert vlm``: llm-compressor recipe for the language model only.
|
|
357
|
+
|
|
358
|
+
``fp8``: W8A8 FP8 (dynamic per-token activations; no calibration data needed).
|
|
359
|
+
``w4a16-awq`` / ``w4a16-gptq``: 4-bit weights, 16-bit activations, calibrated on
|
|
360
|
+
``calibration`` (a few hundred pathology image + question pairs). The vision encoder
|
|
361
|
+
and projector stay bf16, as does ``lm_head``; ``extra_ignore`` adds module patterns."""
|
|
362
|
+
|
|
363
|
+
scheme: Literal["fp8", "w4a16-awq", "w4a16-gptq"] = "fp8"
|
|
364
|
+
calibration: VqaDataConfig | None = None
|
|
365
|
+
max_seq_len: int = Field(2048, gt=0)
|
|
366
|
+
extra_ignore: list[str] = []
|
|
367
|
+
|
|
368
|
+
@model_validator(mode="after")
|
|
369
|
+
def _calibration_when_needed(self) -> "VlmQuantConfig":
|
|
370
|
+
if self.scheme != "fp8" and self.calibration is None:
|
|
371
|
+
raise ValueError(f"{self.scheme} needs calibration data")
|
|
372
|
+
return self
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
class VlmParityTolerances(_Strict):
|
|
376
|
+
"""Bounds on how much worse the candidate may be than the bf16 reference."""
|
|
377
|
+
|
|
378
|
+
accuracy_drop_max: float = Field(0.02, ge=0, le=1)
|
|
379
|
+
iou_drop_max: float = Field(0.05, ge=0, le=1)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
class VlmParityConfig(_Strict):
|
|
383
|
+
"""``pathoinfer convert vlm-parity``: both models answer ``eval`` (rows with
|
|
384
|
+
``answer``; ``box`` for grounding models) through OpenAI-compatible vLLM servers."""
|
|
385
|
+
|
|
386
|
+
eval: VqaDataConfig
|
|
387
|
+
tolerances: VlmParityTolerances = VlmParityTolerances()
|
|
388
|
+
max_tokens: int = Field(64, gt=0)
|
|
389
|
+
concurrency: int = Field(8, gt=0)
|
|
390
|
+
timeout_s: float = Field(120.0, gt=0)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def load_yaml[T: BaseModel](path: str | Path, model: type[T]) -> T:
|
|
394
|
+
with open(path) as f:
|
|
395
|
+
return model.model_validate(yaml.safe_load(f))
|