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.
Files changed (80) hide show
  1. pathoinfer/__init__.py +6 -0
  2. pathoinfer/_extras.py +18 -0
  3. pathoinfer/_logging.py +91 -0
  4. pathoinfer/analysis.py +68 -0
  5. pathoinfer/cli.py +480 -0
  6. pathoinfer/config.py +395 -0
  7. pathoinfer/convert/README.md +340 -0
  8. pathoinfer/convert/__init__.py +4 -0
  9. pathoinfer/convert/common.py +98 -0
  10. pathoinfer/convert/fp16.py +135 -0
  11. pathoinfer/convert/parity.py +484 -0
  12. pathoinfer/convert/ptq.py +163 -0
  13. pathoinfer/convert/tensorrt.py +139 -0
  14. pathoinfer/convert/vlm.py +359 -0
  15. pathoinfer/convert/vlm_parity.py +233 -0
  16. pathoinfer/engine/README.md +134 -0
  17. pathoinfer/engine/__init__.py +3 -0
  18. pathoinfer/engine/pipeline.py +437 -0
  19. pathoinfer/engine/scheduler.py +161 -0
  20. pathoinfer/io/README.md +79 -0
  21. pathoinfer/io/__init__.py +1 -0
  22. pathoinfer/io/interop.py +21 -0
  23. pathoinfer/io/objects.py +232 -0
  24. pathoinfer/io/writers/__init__.py +1 -0
  25. pathoinfer/io/writers/geojson.py +106 -0
  26. pathoinfer/io/writers/overlay.py +102 -0
  27. pathoinfer/io/writers/parquet.py +188 -0
  28. pathoinfer/io/writers/tiff.py +101 -0
  29. pathoinfer/post/README.md +116 -0
  30. pathoinfer/post/__init__.py +1 -0
  31. pathoinfer/post/instances.py +92 -0
  32. pathoinfer/post/nms.py +1 -0
  33. pathoinfer/post/smoothing.py +1 -0
  34. pathoinfer/post/vectorise.py +486 -0
  35. pathoinfer/py.typed +0 -0
  36. pathoinfer/registry/README.md +72 -0
  37. pathoinfer/registry/__init__.py +1 -0
  38. pathoinfer/registry/create.py +71 -0
  39. pathoinfer/registry/legacy.py +71 -0
  40. pathoinfer/registry/loader.py +171 -0
  41. pathoinfer/registry/model_card.py +309 -0
  42. pathoinfer/registry/onnx_info.py +45 -0
  43. pathoinfer/registry/schema/model_card.v1.json +1049 -0
  44. pathoinfer/runtime/README.md +119 -0
  45. pathoinfer/runtime/__init__.py +1 -0
  46. pathoinfer/runtime/base.py +86 -0
  47. pathoinfer/runtime/factory.py +51 -0
  48. pathoinfer/runtime/local/__init__.py +1 -0
  49. pathoinfer/runtime/local/onnx.py +155 -0
  50. pathoinfer/runtime/local/tensorrt.py +70 -0
  51. pathoinfer/runtime/local/torch.py +57 -0
  52. pathoinfer/runtime/local/vllm_offline.py +56 -0
  53. pathoinfer/runtime/remote/README.md +124 -0
  54. pathoinfer/runtime/remote/__init__.py +1 -0
  55. pathoinfer/runtime/remote/triton.py +77 -0
  56. pathoinfer/runtime/remote/vllm.py +137 -0
  57. pathoinfer/runtime/vlm.py +138 -0
  58. pathoinfer/serving/README.md +124 -0
  59. pathoinfer/serving/__init__.py +2 -0
  60. pathoinfer/serving/api.py +359 -0
  61. pathoinfer/serving/triton_repo.py +146 -0
  62. pathoinfer/serving/vllm.py +101 -0
  63. pathoinfer/stitch/README.md +209 -0
  64. pathoinfer/stitch/__init__.py +1 -0
  65. pathoinfer/stitch/base.py +133 -0
  66. pathoinfer/stitch/detection.py +241 -0
  67. pathoinfer/stitch/heatmap.py +211 -0
  68. pathoinfer/stitch/instance.py +232 -0
  69. pathoinfer/stitch/segmentation.py +247 -0
  70. pathoinfer/tiling/README.md +143 -0
  71. pathoinfer/tiling/__init__.py +4 -0
  72. pathoinfer/tiling/dataset.py +82 -0
  73. pathoinfer/tiling/grid.py +232 -0
  74. pathoinfer/tiling/slide_id.py +18 -0
  75. pathoinfer/tiling/synthetic.py +36 -0
  76. pathoinfer-0.2.0.dist-info/METADATA +369 -0
  77. pathoinfer-0.2.0.dist-info/RECORD +80 -0
  78. pathoinfer-0.2.0.dist-info/WHEEL +4 -0
  79. pathoinfer-0.2.0.dist-info/entry_points.txt +2 -0
  80. pathoinfer-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,233 @@
1
+ """Parity of a quantised VLM against its bf16 reference, through two vLLM servers.
2
+
3
+ Both models answer the same fixed eval set (``VqaDataConfig``: image, question, answer,
4
+ optional box) greedily. Metrics, as in PathVQA:
5
+
6
+ - accuracy: normalised exact match with ``answer`` (boxes in ``[...]`` dropped, lower
7
+ case, punctuation and the articles a/an/the removed, spaces collapsed), so
8
+ "Yes. [10, 20, 30, 40]" matches "yes";
9
+ - for grounding models (``output.grounding``) and rows with a ``box``: mean IoU of the
10
+ first box in each answer with ``box``, converted from the card's box units.
11
+
12
+ The candidate passes when its accuracy is at most ``accuracy_drop_max`` below the
13
+ reference's and its mean IoU at most ``iou_drop_max`` below. A pass writes the candidate
14
+ as a new folder with ``provenance.parity`` and may register it in MLflow under an alias;
15
+ a fail lists the questions the reference answered right and the candidate wrong, and
16
+ writes nothing.
17
+ """
18
+
19
+ import json
20
+ import os
21
+ import re
22
+ import shutil
23
+ import string
24
+ from collections.abc import Callable
25
+ from concurrent.futures import ThreadPoolExecutor
26
+ from dataclasses import dataclass, field
27
+ from datetime import UTC, datetime
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ from loguru import logger
32
+
33
+ from pathoinfer._logging import log_call
34
+ from pathoinfer.config import VlmParityConfig
35
+ from pathoinfer.convert.common import CARD_FILE
36
+ from pathoinfer.convert.parity import register_model
37
+ from pathoinfer.convert.vlm import load_pairs, read_rgb
38
+ from pathoinfer.registry.loader import load_vlm
39
+ from pathoinfer.registry.model_card import Parity, VqaCard, VqaOutput
40
+ from pathoinfer.runtime.vlm import Crop, parse_boxes
41
+
42
+ Ask = Callable[[str, str], str] # (image path, question) -> answer
43
+ _ARTICLES = re.compile(r"\b(a|an|the)\b")
44
+ _BRACKETS = re.compile(r"\[([^\[\]]*)\]")
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class VlmParityReport:
49
+ passed: bool
50
+ metrics: dict[str, float]
51
+ tolerances: dict[str, float]
52
+ failures: list[str]
53
+ eval_hash: str
54
+ samples: int
55
+ regressions: list[dict[str, str]] = field(default_factory=list)
56
+
57
+ def summary(self) -> str:
58
+ lines = [f"vlm parity {'PASS' if self.passed else 'FAIL'} on {self.samples} questions"]
59
+ lines += [f" {k} {v:.4f}" for k, v in self.metrics.items()]
60
+ lines += [f" failed: {f}" for f in self.failures]
61
+ lines += [
62
+ f" regressed: {r['question']!r}: reference {r['reference']!r}, "
63
+ f"candidate {r['candidate']!r}, truth {r['answer']!r}"
64
+ for r in self.regressions
65
+ ]
66
+ return "\n".join(lines)
67
+
68
+
69
+ def normalise(answer: str) -> str:
70
+ """The answer text for exact match: boxes (``[...]``) dropped, lower case, no
71
+ punctuation or articles, single spaces."""
72
+ text = _BRACKETS.sub(" ", str(answer)).lower()
73
+ text = text.translate(str.maketrans("", "", string.punctuation))
74
+ return " ".join(_ARTICLES.sub(" ", text).split())
75
+
76
+
77
+ def parse_box(answer: str, output: VqaOutput, size: tuple[int, int]) -> list[float] | None:
78
+ """The first box in ``answer`` as ``xyxy`` pixels of the image of ``size`` (width,
79
+ height), read as ``runtime.vlm.parse_boxes`` does."""
80
+ grounding = parse_boxes(answer, output, Crop(0, 0, size[0], size[1], size))
81
+ return [float(v) for v in grounding.boxes[0]] if len(grounding) else None
82
+
83
+
84
+ def iou(a: list[float] | None, b: list[float]) -> float:
85
+ if a is None:
86
+ return 0.0
87
+ w = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
88
+ h = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
89
+ union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - w * h
90
+ return w * h / union if union > 0 else 0.0
91
+
92
+
93
+ def score(
94
+ card: VqaCard, rows: list[dict[str, Any]], answers: list[str]
95
+ ) -> tuple[float, float | None]:
96
+ """Accuracy over ``rows`` and, for grounding models, mean IoU over rows with a box."""
97
+ correct = [
98
+ normalise(a) == normalise(str(r["answer"])) for r, a in zip(rows, answers, strict=True)
99
+ ]
100
+ boxed = [(r, a) for r, a in zip(rows, answers, strict=True) if r.get("box")]
101
+ if not (card.output.grounding and boxed):
102
+ return sum(correct) / len(correct), None
103
+ ious = []
104
+ for row, answer in boxed:
105
+ height, width = read_rgb(row["image"]).shape[:2]
106
+ box = parse_box(answer, card.output, (width, height))
107
+ ious.append(iou(box, [float(v) for v in row["box"]]))
108
+ return sum(correct) / len(correct), sum(ious) / len(ious)
109
+
110
+
111
+ def check(
112
+ reference: str | Path,
113
+ candidate: str | Path,
114
+ cfg: VlmParityConfig,
115
+ ask_reference: Ask,
116
+ ask_candidate: Ask,
117
+ ) -> VlmParityReport:
118
+ """Ask both models every eval question and judge the candidate."""
119
+ ref_card, _ = load_vlm(reference)
120
+ cand_card, _ = load_vlm(candidate)
121
+ if (ref_card.architecture, ref_card.output) != (cand_card.architecture, cand_card.output):
122
+ raise ValueError("reference and candidate differ in architecture or output")
123
+ rows, eval_hash = load_pairs(cfg.eval)
124
+ if any(r.get("answer") is None for r in rows):
125
+ raise ValueError(f"{cfg.eval.path}: every eval row needs an answer")
126
+ ref_answers = _answers(ask_reference, rows, cfg.concurrency)
127
+ cand_answers = _answers(ask_candidate, rows, cfg.concurrency)
128
+ ref_acc, ref_iou = score(ref_card, rows, ref_answers)
129
+ cand_acc, cand_iou = score(cand_card, rows, cand_answers)
130
+ metrics = {
131
+ "accuracy_reference": ref_acc,
132
+ "accuracy": cand_acc,
133
+ "accuracy_drop": ref_acc - cand_acc,
134
+ }
135
+ tolerances = {"accuracy_drop": cfg.tolerances.accuracy_drop_max}
136
+ if ref_iou is not None and cand_iou is not None:
137
+ metrics |= {"iou_reference": ref_iou, "iou": cand_iou, "iou_drop": ref_iou - cand_iou}
138
+ tolerances["iou_drop"] = cfg.tolerances.iou_drop_max
139
+ failures = [
140
+ f"{name} {metrics[name]:.4f} > {bound:g}"
141
+ for name, bound in tolerances.items()
142
+ if metrics[name] > bound
143
+ ]
144
+ regressions = [
145
+ {"question": r["question"], "answer": str(r["answer"]), "reference": a, "candidate": b}
146
+ for r, a, b in zip(rows, ref_answers, cand_answers, strict=True)
147
+ if normalise(a) == normalise(str(r["answer"])) != normalise(b)
148
+ ][:5]
149
+ report = VlmParityReport(
150
+ not failures,
151
+ metrics,
152
+ tolerances,
153
+ failures,
154
+ eval_hash,
155
+ len(rows),
156
+ regressions if failures else [],
157
+ )
158
+ logger.info("{}", report.summary())
159
+ return report
160
+
161
+
162
+ @log_call
163
+ def gate(
164
+ reference: str | Path,
165
+ candidate: str | Path,
166
+ cfg: VlmParityConfig,
167
+ out: Path,
168
+ reference_url: str,
169
+ candidate_url: str,
170
+ register: tuple[str, str] | None = None,
171
+ tracking_uri: str | None = None,
172
+ ) -> VlmParityReport:
173
+ """``check`` against the two servers; on a pass write ``out`` with the parity in its
174
+ card (and register it), on a fail write nothing."""
175
+ from pathoinfer.runtime.remote.vllm import VllmClient
176
+
177
+ clients = [
178
+ VllmClient(url, timeout_s=cfg.timeout_s, concurrency=cfg.concurrency)
179
+ for url in (reference_url, candidate_url)
180
+ ]
181
+ try:
182
+ report = check(
183
+ reference,
184
+ candidate,
185
+ cfg,
186
+ lambda image, question: clients[0].ask(image, question, cfg.max_tokens),
187
+ lambda image, question: clients[1].ask(image, question, cfg.max_tokens),
188
+ )
189
+ finally:
190
+ for client in clients:
191
+ client.close()
192
+ if report.passed:
193
+ write_passed(reference, candidate, report, out)
194
+ if register is not None:
195
+ register_model(out, *register, tracking_uri=tracking_uri)
196
+ return report
197
+
198
+
199
+ def write_passed(
200
+ reference: str | Path, candidate: str | Path, report: VlmParityReport, out: Path
201
+ ) -> VqaCard:
202
+ """Copy the candidate folder to the new folder ``out`` with ``provenance.parity``."""
203
+ if out.exists():
204
+ raise FileExistsError(f"{out} exists; choose a new folder")
205
+ ref_card, _ = load_vlm(reference)
206
+ cand_card, cand_dir = load_vlm(candidate)
207
+ data = cand_card.model_dump(mode="json")
208
+ data["provenance"]["parity"] = Parity(
209
+ reference=f"{ref_card.name}@{ref_card.version}",
210
+ tile_set_hash=report.eval_hash,
211
+ metrics=report.metrics,
212
+ tolerances=report.tolerances,
213
+ checked_at=datetime.now(UTC).isoformat(timespec="seconds"),
214
+ ).model_dump(mode="json")
215
+ card = VqaCard.model_validate(data)
216
+ partial = out.with_name(out.name + ".partial")
217
+ shutil.rmtree(partial, ignore_errors=True)
218
+ shutil.copytree(cand_dir, partial)
219
+ (partial / CARD_FILE).write_text(card.model_dump_json(indent=2) + "\n")
220
+ os.replace(partial, out)
221
+ logger.info("vlm parity passed: wrote {}", out)
222
+ return card
223
+
224
+
225
+ def _answers(ask: Ask, rows: list[dict[str, Any]], concurrency: int) -> list[str]:
226
+ with ThreadPoolExecutor(concurrency) as pool:
227
+ return list(pool.map(lambda r: ask(r["image"], r["question"]), rows))
228
+
229
+
230
+ def report_json(report: VlmParityReport) -> str:
231
+ from dataclasses import asdict
232
+
233
+ return json.dumps(asdict(report), indent=2) + "\n"
@@ -0,0 +1,134 @@
1
+ # pathoinfer - engine
2
+
3
+ Processes slides: for each slide of a run config, builds the tissue grid, reads tiles in
4
+ worker processes, runs the model, stitches on a separate thread and writes the outputs.
5
+ The engine knows nothing about how the model executes (that is `runtime/`) or how
6
+ outputs are encoded (that is `io/`).
7
+
8
+ ## Usage
9
+
10
+ From the command line:
11
+
12
+ ```bash
13
+ pathoinfer validate examples/segmentation.yaml # config, model and slides; runs nothing
14
+ pathoinfer run examples/segmentation.yaml # exit 1 if any slide failed
15
+ ```
16
+
17
+ From Python:
18
+
19
+ ```python
20
+ from pathlib import Path
21
+
22
+ from pathoinfer.config import load_config
23
+ from pathoinfer.engine.pipeline import load, run_batch, run_slide
24
+
25
+ cfg = load_config("examples/segmentation.yaml")
26
+ results = run_batch(cfg) # every slide of cfg.slides
27
+
28
+ model = load(cfg) # or one slide, reusing a loaded model
29
+ result = run_slide(cfg, Path("slides/slide_name-01.svs"), model)
30
+ print(result.status, result.tiles, result.objects, result.wall_s)
31
+ ```
32
+
33
+ `examples/*.yaml` documents every config field; `docs/outputs.md` every output.
34
+
35
+ ## Contract
36
+
37
+ | | |
38
+ |---|---|
39
+ | `load(cfg)` | Loads the model (`registry.loader.load_model`), checks its task matches the config's, builds and warms up the runtime. Returns a `Model` with the settings hash. Raises on a task mismatch. |
40
+ | `run_slide(cfg, path, model=None)` | Runs one slide and writes its outputs. Raises on any failure; nothing is marked finished. |
41
+ | `run_batch(cfg)` | Runs every slide, loading the model once. A failing slide is logged and recorded; the batch carries on. Returns one `RunResult` per slide. Raises only on problems with the whole run: no slides, two slides with the same file stem, or a model that does not load. |
42
+ | `RunResult` | `slide`, `status` (`done`, `skipped` or `failed`), `slide_id`, `tiles`, `objects`, `wall_s`, `outputs`, `timings` (seconds per stage), `peak_memory` (MB), `error`. |
43
+
44
+ ## One slide
45
+
46
+ ```text
47
+ open_slide -> build_grid --> DataLoader readers --> runtime.predict --> StitchThread --> writers
48
+ (patchology) (tissue, (num_workers (this thread) (own thread, (GeoJSON,
49
+ cores) processes) queue of 8) Parquet, TIFF)
50
+ ```
51
+
52
+ 1. **Grid.** The slide opens through patchology; `build_grid` keeps tissue tiles at the
53
+ card's tile size and mpp, with the config's overlap (default: the card's
54
+ `recommended_overlap`). ICC conversion is on when both the config and the card ask for
55
+ it. A slide without a resolution raises `SlideResolutionError`.
56
+ 2. **Stream** (`scheduler.stream`). Three stages, each bounded so memory stays flat
57
+ whatever their relative speed: reader processes fill the DataLoader prefetch queue
58
+ (`num_workers * prefetch_factor` batches), the runtime runs on the calling thread, and
59
+ the stitcher runs behind a queue of `STITCH_QUEUE` batches. On any error the stitcher
60
+ thread and the reader processes are stopped before the error is raised.
61
+ 3. **Write.** `RunInfo` and `ObjectTable` (`io/objects.py`) feed the writers the config
62
+ enables. Outputs go to `outputs.dir`, named after the slide's file stem.
63
+ 4. **Mark.** `<stem>.done.json` is written last: settings hash, slide id and the files
64
+ written.
65
+
66
+ ## Resume
67
+
68
+ With `resume: true`, `run_batch` skips a slide when its marker exists, its
69
+ `settings_hash` matches and every file it lists still exists. The hash
70
+ (`RunConfig.settings_hash`) covers the model card and every setting that changes
71
+ outputs: tiling, stitching, outputs, class colours, autocast. It leaves out the slide
72
+ list, the loader, the device and the batch size. Change a stitch setting or swap the
73
+ model version behind an alias and the slide runs again; add slides or more workers and
74
+ finished ones stay skipped. An interrupted slide has no marker, so it runs again.
75
+
76
+ ## Files per run
77
+
78
+ Besides each slide's outputs, `run_batch` writes into `outputs.dir`:
79
+
80
+ | File | Contents |
81
+ |---|---|
82
+ | `batch-<UTC time>.parquet` | One row per slide: `slide`, `status`, `slide_id`, `tiles`, `objects`, `wall_s`, `<stage>_s` timings, `peak_rss_mb`, `error`, `settings_hash`. |
83
+ | `run-<UTC time>.log` | Every pathoinfer and patchology log record of the run, DEBUG and up. |
84
+
85
+ ## Logging
86
+
87
+ One INFO line per slide, as `key=value` pairs:
88
+
89
+ ```text
90
+ slide=slide_name-01.svs slide_id=684c… tiles=3044 tiles_per_s=984 objects=7 wall_s=3.8
91
+ grid_s=0.70 start_s=2.88 read_s=0.08 infer_s=0.06 stitch_wait_s=0.07 stitch_finalize_s=0.01
92
+ write_s=0.02 peak_rss_mb=1299
93
+ ```
94
+
95
+ | Stage | Time spent |
96
+ |---|---|
97
+ | `grid` | Opening the slide, tissue detection, building the grid |
98
+ | `start` | Starting the reader processes |
99
+ | `read` | Waiting for the next batch of tiles |
100
+ | `infer` | `runtime.predict` |
101
+ | `stitch_wait` | Waiting for room in the stitcher's queue (the stitcher is the bottleneck) |
102
+ | `stitch_finalize` | Finishing the stitch after the last batch |
103
+ | `write` | Writing the outputs |
104
+
105
+ `tiles_per_s` is tiles over `start + read + infer + stitch_wait`. A large `read` means
106
+ more workers would help; a large `stitch_wait` points at the stitcher; `infer` near the
107
+ total means the model is the limit. Run start and end, skipped and failed slides are
108
+ logged too; `-v` adds DEBUG detail.
109
+
110
+ ## Performance notes
111
+
112
+ - `scripts/perf_report.py SLIDE CONFIG` times read, inference, stitching and writing one
113
+ at a time on up to `--max-tiles` tiles and names the slowest. The per-slide log line
114
+ shows waiting time in an overlapped run; the report shows each stage's capacity.
115
+ - Each slide gets its own DataLoader, so reader start-up (`start`, about 0.7 s per worker
116
+ measured on one machine) is paid per slide. For a fast model on many small slides it
117
+ can dominate; reusing readers across slides is the fix if that matters.
118
+ - Peak memory is the process's resident set (`peak_rss_mb`) and, once CUDA is in use,
119
+ peak allocated GPU memory (`peak_cuda_mb`).
120
+
121
+ ## Testing
122
+
123
+ `tests/engine/test_pipeline.py` runs a synthetic pyramidal slide end to end with the
124
+ fixture models at 4 mpp (about 100 tiles):
125
+
126
+ - segmentation writes every output, and the GeoJSON, Parquet and TIFF read back valid;
127
+ - detection with `tiny_det` (one box per tile centre) reports exactly one object per tile;
128
+ - resume skips a finished slide, and runs it again after a setting changes, an output is
129
+ deleted, or resume is off;
130
+ - a slide without a resolution and a missing slide fail, are recorded in the batch
131
+ summary, and the next slide still runs;
132
+ - an error mid-slide stops every reader process and writes no marker;
133
+ - 0 and 2 reader processes give the same result;
134
+ - the CLI validates, describes and runs a config, and reports bad configs.
@@ -0,0 +1,3 @@
1
+ """Engine: "process this slide". The pathoinfer counterpart of pathotrain.engine; knows nothing
2
+ about how the model executes.
3
+ """