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,437 @@
1
+ """Process slides: tissue and grid -> DataLoader -> runtime -> stitcher thread -> writers.
2
+
3
+ ``run_batch`` loads the model once and runs every slide of a config. A slide that fails
4
+ is logged and recorded; the batch carries on. Each finished slide gets a
5
+ ``<stem>.done.json`` marker naming its outputs and the run's settings hash, so a resumed
6
+ run skips it while the settings and outputs are unchanged.
7
+ """
8
+
9
+ import json
10
+ import re
11
+ import time
12
+ from collections import Counter
13
+ from dataclasses import dataclass, field
14
+ from datetime import UTC, datetime
15
+ from pathlib import Path
16
+ from typing import Literal
17
+
18
+ import polars as pl
19
+ from loguru import logger
20
+
21
+ from patchology import open_slide
22
+ from pathoinfer._logging import add_file_sink, log_call
23
+ from pathoinfer.config import ClassRemap, RunConfig
24
+ from pathoinfer.engine.scheduler import (
25
+ STITCH_QUEUE,
26
+ GpuSampler,
27
+ Progress,
28
+ Timings,
29
+ cpu_seconds,
30
+ peak_memory_mb,
31
+ stream,
32
+ )
33
+ from pathoinfer.io.objects import ObjectTable, RunInfo
34
+ from pathoinfer.io.writers.geojson import write_geojson
35
+ from pathoinfer.io.writers.overlay import write_overlay
36
+ from pathoinfer.io.writers.parquet import write_parquet, write_summary
37
+ from pathoinfer.io.writers.tiff import write_tiff
38
+ from pathoinfer.registry.loader import load_model
39
+ from pathoinfer.registry.model_card import (
40
+ ClassificationCard,
41
+ DetectionCard,
42
+ InstanceCard,
43
+ ModelCard,
44
+ SegmentationCard,
45
+ )
46
+ from pathoinfer.runtime.base import Runtime, resolve_device
47
+ from pathoinfer.runtime.factory import make_runtime
48
+ from pathoinfer.stitch.base import Stitcher, StitchThread
49
+ from pathoinfer.stitch.detection import DetectionStitcher
50
+ from pathoinfer.stitch.heatmap import HeatmapStitcher
51
+ from pathoinfer.stitch.instance import InstanceStitcher
52
+ from pathoinfer.stitch.segmentation import SegmentationStitcher
53
+ from pathoinfer.tiling.dataset import make_loader
54
+ from pathoinfer.tiling.grid import SlideGrid, build_grid
55
+
56
+ Status = Literal["done", "skipped", "failed"]
57
+ # The stages tiles flow through; tiles/s is tiles over their total time.
58
+ STREAM_STAGES = ("start", "read", "infer", "stitch_wait")
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class Model:
63
+ """A loaded model, shared by every slide of a run."""
64
+
65
+ card: ModelCard
66
+ model_dir: Path
67
+ runtime: Runtime
68
+ settings_hash: str
69
+ precision: str # what the model runs in: the card's, or the autocast dtype
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class RunResult:
74
+ slide: Path
75
+ status: Status
76
+ slide_id: str | None = None
77
+ tiles: int = 0
78
+ objects: int = 0
79
+ wall_s: float = 0.0
80
+ outputs: tuple[Path, ...] = ()
81
+ timings: dict[str, float] = field(default_factory=dict)
82
+ peak_memory: dict[str, float] = field(default_factory=dict)
83
+ error: str | None = None
84
+
85
+
86
+ @log_call
87
+ def load(cfg: RunConfig) -> Model:
88
+ """Load and warm up ``cfg``'s model. Raises ValueError if its task is not the
89
+ config's."""
90
+ card, model_dir = load_model(cfg.model)
91
+ if card.task != cfg.task:
92
+ raise ValueError(f"config task is {cfg.task}, but {cfg.model} is a {card.task} model")
93
+ logger.debug("model card: {}", card.model_dump_json())
94
+ runtime = make_runtime(card, model_dir, cfg.runtime)
95
+ runtime.warmup()
96
+ autocast = card.framework == "torch" and not cfg.runtime.triton_url and cfg.runtime.autocast
97
+ precision = autocast or card.precision
98
+ return Model(card, model_dir, runtime, cfg.settings_hash(card.model_dump_json()), precision)
99
+
100
+
101
+ def output_paths(cfg: RunConfig, slide: Path) -> dict[str, Path]:
102
+ """The files a slide's run writes, by kind (GeoJSON split per class and
103
+ classification heatmaps, one per class, add more)."""
104
+ out, stem = cfg.outputs, slide.stem
105
+ paths = {}
106
+ if out.geojson:
107
+ paths["geojson"] = out.dir / f"{stem}.geojson{'.gz' if out.gzip else ''}"
108
+ if out.parquet:
109
+ paths["objects"] = out.dir / f"{stem}.objects.parquet"
110
+ paths["summary"] = out.dir / f"{stem}.summary.{out.summary_format}"
111
+ if out.tiff and cfg.task == "segmentation":
112
+ paths["labels"] = out.dir / f"{stem}.labels.tiff"
113
+ if out.overlay and cfg.task == "segmentation":
114
+ paths["overlay"] = out.dir / f"{stem}.overlay.png"
115
+ return paths
116
+
117
+
118
+ def finished_summary(
119
+ name: str,
120
+ wall: float,
121
+ tiles: int,
122
+ tiles_per_s: float,
123
+ objects: int,
124
+ timings: Timings,
125
+ cpu: float,
126
+ peak: dict[str, float],
127
+ ) -> str:
128
+ """A slide's run for people: time per stage (share of the wall time), the main
129
+ process's CPU (average cores in use) and peak memory. Reader processes are not
130
+ measured."""
131
+ stages = sorted(timings.seconds.items(), key=lambda kv: -kv[1])
132
+ time_line = " | ".join(
133
+ f"{k.replace('_', ' ')} {v:.1f} s ({100 * v / max(wall, 1e-9):.0f}%)" for k, v in stages
134
+ )
135
+ cores = cpu / max(wall, 1e-9)
136
+
137
+ def gb(mb: float) -> str:
138
+ return f"{mb / 1024:.1f} GB"
139
+
140
+ memory = f"RAM peak {gb(peak['rss_mb'])} (main process)"
141
+ if "cuda_mb" in peak:
142
+ memory += f"; GPU {gb(peak['cuda_mb'])} peak by torch"
143
+ gpu = ""
144
+ if "gpu_util_mean" in peak:
145
+ gpu = (
146
+ f"\n GPU busy {peak['gpu_util_mean']:.0f}% on average "
147
+ f"(max {peak['gpu_util_max']:.0f}%) during inference; "
148
+ f"{gb(peak['gpu_used_mb'])} peak in use on the device"
149
+ )
150
+ return (
151
+ f"finished {name} in {wall:.1f} s: {tiles} tiles at {tiles_per_s:.0f} tiles/s, "
152
+ f"{objects} objects\n"
153
+ f" time {time_line}\n"
154
+ f" CPU {cores:.1f} cores on average ({cpu:.0f} s; readers not counted)\n"
155
+ f" memory {memory}{gpu}"
156
+ )
157
+
158
+
159
+ def marker_path(cfg: RunConfig, slide: Path) -> Path:
160
+ return cfg.outputs.dir / f"{slide.stem}.done.json"
161
+
162
+
163
+ def is_done(cfg: RunConfig, slide: Path, settings_hash: str) -> bool:
164
+ """True if a run with the same settings finished ``slide`` and its outputs exist."""
165
+ try:
166
+ marker = json.loads(marker_path(cfg, slide).read_text())
167
+ except (FileNotFoundError, json.JSONDecodeError):
168
+ return False
169
+ return marker.get("settings_hash") == settings_hash and all(
170
+ Path(p).is_file() for p in marker.get("outputs", [])
171
+ )
172
+
173
+
174
+ @log_call
175
+ def run_slide(
176
+ cfg: RunConfig, path: Path, model: Model | None = None, on_progress: Progress | None = None
177
+ ) -> RunResult:
178
+ """Run one slide end to end and write its outputs; raises on failure. ``on_progress``
179
+ is called after each batch with (tiles done, tiles in the slide)."""
180
+ model = model or load(cfg)
181
+ card = model.card
182
+ start = time.perf_counter()
183
+ cpu_start = cpu_seconds()
184
+ timings = Timings()
185
+ with timings.stage("grid"), open_slide(path, cfg.tiling.backend) as slide:
186
+ overlap = cfg.tiling.overlap
187
+ overlap = card.recommended_overlap if overlap is None else overlap
188
+ grid = build_grid(
189
+ slide,
190
+ card.input.tile_size,
191
+ card.input.mpp,
192
+ round(overlap * card.input.tile_size),
193
+ min_tissue_fraction=cfg.tiling.min_tissue_fraction,
194
+ tissue=cfg.tiling.tissue,
195
+ artifacts=cfg.tiling.artifacts,
196
+ icc=cfg.tiling.icc and card.input.icc,
197
+ )
198
+ logger.debug(
199
+ "{}: {} tiles in a {} x {} grid", path.name, len(grid.tiles), grid.n_rows, grid.n_cols
200
+ )
201
+ output_mpp = segmentation_output_mpp(cfg, grid) if cfg.task == "segmentation" else None
202
+ loader = make_loader(
203
+ grid,
204
+ cfg.runtime.batch_size,
205
+ cfg.loader.num_workers,
206
+ prefetch_factor=cfg.loader.prefetch_factor,
207
+ persistent_workers=False,
208
+ )
209
+ device = resolve_device(cfg.runtime.device)
210
+ on_gpu = device.type == "cuda" and cfg.runtime.triton_url is None # Triton's GPU is remote
211
+ gpu = GpuSampler(device.index or 0)
212
+ try:
213
+ thread = StitchThread(make_stitcher(cfg, card, grid, output_mpp), STITCH_QUEUE)
214
+ if on_gpu:
215
+ with gpu:
216
+ result, tiles = stream(loader, model.runtime, thread, timings, on_progress)
217
+ else:
218
+ result, tiles = stream(loader, model.runtime, thread, timings, on_progress)
219
+ finally:
220
+ loader.dataset.close() # type: ignore[attr-defined] # TileDataset; open with 0 workers
221
+
222
+ remap = (
223
+ cfg.segmentation.class_remap(card)
224
+ if isinstance(card, SegmentationCard)
225
+ else ClassRemap({}, {})
226
+ )
227
+ run = RunInfo.create(
228
+ card,
229
+ grid,
230
+ cfg.model,
231
+ output_mpp,
232
+ cfg.class_colors,
233
+ exclude=remap.targets,
234
+ rename=remap.names,
235
+ precision=model.precision,
236
+ )
237
+ objects = ObjectTable.from_result(result, run, cfg.detection.geometry)
238
+ paths = output_paths(cfg, path)
239
+ cfg.outputs.dir.mkdir(parents=True, exist_ok=True)
240
+ written: list[Path] = []
241
+ with timings.stage("write"):
242
+ if "geojson" in paths:
243
+ written += write_geojson(paths["geojson"], objects, run, cfg.outputs.per_class)
244
+ if "objects" in paths:
245
+ written.append(write_parquet(paths["objects"], objects, run, cfg.outputs.geoparquet))
246
+ written.append(write_summary(paths["summary"], objects, run))
247
+ if "labels" in paths:
248
+ written.append(write_tiff(paths["labels"], result.rasters["labels"], run))
249
+ if cfg.outputs.tiff and cfg.task == "classification":
250
+ for name, raster in result.rasters.items():
251
+ safe = re.sub(r"[^\w.-]+", "_", name)
252
+ tiff = cfg.outputs.dir / f"{path.stem}.{safe}.tiff"
253
+ written.append(write_tiff(tiff, raster, run))
254
+ if "overlay" in paths:
255
+ with open_slide(path, cfg.tiling.backend) as slide:
256
+ written.append(
257
+ write_overlay(paths["overlay"], slide, objects, run, cfg.outputs.overlay_mpp)
258
+ )
259
+ marker = {
260
+ "settings_hash": model.settings_hash,
261
+ "precision": model.precision,
262
+ "slide": str(path),
263
+ "slide_id": grid.slide_id,
264
+ "outputs": [str(p) for p in written],
265
+ "finished_at": datetime.now(UTC).isoformat(timespec="seconds"),
266
+ }
267
+ marker_path(cfg, path).write_text(json.dumps(marker, indent=2) + "\n")
268
+
269
+ wall = time.perf_counter() - start
270
+ peak = peak_memory_mb() | gpu.result
271
+ cpu = cpu_seconds() - cpu_start
272
+ tiles_per_s = tiles / max(sum(timings.seconds.get(k, 0.0) for k in STREAM_STAGES), 1e-9)
273
+ stages = " ".join(f"{k}_s={v:.2f}" for k, v in timings.seconds.items())
274
+ memory = " ".join(f"peak_{k}={v:.0f}" for k, v in peak.items())
275
+ logger.info(
276
+ "slide={} slide_id={} tiles={} tiles_per_s={:.0f} objects={} wall_s={:.1f} {} "
277
+ "cpu_s={:.0f} {}",
278
+ path.name,
279
+ grid.slide_id,
280
+ tiles,
281
+ tiles_per_s,
282
+ len(objects),
283
+ wall,
284
+ stages,
285
+ cpu,
286
+ memory,
287
+ )
288
+ logger.info(
289
+ "{}",
290
+ finished_summary(path.name, wall, tiles, tiles_per_s, len(objects), timings, cpu, peak),
291
+ )
292
+ return RunResult(
293
+ path,
294
+ "done",
295
+ grid.slide_id,
296
+ tiles,
297
+ len(objects),
298
+ wall,
299
+ tuple(written),
300
+ dict(timings.seconds),
301
+ peak,
302
+ )
303
+
304
+
305
+ @log_call
306
+ def run_batch(cfg: RunConfig) -> list[RunResult]:
307
+ """Run every slide of ``cfg``, skipping finished ones when ``cfg.resume``. Writes a
308
+ ``batch-<time>.parquet`` summary and a ``run-<time>.log`` into the output folder.
309
+
310
+ Raises:
311
+ ValueError: no slides, two slides with the same file stem, or a task mismatch.
312
+ """
313
+ slides = cfg.slide_paths()
314
+ if not slides:
315
+ raise ValueError(f"no slides match {cfg.slides!r}")
316
+ stems = Counter(p.stem for p in slides)
317
+ clashes = sorted(s for s, n in stems.items() if n > 1)
318
+ if clashes:
319
+ raise ValueError(f"slides share output names {clashes}; give them distinct file names")
320
+ cfg.outputs.dir.mkdir(parents=True, exist_ok=True)
321
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
322
+ sink = add_file_sink(cfg.outputs.dir / f"run-{stamp}.log")
323
+ start = time.perf_counter()
324
+ try:
325
+ model = load(cfg)
326
+ logger.info(
327
+ "run start: {} slides, model {} {} ({}), precision {}, settings {}",
328
+ len(slides),
329
+ model.card.name,
330
+ model.card.version,
331
+ cfg.model,
332
+ model.precision,
333
+ model.settings_hash,
334
+ )
335
+ results = [_run_one(cfg, path, model) for path in slides]
336
+ summary = cfg.outputs.dir / f"batch-{stamp}.parquet"
337
+ _batch_frame(results, model.settings_hash, model.precision).write_parquet(summary)
338
+ counts = Counter(r.status for r in results)
339
+ logger.info(
340
+ "run end: {} done, {} skipped, {} failed in {:.1f} s; summary {}",
341
+ counts["done"],
342
+ counts["skipped"],
343
+ counts["failed"],
344
+ time.perf_counter() - start,
345
+ summary,
346
+ )
347
+ return results
348
+ finally:
349
+ logger.remove(sink)
350
+
351
+
352
+ def _run_one(cfg: RunConfig, path: Path, model: Model) -> RunResult:
353
+ if cfg.resume and is_done(cfg, path, model.settings_hash):
354
+ logger.info("slide={} skipped: finished with the same settings", path.name)
355
+ return RunResult(path, "skipped")
356
+ try:
357
+ return run_slide(cfg, path, model)
358
+ except Exception as e: # noqa: BLE001 recorded in the batch summary, the run carries on
359
+ logger.exception("slide={} failed", path.name)
360
+ return RunResult(path, "failed", error=f"{type(e).__name__}: {e}")
361
+
362
+
363
+ def _batch_frame(results: list[RunResult], settings_hash: str, precision: str) -> pl.DataFrame:
364
+ stages = sorted({k for r in results for k in r.timings})
365
+ rows = [
366
+ {
367
+ "slide": str(r.slide),
368
+ "status": r.status,
369
+ "slide_id": r.slide_id,
370
+ "tiles": r.tiles,
371
+ "objects": r.objects,
372
+ "wall_s": r.wall_s,
373
+ **{f"{k}_s": r.timings.get(k, 0.0) for k in stages},
374
+ "peak_rss_mb": r.peak_memory.get("rss_mb"),
375
+ "error": r.error,
376
+ "settings_hash": settings_hash,
377
+ "precision": precision,
378
+ }
379
+ for r in results
380
+ ]
381
+ return pl.DataFrame(rows, infer_schema_length=None)
382
+
383
+
384
+ def segmentation_output_mpp(cfg: RunConfig, grid: SlideGrid) -> float:
385
+ return cfg.segmentation.output_mpp or max(2.0, grid.mpp)
386
+
387
+
388
+ def make_stitcher(
389
+ cfg: RunConfig, card: ModelCard, grid: SlideGrid, output_mpp: float | None
390
+ ) -> Stitcher:
391
+ if isinstance(card, SegmentationCard):
392
+ assert output_mpp is not None
393
+ return SegmentationStitcher(
394
+ card,
395
+ grid,
396
+ output_mpp=output_mpp,
397
+ simplify_px=cfg.segmentation.simplify_px,
398
+ smooth=cfg.segmentation.smooth,
399
+ min_area_um2=cfg.segmentation.min_area_um2,
400
+ fill_holes_um2=cfg.segmentation.fill_holes_um2,
401
+ connectivity=cfg.segmentation.connectivity,
402
+ keep_labels=cfg.outputs.tiff,
403
+ class_targets=cfg.segmentation.class_remap(card).targets,
404
+ )
405
+ if isinstance(card, InstanceCard):
406
+ opts = cfg.instance
407
+ return InstanceStitcher(
408
+ card,
409
+ grid,
410
+ threshold=opts.threshold,
411
+ marker_threshold=opts.marker_threshold,
412
+ min_size_px=opts.min_size_px,
413
+ simplify_px=opts.simplify_px,
414
+ smooth=opts.smooth,
415
+ workers=opts.workers,
416
+ )
417
+ if isinstance(card, ClassificationCard):
418
+ heat = cfg.classification
419
+ return HeatmapStitcher(
420
+ card,
421
+ grid,
422
+ sigma_tiles=heat.sigma_tiles,
423
+ thresholds=heat.thresholds,
424
+ simplify_px=heat.simplify_px,
425
+ smooth=heat.smooth,
426
+ min_area_um2=heat.min_area_um2,
427
+ fill_holes_um2=heat.fill_holes_um2,
428
+ connectivity=heat.connectivity,
429
+ )
430
+ if not isinstance(card, DetectionCard):
431
+ raise NotImplementedError(f"no stitcher for {card.task} yet")
432
+ return DetectionStitcher(
433
+ card,
434
+ grid,
435
+ score_threshold=cfg.detection.score_threshold,
436
+ nms_iou=cfg.detection.nms_iou,
437
+ )
@@ -0,0 +1,161 @@
1
+ """Move one slide's tiles from the readers through the runtime into the stitcher.
2
+
3
+ Three stages, each bounded so memory stays flat whatever their relative speed: reader
4
+ processes fill the DataLoader's prefetch queue (``num_workers * prefetch_factor``
5
+ batches), the runtime runs on this thread, and the stitcher runs on its own thread behind
6
+ a queue of ``STITCH_QUEUE`` batches. ``stream`` times each stage and, on any error,
7
+ stops the reader processes and the stitcher thread before raising.
8
+ """
9
+
10
+ import os
11
+ import resource
12
+ import threading
13
+ import time
14
+ from collections.abc import Callable, Iterator
15
+ from contextlib import contextmanager
16
+ from dataclasses import dataclass, field
17
+ from typing import Self
18
+
19
+ import torch
20
+ from torch.utils.data import DataLoader
21
+
22
+ from pathoinfer.runtime.base import Runtime
23
+ from pathoinfer.stitch.base import StitchResult, StitchThread
24
+ from pathoinfer.tiling.dataset import Item
25
+
26
+ STITCH_QUEUE = 8
27
+ # Called after each batch with (tiles done, tiles in the slide).
28
+ Progress = Callable[[int, int], None]
29
+
30
+
31
+ @dataclass
32
+ class Timings:
33
+ """Seconds per stage. ``start`` is reader start-up, ``read`` time spent waiting for
34
+ tiles, ``stitch_wait`` time spent waiting for the stitcher's queue to have room."""
35
+
36
+ seconds: dict[str, float] = field(default_factory=dict)
37
+
38
+ @contextmanager
39
+ def stage(self, name: str) -> Iterator[None]:
40
+ start = time.perf_counter()
41
+ try:
42
+ yield
43
+ finally:
44
+ self.seconds[name] = self.seconds.get(name, 0.0) + time.perf_counter() - start
45
+
46
+
47
+ def peak_memory_mb() -> dict[str, float]:
48
+ """Peak resident memory of this process and, on CUDA, peak GPU memory allocated by
49
+ torch (TensorRT and ONNX Runtime allocate outside it; ``GpuSampler`` sees all). Reader
50
+ processes are not counted: they are the forkserver's children, not this process's."""
51
+ peaks = {"rss_mb": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024}
52
+ if torch.cuda.is_initialized(): # type: ignore[no-untyped-call] # never start CUDA here
53
+ peaks["cuda_mb"] = torch.cuda.max_memory_allocated() / 2**20
54
+ return peaks
55
+
56
+
57
+ class GpuSampler:
58
+ """Samples one GPU's utilisation and memory in use through NVML every ``interval_s``
59
+ on a thread, while the ``with`` block runs. ``result`` is empty when NVML is not
60
+ available (no NVIDIA driver), so CPU machines run unchanged.
61
+
62
+ ``result``: ``gpu_util_mean`` and ``gpu_util_max`` (% of time a kernel ran, NVML's
63
+ definition, not how full the GPU was) and ``gpu_used_mb`` (peak memory in use on the
64
+ device: every process's, TensorRT's and ONNX Runtime's included)."""
65
+
66
+ def __init__(self, cuda_index: int, interval_s: float = 0.5) -> None:
67
+ self.cuda_index, self.interval_s = cuda_index, interval_s
68
+ self.result: dict[str, float] = {}
69
+ self._stop = threading.Event()
70
+ self._util: list[int] = []
71
+ self._used = 0
72
+ self._thread: threading.Thread | None = None
73
+
74
+ def __enter__(self) -> Self:
75
+ import pynvml
76
+
77
+ try:
78
+ pynvml.nvmlInit()
79
+ handle = pynvml.nvmlDeviceGetHandleByIndex(_nvml_index(self.cuda_index))
80
+ except pynvml.NVMLError:
81
+ return self
82
+ self._thread = threading.Thread(target=self._sample, args=(handle,), daemon=True)
83
+ self._thread.start()
84
+ return self
85
+
86
+ def __exit__(self, *_: object) -> None:
87
+ if self._thread is None:
88
+ return
89
+ import pynvml
90
+
91
+ self._stop.set()
92
+ self._thread.join()
93
+ pynvml.nvmlShutdown()
94
+ if self._util:
95
+ self.result = {
96
+ "gpu_util_mean": sum(self._util) / len(self._util),
97
+ "gpu_util_max": float(max(self._util)),
98
+ "gpu_used_mb": self._used / 2**20,
99
+ }
100
+
101
+ def _sample(self, handle: object) -> None:
102
+ import pynvml
103
+
104
+ while True:
105
+ self._util.append(pynvml.nvmlDeviceGetUtilizationRates(handle).gpu)
106
+ self._used = max(self._used, pynvml.nvmlDeviceGetMemoryInfo(handle).used)
107
+ if self._stop.wait(self.interval_s):
108
+ return
109
+
110
+
111
+ def _nvml_index(cuda_index: int) -> int:
112
+ """NVML numbers GPUs as the system does; CUDA renumbers them after
113
+ ``CUDA_VISIBLE_DEVICES``. shortcut: assumes the default PCI ordering, use PCI bus ids
114
+ if machines set CUDA_DEVICE_ORDER otherwise."""
115
+ visible = os.environ.get("CUDA_VISIBLE_DEVICES", "").split(",")
116
+ if cuda_index < len(visible) and visible[cuda_index].strip().isdigit():
117
+ return int(visible[cuda_index])
118
+ return cuda_index
119
+
120
+
121
+ def cpu_seconds() -> float:
122
+ """CPU time (user + system) of this process so far, all its threads."""
123
+ own = resource.getrusage(resource.RUSAGE_SELF)
124
+ return own.ru_utime + own.ru_stime
125
+
126
+
127
+ def stream(
128
+ loader: DataLoader[Item],
129
+ runtime: Runtime,
130
+ thread: StitchThread,
131
+ timings: Timings,
132
+ on_progress: Progress | None = None,
133
+ ) -> tuple[StitchResult, int]:
134
+ """Run every batch of ``loader`` through ``runtime`` into ``thread``; returns the
135
+ stitched result and the number of tiles."""
136
+ with timings.stage("start"): # starts the reader processes
137
+ batches = iter(loader)
138
+ total = len(loader.dataset.grid.tiles) # type: ignore[attr-defined] # TileDataset
139
+ tiles = 0
140
+ try:
141
+ while True:
142
+ with timings.stage("read"):
143
+ batch = next(batches, None)
144
+ if batch is None:
145
+ break
146
+ images, specs = batch
147
+ with timings.stage("infer"):
148
+ outputs = runtime.predict(images)
149
+ with timings.stage("stitch_wait"):
150
+ thread.put(specs, outputs)
151
+ tiles += len(specs)
152
+ if on_progress is not None:
153
+ on_progress(tiles, total)
154
+ with timings.stage("stitch_finalize"):
155
+ return thread.finalize(), tiles
156
+ finally:
157
+ thread.close()
158
+ # Stop reader processes now rather than at garbage collection, also on errors.
159
+ shutdown = getattr(batches, "_shutdown_workers", None)
160
+ if shutdown is not None:
161
+ shutdown()
@@ -0,0 +1,79 @@
1
+ # pathoinfer - io
2
+
3
+ Writes a slide's stitched result to files: GeoJSON for viewers such as QuPath, Parquet
4
+ for analysis, and pyramidal TIFF for heatmaps. Every coordinate is a level-0 pixel
5
+ coordinate of the slide (x right, y down), not WGS84. `docs/outputs.md` describes each
6
+ file's fields and columns.
7
+
8
+ ## Contract
9
+
10
+ Every writer reads the same two inputs, both from `io/objects.py`:
11
+
12
+ | | |
13
+ |---|---|
14
+ | `RunInfo.create(card, grid, model_source, output_mpp=None, colors=None)` | The run's metadata: slide id and name, task, model name, version and source, ModelCard schema, slide and model mpp, output mpp, tile size, overlap, tissue area, classes (without background, colour overrides applied), package versions, UTC time. Recorded in every output. |
15
+ | `ObjectTable.from_result(result, run, geometry="box")` | One row per object as NumPy columns: shapely `geometry`, `class_id`, `score` (NaN for segmentation), `area_um2` and the task's `measurements`. `geometry` picks box polygons or centre points for detections. |
16
+
17
+ Objects stay columns from stitcher to file, so a million detections never become a
18
+ million Python objects.
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ from pathoinfer.io.objects import ObjectTable, RunInfo
24
+ from pathoinfer.io.writers.geojson import write_geojson
25
+ from pathoinfer.io.writers.parquet import write_parquet, write_summary
26
+ from pathoinfer.io.writers.tiff import write_tiff
27
+
28
+ run = RunInfo.create(card, grid, "models:/cells@prod", colors=config.class_colors)
29
+ objects = ObjectTable.from_result(result, run, geometry=config.detection.geometry)
30
+
31
+ write_geojson("out/slide_name-01.geojson.gz", objects, run)
32
+ write_parquet("out/slide_name-01.objects.parquet", objects, run)
33
+ write_summary("out/slide_name-01.summary.parquet", objects, run)
34
+ if "labels" in result.rasters:
35
+ write_tiff("out/slide_name-01.labels.tiff", result.rasters["labels"], run)
36
+ ```
37
+
38
+ `card` comes from `registry.loader.load_model`, `grid` from `tiling.grid.build_grid` and
39
+ `result` from a stitcher's `finalize()`.
40
+
41
+ Each writer writes `<file>.partial` and renames it when done, so a file that exists is
42
+ complete. Each logs the path it wrote at INFO.
43
+
44
+ ## Modules
45
+
46
+ | Module | Writes |
47
+ |---|---|
48
+ | `writers/geojson.py` | `write_geojson(path, objects, run, per_class=False)`: QuPath FeatureCollection (`objectType`, `classification`, `measurements`, `object_id`), run metadata in the top-level `properties`, coordinates rounded to 0.1 px. `.geojson` or `.geojson.gz`; `per_class` writes `<stem>.<class>.geojson[.gz]` per class. |
49
+ | `writers/parquet.py` | `write_parquet(path, objects, run, geoparquet=False)`: objects table, WKB geometry, zstd, 100k-row row groups, run metadata under the key-value key `pathoinfer`. `write_summary(path, objects, run)`: one row per class with `count`, `mean_score`, `total_area_um2` and `tissue_area_um2`. |
50
+ | `writers/tiff.py` | `write_tiff(path, raster, run)`: 2D raster as a tiled zlib BigTIFF pyramid, each level a top-level image (OpenSlide, fastslide and QuPath open it), resolution tags, label maps 8-bit (255 = no tile), run metadata as JSON in the ImageDescription. |
51
+ | `objects.py` | `RunInfo`, `ObjectTable`. |
52
+ | `interop.py` | `to_geodataframe(path)`: an objects table as a geopandas `GeoDataFrame`, behind the `[geopandas]` extra. The only module that imports geopandas. |
53
+
54
+ Analysis over many slides' Parquet files lives in `pathoinfer.analysis`
55
+ (`class_density`, `score_histogram`); `docs/outputs.md` has examples.
56
+
57
+ ## GeoParquet
58
+
59
+ `geoparquet=True` writes through DuckDB's spatial extension, which adds the GeoParquet
60
+ `geo` metadata. A `geo` entry without a `crs` means longitude and latitude, so the
61
+ geometry is tagged with a PROJJSON engineering CRS for level-0 pixels (`pixel_crs`). The
62
+ writer reads the metadata back after every write and raises if it is missing or wrong.
63
+ The first use downloads the extension, which needs network access. The default, plain
64
+ Parquet with WKB, needs neither.
65
+
66
+ ## Testing
67
+
68
+ `tests/io/` writes the stitched fixtures from `tests/outputs.py` (a disk and an annulus
69
+ from the segmentation stitcher, a grid of detections) and reads each file back:
70
+
71
+ - GeoJSON re-reads with shapely as the same shapes within the 0.1 px rounding, holes
72
+ kept; per-class files keep the global `object_id`s;
73
+ - Parquet reads the same through Polars and DuckDB, and WKB decodes to the same shapes
74
+ exactly;
75
+ - GeoParquet metadata names the pixel CRS (skipped without the spatial extension);
76
+ - the summary counts every class, including classes without objects;
77
+ - the TIFF has the expected pyramid levels, tiling, compression and resolution.
78
+
79
+ `tests/test_analysis.py` runs the analysis queries over two written slides.
@@ -0,0 +1 @@
1
+ """Output formats. Slides are read through patchology, never here."""