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,340 @@
|
|
|
1
|
+
# pathoinfer - convert
|
|
2
|
+
|
|
3
|
+
Turns a full-precision model folder into faster variants for deployment: FP16, INT8 or
|
|
4
|
+
FP8 ONNX and TensorRT plans for tile models, and FP8 or 4-bit vision-language models
|
|
5
|
+
(VLMs) for vLLM. Every step writes a **new** model folder
|
|
6
|
+
and never edits one in place. A variant is trusted only after `convert parity` has
|
|
7
|
+
compared it with its reference through the real stitchers and written it with the result
|
|
8
|
+
in its card.
|
|
9
|
+
|
|
10
|
+
Post-training quantisation (PTQ) only: quantisation-aware training belongs in training
|
|
11
|
+
(pathotrain).
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install "pathoinfer[onnx,convert]" # FP16, ONNX Runtime INT8, ModelOpt INT8/FP8
|
|
17
|
+
pip install "pathoinfer[onnx,convert,trt]" # plus TensorRT plans (several GB)
|
|
18
|
+
pip install "pathoinfer[mlflow]" # to register passed variants
|
|
19
|
+
pip install "pathoinfer[vlm-convert,vllm-client]" # VLMs: llm-compressor, PEFT, httpx
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`[convert]` lists the helpers NVIDIA ModelOpt's ONNX quantiser needs instead of
|
|
23
|
+
`nvidia-modelopt[onnx]`: that extra pins `onnxruntime-gpu<1.31` and `onnx~=1.21`, which
|
|
24
|
+
clash with the `onnxruntime-gpu>=1.31.1` the workspace uses. The listed versions are
|
|
25
|
+
verified with onnxruntime-gpu 1.31.1 and onnx 1.23.2 (`tests/convert`).
|
|
26
|
+
|
|
27
|
+
## Workflow
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
# 1. Convert (each writes a new folder).
|
|
31
|
+
pathoinfer convert fp16 models/tumour-seg models/tumour-seg-fp16
|
|
32
|
+
pathoinfer convert ptq models/tumour-seg models/tumour-seg-int8 --config quant.yaml
|
|
33
|
+
|
|
34
|
+
# 2. Optionally build a plan for this GPU from a converted ONNX folder.
|
|
35
|
+
pathoinfer convert trt models/tumour-seg-fp16 models/tumour-seg-fp16-plan --batch 1 32 64
|
|
36
|
+
|
|
37
|
+
# 3. Gate: compare with the reference; on a pass write the final folder (and register it).
|
|
38
|
+
pathoinfer convert parity models/tumour-seg models/tumour-seg-fp16-plan \
|
|
39
|
+
models/tumour-seg-fp16-blackwell --config parity.yaml \
|
|
40
|
+
--register tumour-seg --alias fp16-blackwell --report parity.json
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`convert parity` exits 0 on a pass and 1 on a fail. A fail writes no folder and
|
|
44
|
+
registers nothing.
|
|
45
|
+
|
|
46
|
+
Every converted card records `precision`, `version` (with a suffix such as `+fp16`,
|
|
47
|
+
`+int8` or `+trt-nvidia-geforce-rtx-5090-sm120`) and `provenance.parent_model`
|
|
48
|
+
(`name@version` of the source). Quantised cards also record
|
|
49
|
+
`provenance.calibration_set_hash` and the settings under
|
|
50
|
+
`provenance.source_metadata.quantisation`. Plans record the GPU, compute capability,
|
|
51
|
+
TensorRT version and profile under `provenance.source_metadata.tensorrt`.
|
|
52
|
+
|
|
53
|
+
## FP16 (`fp16.py`)
|
|
54
|
+
|
|
55
|
+
`pathoinfer convert fp16 SOURCE OUT [--fp16-io] [--keep-fp32 OP ...]`
|
|
56
|
+
|
|
57
|
+
ONNX Runtime's converter turns weights and activations into float16. Op types on its
|
|
58
|
+
default block list, plus `--keep-fp32`, stay float32 with Casts around them. Graph
|
|
59
|
+
inputs and outputs stay float32 unless you pass `--fp16-io`, in which case the card's
|
|
60
|
+
`input.dtype` becomes `float16`. The source must be an FP32 ONNX model.
|
|
61
|
+
|
|
62
|
+
## INT8 and FP8 (`ptq.py`)
|
|
63
|
+
|
|
64
|
+
`pathoinfer convert ptq SOURCE OUT --config quant.yaml`
|
|
65
|
+
|
|
66
|
+
```yaml
|
|
67
|
+
# quant.yaml
|
|
68
|
+
precision: int8 # int8 or fp8 (fp8 needs engine: modelopt)
|
|
69
|
+
engine: modelopt # modelopt (TensorRT targets) or ort (runs in ONNX Runtime)
|
|
70
|
+
method: entropy # entropy, minmax or percentile
|
|
71
|
+
percentile: 99.999 # for method: percentile
|
|
72
|
+
calibration:
|
|
73
|
+
slides: calibration/*.svs # path, glob, .txt/.csv/.parquet list, or a list of these
|
|
74
|
+
tiles: 512 # spread evenly over the slides; 500-1000 is typical
|
|
75
|
+
seed: 0
|
|
76
|
+
keep_ops: [LayerNormalization, Softmax] # op types kept in high precision
|
|
77
|
+
keep_nodes: ["*attn*", "*attention*"] # node-name globs (lower case) kept too
|
|
78
|
+
keep_ends: true # also keep the first and last Conv/MatMul/Gemm
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Calibration tiles are read through patchology at the card's tile size and mpp (tissue
|
|
82
|
+
tiles, chosen at random with `seed`) and preprocessed exactly as at inference. List
|
|
83
|
+
slides that cover your scanners, stains and tissue types. The calibration-set hash
|
|
84
|
+
identifies exactly which tiles were read.
|
|
85
|
+
|
|
86
|
+
| Engine | Precisions | Kept layers run in | Use for |
|
|
87
|
+
|---|---|---|---|
|
|
88
|
+
| `modelopt` (NVIDIA ModelOpt) | INT8, FP8 | FP16 | TensorRT plans; FP8 on Hopper and Blackwell |
|
|
89
|
+
| `ort` (ONNX Runtime) | INT8 | FP32 | INT8 that must run in ONNX Runtime without TensorRT |
|
|
90
|
+
|
|
91
|
+
ModelOpt runs in a child process. While it quantises, it patches ONNX Runtime's
|
|
92
|
+
calibration classes for the rest of the process it runs in, which would break any later
|
|
93
|
+
ONNX Runtime quantisation. It also skips convolutions with very few channels, so a tiny
|
|
94
|
+
network may come out unquantised. During calibration ONNX Runtime may log that
|
|
95
|
+
`libnvinfer.so.10` is missing (its TensorRT provider wants TensorRT 10, `[trt]` installs
|
|
96
|
+
11); this is harmless, and calibration falls back to CUDA or CPU.
|
|
97
|
+
|
|
98
|
+
## TensorRT plans (`tensorrt.py`)
|
|
99
|
+
|
|
100
|
+
`pathoinfer convert trt SOURCE OUT [--batch MIN OPT MAX] [--workspace-gb GB] [--device 0]`
|
|
101
|
+
|
|
102
|
+
A plan is a serialised TensorRT engine for one GPU architecture and TensorRT version.
|
|
103
|
+
It is built as a strongly typed network, so its precision is the ONNX graph's: FP32,
|
|
104
|
+
FP16 from `convert fp16`, or INT8/FP8 from `convert ptq`. The plan therefore computes
|
|
105
|
+
what parity checks. One optimisation profile covers batch sizes `MIN` to `MAX`, tuned
|
|
106
|
+
for `OPT`. Runs must use a `batch_size` within it. `--workspace-gb` caps the memory
|
|
107
|
+
TensorRT's tactics may use while building; unset, it is the GPU's memory (4 GB was too
|
|
108
|
+
little for an FP32 HoVer-Net: "Could not find any implementation").
|
|
109
|
+
|
|
110
|
+
Built plans are cached in `~/.cache/pathoinfer/plans`, keyed by model hash, GPU,
|
|
111
|
+
compute capability, TensorRT version, precision and profile, so building the same plan
|
|
112
|
+
again copies the cached one. Plan folders (`framework: tensorrt`) run in
|
|
113
|
+
`pathoinfer run` like any other model, on the GPU they were built for.
|
|
114
|
+
|
|
115
|
+
## Parity gate (`parity.py`)
|
|
116
|
+
|
|
117
|
+
`pathoinfer convert parity REFERENCE CANDIDATE OUT --config parity.yaml [--register NAME --alias ALIAS] [--tracking-uri URI] [--report FILE]`
|
|
118
|
+
|
|
119
|
+
```yaml
|
|
120
|
+
# parity.yaml
|
|
121
|
+
slides: parity/*.svs # slides held out from calibration
|
|
122
|
+
window_tiles: 6 # mini-slides: windows of 6 x 6 grid tiles around tissue
|
|
123
|
+
windows: 2 # per slide
|
|
124
|
+
seed: 0
|
|
125
|
+
reference_device: auto # the full-precision model
|
|
126
|
+
candidate: {device: cuda, batch_size: 16}
|
|
127
|
+
iou: 0.5 # detection matching
|
|
128
|
+
tolerances:
|
|
129
|
+
dice_min: 0.97 # segmentation: Dice per class, polygon level
|
|
130
|
+
f1_min: 0.97 # detection: F1 per class
|
|
131
|
+
count_diff_max: 0.03 # detection: |n_candidate - n_reference| / n_reference per class
|
|
132
|
+
auc_min: 0.99 # classification: one-vs-rest AUC per class
|
|
133
|
+
segmentation: {output_mpp: 2.0} # stitch settings, as in a run config
|
|
134
|
+
detection: {score_threshold: null}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Both models run on the same tiles: mini-slides, read once through patchology. Each
|
|
138
|
+
window's outputs go through the task's stitcher (cores, seams, polygons) for each model,
|
|
139
|
+
and the stitched results are compared per class, pooled over windows:
|
|
140
|
+
|
|
141
|
+
| Task | Metric | Pass when the worst class |
|
|
142
|
+
|---|---|---|
|
|
143
|
+
| Segmentation | Dice of the class's polygons, `2 \|A ∩ B\| / (\|A\| + \|B\|)` | `dice_min` >= tolerance |
|
|
144
|
+
| Detection | F1 of detections matched one to one by box IoU >= `iou` | `f1_min` >= tolerance |
|
|
145
|
+
| Detection | Relative count difference | `count_diff_max` <= tolerance |
|
|
146
|
+
| Classification | AUC of the candidate's core probabilities against the reference's argmax | `auc_min` >= tolerance |
|
|
147
|
+
|
|
148
|
+
On a pass, the candidate folder is copied to `OUT` and its card gains
|
|
149
|
+
`provenance.parity`: the reference (`name@version`), the tile-set hash, the metric
|
|
150
|
+
values, the tolerances and the time of the check. With `--register NAME --alias ALIAS`
|
|
151
|
+
the new folder is logged to MLflow, added as a version of `NAME`, and `ALIAS` (for
|
|
152
|
+
example `fp16-blackwell` or `int8-l4`) points at it. Load it later as
|
|
153
|
+
`models:/NAME@ALIAS`.
|
|
154
|
+
|
|
155
|
+
On a fail, the report lists the failing metrics, the worst class of each metric and,
|
|
156
|
+
when both models are ONNX, the five intermediate tensors whose values differ most from
|
|
157
|
+
the reference's. These are the layers to keep in high precision (`keep_ops`,
|
|
158
|
+
`keep_nodes`) before trying again. `--report` writes the report as JSON in both cases.
|
|
159
|
+
|
|
160
|
+
Choose tolerances for the model, not for the method. A class that covers a small share
|
|
161
|
+
of the slide amplifies a few flipped pixels into a large Dice drop: on a random test
|
|
162
|
+
network with 0.5% tumour pixels, INT8 logits within 5.5% of FP32, with 99.7% of pixels
|
|
163
|
+
agreeing, still gave a Dice of 0.67.
|
|
164
|
+
|
|
165
|
+
## Vision-language models (`vlm.py`, `vlm_parity.py`)
|
|
166
|
+
|
|
167
|
+
For Qwen3-VL and SmolVLM fine-tuned with TRL + PEFT. pathoinfer never imports vllm: it
|
|
168
|
+
writes folders that `vllm serve` loads and talks to vLLM servers over HTTP. Run vLLM in
|
|
169
|
+
its own environment; it pins its own torch and transformers. When to choose `fp8`,
|
|
170
|
+
`w4a16-awq` or `w4a16-gptq`, and measurements on Qwen3-VL-2B, are in
|
|
171
|
+
[docs/vlm_quantisation.md](../../../docs/vlm_quantisation.md).
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
pathoinfer convert vlm-merge Qwen/Qwen3-VL-2B-Instruct runs/lora-final models/pvqa-bf16 \
|
|
175
|
+
--card card.yaml
|
|
176
|
+
pathoinfer convert vlm models/pvqa-bf16 models/pvqa-fp8 --config vlm.yaml
|
|
177
|
+
# with `vllm serve models/pvqa-bf16 --port 8000` and `vllm serve models/pvqa-fp8 --port 8001` running:
|
|
178
|
+
pathoinfer convert vlm-parity models/pvqa-bf16 models/pvqa-fp8 models/pvqa-fp8-blackwell \
|
|
179
|
+
--config vlm_parity.yaml \
|
|
180
|
+
--reference-url http://localhost:8000 --candidate-url http://localhost:8001 \
|
|
181
|
+
[--register pvqa --alias fp8-blackwell] [--tracking-uri URI] [--report parity.json]
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
### Merge (`vlm-merge`)
|
|
185
|
+
|
|
186
|
+
`merge_lora(base, adapter, out, card)` loads the base model (a local folder or Hugging
|
|
187
|
+
Face Hub id) in bf16, applies the PEFT adapter, merges it into the weights and saves a
|
|
188
|
+
safetensors folder with the base model's processor. `--card` gives the card fields the
|
|
189
|
+
weights cannot:
|
|
190
|
+
|
|
191
|
+
```yaml
|
|
192
|
+
# card.yaml
|
|
193
|
+
name: pvqa
|
|
194
|
+
version: "1"
|
|
195
|
+
input: {tile_size: 448, mpp: 0.5} # how slide crops were made for fine-tuning
|
|
196
|
+
output: {grounding: false} # true if answers contain boxes
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
The folder gets a `VqaCard` (task `vqa`, framework `hf`, file `config.json`) with
|
|
200
|
+
`architecture` from the model config, `precision: bf16` and the base model as
|
|
201
|
+
`parent_model`. `registry.loader.load_vlm` reads it; `load_model` refuses it, because
|
|
202
|
+
tile code paths cannot run a VLM.
|
|
203
|
+
|
|
204
|
+
### Quantise (`vlm`)
|
|
205
|
+
|
|
206
|
+
```yaml
|
|
207
|
+
# vlm.yaml (VlmQuantConfig)
|
|
208
|
+
scheme: w4a16-gptq # fp8, w4a16-awq or w4a16-gptq
|
|
209
|
+
calibration: # VqaDataConfig; needed for the w4a16 schemes
|
|
210
|
+
path: data/calibration/pairs.jsonl # .jsonl, .csv or .parquet: image, question (, answer)
|
|
211
|
+
samples: 256 # seeded random subset; null for every row
|
|
212
|
+
seed: 0
|
|
213
|
+
max_seq_len: 2048
|
|
214
|
+
extra_ignore: [] # more module patterns to keep in bf16
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
`quantise_vlm(source, out, cfg)` runs one llm-compressor recipe on the **language model
|
|
218
|
+
only**:
|
|
219
|
+
|
|
220
|
+
| Scheme | Recipe | Calibration | Card `precision` |
|
|
221
|
+
|---|---|---|---|
|
|
222
|
+
| `fp8` | `QuantizationModifier`, `FP8_DYNAMIC` (W8A8, per-token dynamic activations) | none | `fp8` |
|
|
223
|
+
| `w4a16-awq` | `AWQModifier` (smoothing) then `QuantizationModifier`, `W4A16_ASYM` | image + question pairs | `int4` |
|
|
224
|
+
| `w4a16-gptq` | `GPTQModifier`, `W4A16` | image + question pairs | `int4` |
|
|
225
|
+
|
|
226
|
+
- **Ignore list** (`ignore_list`). Built from the model's module names: every child of
|
|
227
|
+
`model` except the language model (`model.language_model` in Qwen3-VL,
|
|
228
|
+
`model.text_model` in SmolVLM), plus `lm_head`. It is checked before quantising: each
|
|
229
|
+
pattern must match a Linear layer, and every quantised layer must sit inside the
|
|
230
|
+
language model. Qwen3-VL keeps `model.visual` (blocks, `merger`,
|
|
231
|
+
`deepstack_merger_list`); SmolVLM keeps `model.vision_model` and `model.connector`.
|
|
232
|
+
- **AWQ mappings** (`awq_mappings`). llm-compressor 0.15 has none for the VLM classes, so
|
|
233
|
+
pathoinfer uses the Qwen3/Llama decoder pairs (`input_layernorm` -> q/k/v,
|
|
234
|
+
`v_proj` -> `o_proj`, `post_attention_layernorm` -> gate/up, `up_proj` -> `down_proj`),
|
|
235
|
+
anchored inside the language model so the similarly named vision layers are left
|
|
236
|
+
alone. Each must match a module, or the run stops.
|
|
237
|
+
- **Calibration** (`load_pairs`). Rows are pathology crops made the way the model saw
|
|
238
|
+
them in fine-tuning, with questions (and answers, which are appended as the assistant
|
|
239
|
+
turn). Images are read with OpenCV. Each pair goes through the model's processor and
|
|
240
|
+
chat template, one sample at a time, and the decoder layers are calibrated in sequence.
|
|
241
|
+
The calibration-set hash covers each image's content and question, so renaming a file
|
|
242
|
+
does not change it, but changing its pixels does.
|
|
243
|
+
|
|
244
|
+
The output folder holds compressed-tensors safetensors (`float-quantized` for FP8,
|
|
245
|
+
`pack-quantized` for W4A16), the processor and a card with `precision`, version suffix
|
|
246
|
+
(`+fp8`, `+w4a16-awq`, `+w4a16-gptq`), `parent_model`, `calibration_set_hash` (null for
|
|
247
|
+
FP8) and `source_metadata.quantisation` (scheme, ignore patterns, number of quantised
|
|
248
|
+
layers).
|
|
249
|
+
|
|
250
|
+
### Parity (`vlm-parity`)
|
|
251
|
+
|
|
252
|
+
```yaml
|
|
253
|
+
# vlm_parity.yaml (VlmParityConfig)
|
|
254
|
+
eval:
|
|
255
|
+
path: data/pathvqa_eval/pairs.jsonl # image, question, answer (, box in image pixels)
|
|
256
|
+
samples: null
|
|
257
|
+
tolerances:
|
|
258
|
+
accuracy_drop_max: 0.02
|
|
259
|
+
iou_drop_max: 0.05
|
|
260
|
+
max_tokens: 64
|
|
261
|
+
concurrency: 8 # questions in flight per server
|
|
262
|
+
timeout_s: 120
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
`gate(reference, candidate, cfg, out, reference_url, candidate_url)` asks both servers
|
|
266
|
+
every eval question greedily (temperature 0) through `runtime.remote.vllm.VllmClient`,
|
|
267
|
+
an OpenAI-compatible client that sends each crop as a data URL. It scores:
|
|
268
|
+
|
|
269
|
+
- **accuracy**: exact match with the true answer after `normalise` (boxes in `[...]`
|
|
270
|
+
dropped, lower case, punctuation and a/an/the removed), as PathVQA scores answers;
|
|
271
|
+
- **IoU**, for grounding cards on rows with a `box`: `parse_box` takes the first box
|
|
272
|
+
that `runtime.vlm.parse_boxes` reads (Qwen-VL's `{"bbox_2d": [...]}` JSON, else a
|
|
273
|
+
bracketed box of four numbers) in the card's `box_format` and `box_units`
|
|
274
|
+
(`per_mille`, `normalised` or `pixel`), as image pixels clipped to the image.
|
|
275
|
+
|
|
276
|
+
Metrics are `accuracy_reference`, `accuracy`, `accuracy_drop` and, for grounding,
|
|
277
|
+
`iou_reference`, `iou`, `iou_drop`. The candidate passes when each drop is within its
|
|
278
|
+
tolerance. A pass copies it to the new folder `out` with `provenance.parity` (reference,
|
|
279
|
+
eval-set hash, metrics, tolerances, time) and, with `--register NAME --alias ALIAS`,
|
|
280
|
+
registers it in MLflow. A fail lists up to five questions the reference answered right
|
|
281
|
+
and the candidate wrong, exits 1, and writes and registers nothing.
|
|
282
|
+
|
|
283
|
+
`check(reference, candidate, cfg, ask_reference, ask_candidate)` takes any two
|
|
284
|
+
`(image, question) -> answer` functions, so parity can also run against other servers.
|
|
285
|
+
|
|
286
|
+
## Python
|
|
287
|
+
|
|
288
|
+
```python
|
|
289
|
+
from pathlib import Path
|
|
290
|
+
|
|
291
|
+
from pathoinfer.config import ParityConfig, QuantConfig, load_yaml
|
|
292
|
+
from pathoinfer.convert.fp16 import to_fp16
|
|
293
|
+
from pathoinfer.convert.parity import gate
|
|
294
|
+
from pathoinfer.convert.ptq import quantise
|
|
295
|
+
from pathoinfer.convert.tensorrt import build_plan
|
|
296
|
+
|
|
297
|
+
to_fp16("models/tumour-seg", Path("models/tumour-seg-fp16"))
|
|
298
|
+
quantise("models/tumour-seg", Path("models/tumour-seg-int8"), load_yaml("quant.yaml", QuantConfig))
|
|
299
|
+
build_plan("models/tumour-seg-fp16", Path("models/tumour-seg-fp16-plan"), max_batch=64)
|
|
300
|
+
report = gate(
|
|
301
|
+
"models/tumour-seg",
|
|
302
|
+
"models/tumour-seg-fp16-plan",
|
|
303
|
+
load_yaml("parity.yaml", ParityConfig),
|
|
304
|
+
Path("models/tumour-seg-fp16-blackwell"),
|
|
305
|
+
register=("tumour-seg", "fp16-blackwell"),
|
|
306
|
+
)
|
|
307
|
+
print(report.summary())
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
## Testing
|
|
311
|
+
|
|
312
|
+
`tests/convert/test_convert.py` (needs `onnx`; runs in CI):
|
|
313
|
+
|
|
314
|
+
- the fixture model converts to FP16 and passes parity, and the passed card records it;
|
|
315
|
+
- a deliberately broken conversion (last layer negated) fails parity, names `logits` as
|
|
316
|
+
the worst layer, writes nothing and registers nothing;
|
|
317
|
+
- ONNX Runtime INT8 writes Q/DQ nodes and a reproducible calibration hash;
|
|
318
|
+
- parity metrics: AUC, one-to-one detection matching, and F1, count difference and AUC
|
|
319
|
+
through the real detection and heatmap stitchers;
|
|
320
|
+
- the CLI, and MLflow registration under an alias (with full MLflow).
|
|
321
|
+
|
|
322
|
+
`tests/convert/test_vlm.py` (needs transformers; recipes also llm-compressor, merging
|
|
323
|
+
PEFT): on tiny random Qwen3-VL and SmolVLM models, the ignore list keeps exactly the
|
|
324
|
+
vision encoder, projector and `lm_head`; AWQ mappings stay inside the language model;
|
|
325
|
+
the three recipes build and llm-compressor accepts them; a LoRA merge equals PEFT's own
|
|
326
|
+
merge and writes a valid card; quantised cards record precision, parent and calibration
|
|
327
|
+
hash; calibration pairs are sampled and hashed by content; answers normalise, boxes parse
|
|
328
|
+
in every unit; parity passes, fails on accuracy and on box drift, and names the
|
|
329
|
+
regressed questions; and the vLLM client sends the image and greedy settings.
|
|
330
|
+
|
|
331
|
+
`tests/convert/test_vlm_full.py` (markers `gpu` and `slow`): quantises a real VLM with
|
|
332
|
+
each scheme and gates it through two vLLM servers. Set `PATHOINFER_VLM_MODEL` (a bf16
|
|
333
|
+
folder with a VqaCard), `PATHOINFER_VLM_PAIRS` and, for parity,
|
|
334
|
+
`PATHOINFER_VLM_CANDIDATE`, `PATHOINFER_VLLM_REFERENCE_URL` and
|
|
335
|
+
`PATHOINFER_VLLM_CANDIDATE_URL`; otherwise the tests skip.
|
|
336
|
+
|
|
337
|
+
`tests/convert/test_nvidia.py` (needs ModelOpt; plans also need TensorRT and a GPU):
|
|
338
|
+
ModelOpt INT8 on a 32-channel network; FP16 plans build, come from the cache the second
|
|
339
|
+
time and pass parity; ModelOpt INT8 and FP8 plans run through parity; and ONNX Runtime
|
|
340
|
+
quantisation still works after ModelOpt in the same process.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"""Offline conversion of model folders into faster variants, each a new model folder:
|
|
2
|
+
``fp16`` (ONNX FP32 -> FP16), ``ptq`` (INT8/FP8 static PTQ with ModelOpt or ONNX Runtime),
|
|
3
|
+
``tensorrt`` (plans per GPU) and ``parity`` (the gate a variant must pass before use).
|
|
4
|
+
``vlm`` (VLM weights) lands after v0.3."""
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Shared by the converters: write a variant model folder, sample calibration tiles, pick
|
|
2
|
+
the layers to keep in high precision."""
|
|
3
|
+
|
|
4
|
+
import fnmatch
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from loguru import logger
|
|
15
|
+
from numpy.typing import NDArray
|
|
16
|
+
|
|
17
|
+
from patchology import open_slide
|
|
18
|
+
from pathoinfer.registry.model_card import ModelCard, parse_card
|
|
19
|
+
from pathoinfer.tiling.grid import build_grid, read_tile
|
|
20
|
+
|
|
21
|
+
CARD_FILE = "model_card.json"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def write_variant(
|
|
25
|
+
card: ModelCard, out: Path, write_model: Callable[[Path], object], **updates: Any
|
|
26
|
+
) -> ModelCard:
|
|
27
|
+
"""Write ``out/<file>`` with ``write_model`` and a card derived from ``card``:
|
|
28
|
+
``updates`` (dotted keys such as ``input.dtype``) applied and ``parent_model`` set.
|
|
29
|
+
``out`` must not exist; it appears complete or not at all."""
|
|
30
|
+
if out.exists():
|
|
31
|
+
raise FileExistsError(f"{out} exists; choose a new folder")
|
|
32
|
+
data = card.model_dump(mode="json")
|
|
33
|
+
data["provenance"] = data["provenance"] | {
|
|
34
|
+
"parent_model": f"{card.name}@{card.version}",
|
|
35
|
+
"parity": None,
|
|
36
|
+
}
|
|
37
|
+
for key, value in updates.items():
|
|
38
|
+
target = data
|
|
39
|
+
*path, leaf = key.split(".")
|
|
40
|
+
for part in path:
|
|
41
|
+
target = target[part]
|
|
42
|
+
target[leaf] = value
|
|
43
|
+
variant = parse_card(data)
|
|
44
|
+
partial = out.with_name(out.name + ".partial")
|
|
45
|
+
shutil.rmtree(partial, ignore_errors=True)
|
|
46
|
+
partial.mkdir(parents=True)
|
|
47
|
+
write_model(partial / variant.file)
|
|
48
|
+
(partial / CARD_FILE).write_text(variant.model_dump_json(indent=2) + "\n")
|
|
49
|
+
os.replace(partial, out)
|
|
50
|
+
logger.info("wrote {} ({} {}, {})", out, variant.name, variant.version, variant.precision)
|
|
51
|
+
return variant
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def calibration_tiles(
|
|
55
|
+
card: ModelCard, slides: list[Path], n_tiles: int, seed: int = 0, backend: str = "openslide"
|
|
56
|
+
) -> tuple[NDArray[np.uint8], str]:
|
|
57
|
+
"""``n_tiles`` uint8 NHWC tiles at the card's tile size and mpp, spread evenly over
|
|
58
|
+
``slides`` (tissue tiles only, chosen at random with ``seed``), and a hash of exactly
|
|
59
|
+
which tiles were read (slide ids, positions, tiling)."""
|
|
60
|
+
if not slides:
|
|
61
|
+
raise ValueError("no calibration slides")
|
|
62
|
+
rng = np.random.default_rng(seed)
|
|
63
|
+
per_slide = np.full(len(slides), n_tiles // len(slides))
|
|
64
|
+
per_slide[: n_tiles % len(slides)] += 1
|
|
65
|
+
tiles, keys = [], []
|
|
66
|
+
for path, count in zip(slides, per_slide, strict=True):
|
|
67
|
+
with open_slide(path, backend) as slide: # type: ignore[arg-type]
|
|
68
|
+
grid = build_grid(slide, card.input.tile_size, card.input.mpp, icc=card.input.icc)
|
|
69
|
+
if not grid.tiles:
|
|
70
|
+
logger.warning("{}: no tissue tiles; skipped for calibration", path.name)
|
|
71
|
+
continue
|
|
72
|
+
picks = rng.choice(len(grid.tiles), size=min(count, len(grid.tiles)), replace=False)
|
|
73
|
+
for i in sorted(picks):
|
|
74
|
+
spec = grid.tiles[i]
|
|
75
|
+
tiles.append(read_tile(slide, grid, spec))
|
|
76
|
+
keys.append((grid.slide_id, spec.x, spec.y))
|
|
77
|
+
if not tiles:
|
|
78
|
+
raise ValueError("no tissue tiles in the calibration slides")
|
|
79
|
+
blob = json.dumps(
|
|
80
|
+
{"tiles": keys, "tile_size": card.input.tile_size, "mpp": card.input.mpp}
|
|
81
|
+
).encode()
|
|
82
|
+
logger.info("calibration: {} tiles from {} slides", len(tiles), len(slides))
|
|
83
|
+
return np.stack(tiles), hashlib.sha256(blob).hexdigest()[:16]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def match_nodes(
|
|
87
|
+
nodes: list[tuple[str, str]], op_types: list[str], name_patterns: list[str], ends: bool
|
|
88
|
+
) -> list[str]:
|
|
89
|
+
"""Names of graph nodes (``(name, op_type)`` in topological order) to keep in high
|
|
90
|
+
precision: those whose op type is in ``op_types``, whose name matches a glob in
|
|
91
|
+
``name_patterns``, and with ``ends`` the first and last compute node (Conv, MatMul,
|
|
92
|
+
Gemm)."""
|
|
93
|
+
keep = {n for n, op in nodes if op in op_types}
|
|
94
|
+
keep |= {n for n, _ in nodes for p in name_patterns if fnmatch.fnmatch(n.lower(), p)}
|
|
95
|
+
compute = [n for n, op in nodes if op in ("Conv", "ConvTranspose", "MatMul", "Gemm")]
|
|
96
|
+
if ends and compute:
|
|
97
|
+
keep |= {compute[0], compute[-1]}
|
|
98
|
+
return [n for n, _ in nodes if n in keep]
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""ONNX FP32 -> FP16 with ONNX Runtime's converter.
|
|
2
|
+
|
|
3
|
+
Weights and activations become float16 except for blocked op types, which stay float32
|
|
4
|
+
with Casts around them. ``keep_io_types`` keeps the graph's inputs and outputs float32,
|
|
5
|
+
so preprocessing and stitchers see the same dtypes as before; without it the card's
|
|
6
|
+
``input.dtype`` becomes ``float16``.
|
|
7
|
+
|
|
8
|
+
Models over 2 GB keep their weights in a file beside the graph. Protobuf cannot hold
|
|
9
|
+
them in memory as one message, so shapes are inferred from the file
|
|
10
|
+
(``infer_shapes_path``) and an FP16 model over ``EXTERNAL_BYTES`` is saved with its
|
|
11
|
+
weights in ``<file>.data``.
|
|
12
|
+
|
|
13
|
+
Weights above FP16's range would be clipped to 65504 by the converter, silently: HoVer-Net's
|
|
14
|
+
decoder BatchNorms hold running variances up to 3e7, and clipping them scaled their
|
|
15
|
+
outputs up to 22x (parity F1 0). So a BatchNorm whose parameters do not fit is first
|
|
16
|
+
rewritten to the same affine map in a form that does (``scale = gamma / sqrt(var + eps)``
|
|
17
|
+
as gamma, ``beta - mean * scale`` as beta, mean 0, variance 1, epsilon 0), and any other
|
|
18
|
+
out-of-range weight feeding an FP16 op raises, naming it.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import tempfile
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
from pathoinfer._extras import extra, require
|
|
28
|
+
from pathoinfer._logging import log_call
|
|
29
|
+
from pathoinfer.convert.common import write_variant
|
|
30
|
+
from pathoinfer.registry.loader import load_model
|
|
31
|
+
from pathoinfer.registry.model_card import ModelCard
|
|
32
|
+
|
|
33
|
+
EXTERNAL_BYTES = 2**30 # well under protobuf's 2 GB message limit
|
|
34
|
+
FP16_MAX = float(np.finfo(np.float16).max)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@log_call
|
|
38
|
+
def to_fp16(
|
|
39
|
+
source: str | Path,
|
|
40
|
+
out: Path,
|
|
41
|
+
*,
|
|
42
|
+
keep_io_types: bool = True,
|
|
43
|
+
keep_fp32_ops: list[str] | None = None,
|
|
44
|
+
version_suffix: str = "+fp16",
|
|
45
|
+
) -> ModelCard:
|
|
46
|
+
"""Convert the ONNX model at ``source`` (any model source) to FP16 in the new folder
|
|
47
|
+
``out``. ``keep_fp32_ops`` adds op types to ONNX Runtime's default block list."""
|
|
48
|
+
onnx = require("onnx", extra("convert"))
|
|
49
|
+
float16 = require("onnxruntime.transformers.float16", extra("onnx"))
|
|
50
|
+
card, model_dir = load_model(str(source))
|
|
51
|
+
if card.framework != "onnx" or card.precision != "fp32":
|
|
52
|
+
raise ValueError(f"expected an fp32 ONNX model, got {card.framework} {card.precision}")
|
|
53
|
+
blocked = sorted({*float16.DEFAULT_OP_BLOCK_LIST, *(keep_fp32_ops or [])})
|
|
54
|
+
with tempfile.TemporaryDirectory() as tmp: # the converter's own inference is in memory
|
|
55
|
+
inferred = Path(tmp) / "inferred.onnx"
|
|
56
|
+
onnx.shape_inference.infer_shapes_path(str(model_dir / card.file), str(inferred))
|
|
57
|
+
model = onnx.load(inferred, load_external_data=False)
|
|
58
|
+
onnx.load_external_data_for_model(model, str(model_dir))
|
|
59
|
+
if "BatchNormalization" not in blocked:
|
|
60
|
+
fit_batchnorms(model)
|
|
61
|
+
check_range(model, set(blocked))
|
|
62
|
+
model = float16.convert_float_to_float16(
|
|
63
|
+
model, keep_io_types=keep_io_types, op_block_list=blocked, disable_shape_infer=True
|
|
64
|
+
)
|
|
65
|
+
external = sum(len(t.raw_data) for t in model.graph.initializer) > EXTERNAL_BYTES
|
|
66
|
+
|
|
67
|
+
def save(path: Path) -> None:
|
|
68
|
+
if external:
|
|
69
|
+
onnx.save(
|
|
70
|
+
model,
|
|
71
|
+
path,
|
|
72
|
+
save_as_external_data=True,
|
|
73
|
+
location=path.name + ".data",
|
|
74
|
+
size_threshold=0,
|
|
75
|
+
)
|
|
76
|
+
else:
|
|
77
|
+
onnx.save(model, path)
|
|
78
|
+
|
|
79
|
+
updates: dict[str, object] = {"precision": "fp16", "version": card.version + version_suffix}
|
|
80
|
+
if not keep_io_types:
|
|
81
|
+
updates["input.dtype"] = "float16"
|
|
82
|
+
return write_variant(card, out, save, **updates)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def fit_batchnorms(model: Any) -> None:
|
|
86
|
+
"""Rewrite, in place, each BatchNorm whose parameters exceed FP16's range to the same
|
|
87
|
+
affine map with parameters that fit (see the module docstring)."""
|
|
88
|
+
from onnx import helper, numpy_helper
|
|
89
|
+
|
|
90
|
+
init = {i.name: i for i in model.graph.initializer}
|
|
91
|
+
for node in model.graph.node:
|
|
92
|
+
params = node.input[1:5]
|
|
93
|
+
if node.op_type != "BatchNormalization" or not all(n in init for n in params):
|
|
94
|
+
continue
|
|
95
|
+
gamma, beta, mean, var = (numpy_helper.to_array(init[n]).astype(np.float64) for n in params)
|
|
96
|
+
if max(np.abs(a).max() for a in (gamma, beta, mean, var)) <= FP16_MAX:
|
|
97
|
+
continue
|
|
98
|
+
eps = next((a.f for a in node.attribute if a.name == "epsilon"), 1e-5)
|
|
99
|
+
scale = gamma / np.sqrt(var + eps)
|
|
100
|
+
values = (scale, beta - mean * scale, np.zeros_like(mean), np.ones_like(var))
|
|
101
|
+
dtype = numpy_helper.to_array(init[params[0]]).dtype
|
|
102
|
+
names = [f"{n}_fp16_fit" for n in params] # new names: the originals may be shared
|
|
103
|
+
model.graph.initializer.extend(
|
|
104
|
+
numpy_helper.from_array(v.astype(dtype), n) for v, n in zip(values, names, strict=True)
|
|
105
|
+
)
|
|
106
|
+
node.input[1:5] = names
|
|
107
|
+
kept = [a for a in node.attribute if a.name != "epsilon"]
|
|
108
|
+
del node.attribute[:]
|
|
109
|
+
node.attribute.extend([*kept, helper.make_attribute("epsilon", 0.0)])
|
|
110
|
+
used = {i for node in model.graph.node for i in node.input}
|
|
111
|
+
unused = [i for i in model.graph.initializer if i.name not in used]
|
|
112
|
+
for i in unused:
|
|
113
|
+
model.graph.initializer.remove(i)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def check_range(model: Any, blocked: set[str]) -> None:
|
|
117
|
+
"""Raise if a float weight outside FP16's range feeds an op that becomes FP16."""
|
|
118
|
+
from onnx import numpy_helper
|
|
119
|
+
|
|
120
|
+
consumers: dict[str, set[str]] = {}
|
|
121
|
+
for node in model.graph.node:
|
|
122
|
+
for i in node.input:
|
|
123
|
+
consumers.setdefault(i, set()).add(node.op_type)
|
|
124
|
+
bad = []
|
|
125
|
+
for i in model.graph.initializer:
|
|
126
|
+
ops = consumers.get(i.name, set()) - blocked
|
|
127
|
+
a = numpy_helper.to_array(i)
|
|
128
|
+
if ops and a.dtype.kind == "f" and a.size and np.abs(a).max() > FP16_MAX:
|
|
129
|
+
bad.append(f"{i.name} ({', '.join(sorted(ops))}, max {np.abs(a).max():.3g})")
|
|
130
|
+
if bad:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"{len(bad)} weights exceed FP16's range ({FP16_MAX:g}) and would be clipped: "
|
|
133
|
+
+ "; ".join(bad[:5])
|
|
134
|
+
+ ". Keep their op types in FP32 with --keep-fp32."
|
|
135
|
+
)
|