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
pathoinfer/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """pathoinfer: whole slide image inference for pathotrain models, built on patchology."""
2
+
3
+ # INFO by default; export PATHOINFER_LOG_LEVEL=DEBUG (or ALL) for more, see patchology.log.
4
+ from pathoinfer._logging import add_file_sink, set_log_level
5
+
6
+ __all__ = ["add_file_sink", "set_log_level"]
pathoinfer/_extras.py ADDED
@@ -0,0 +1,18 @@
1
+ """Lazy imports for optional dependencies, so ``import pathoinfer`` stays light."""
2
+
3
+ import importlib
4
+ from types import ModuleType
5
+
6
+
7
+ def require(module: str, install: str) -> ModuleType:
8
+ """Import ``module`` or raise an ImportError telling the user to run ``install``,
9
+ e.g. ``require("onnxruntime", "pip install 'pathoinfer[onnx]'")``."""
10
+ try:
11
+ return importlib.import_module(module)
12
+ except ImportError as e:
13
+ raise ImportError(f"{module} is not installed: {install}") from e
14
+
15
+
16
+ def extra(name: str) -> str:
17
+ """The install command for pathoinfer's ``name`` extra."""
18
+ return f"pip install 'pathoinfer[{name}]'"
pathoinfer/_logging.py ADDED
@@ -0,0 +1,91 @@
1
+ """loguru setup, shared with patchology and pathotrain through ``patchology.log``.
2
+
3
+ One stderr handler serves the whole process. Its filter gives each record the level set
4
+ for its top-level package by ``<PACKAGE>_LOG_LEVEL`` (``INFO`` when unset, ``ALL`` for
5
+ everything), so ``PATHOINFER_LOG_LEVEL`` controls ``pathoinfer.*`` and
6
+ ``PATCHOLOGY_LOG_LEVEL`` controls ``patchology.*``. pathoinfer adds no stderr handler of
7
+ its own, so nothing prints twice, and never removes a handler it did not add.
8
+
9
+ ``set_log_level`` changes a package's level at runtime by updating its variable, so
10
+ DataLoader workers started afterwards inherit it.
11
+ """
12
+
13
+ import functools
14
+ import os
15
+ from collections.abc import Callable
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ from loguru import logger
20
+
21
+ from patchology.log import configure_logging, level_for
22
+
23
+ if TYPE_CHECKING:
24
+ from loguru import Record
25
+
26
+ LOG_LEVEL = os.getenv("PATHOINFER_LOG_LEVEL", "INFO")
27
+ PACKAGES = ("pathoinfer", "patchology")
28
+
29
+
30
+ def set_log_level(level: str, package: str = "pathoinfer") -> None:
31
+ """Log ``package`` at ``level`` (a loguru level name, or ``ALL``) from now on.
32
+
33
+ Raises:
34
+ ValueError: ``level`` names no loguru level.
35
+ """
36
+ global LOG_LEVEL
37
+ level = level.upper()
38
+ logger.level("TRACE" if level == "ALL" else level)
39
+ os.environ[f"{package.upper()}_LOG_LEVEL"] = level
40
+ # shortcut: patchology caches each package's level; upstream a set_log_level there.
41
+ level_for.cache_clear()
42
+ if package == "pathoinfer":
43
+ LOG_LEVEL = level
44
+
45
+
46
+ def add_file_sink(path: str | Path, level: str = "DEBUG", rotation: str = "50 MB") -> int:
47
+ """Also log pathoinfer's and patchology's records to ``path``; returns the handler id
48
+ to pass to ``logger.remove`` when the run ends. Records are queued, so the run's
49
+ threads never block on the file."""
50
+ return logger.add(
51
+ path,
52
+ level=level,
53
+ rotation=rotation,
54
+ enqueue=True,
55
+ filter=lambda record: (record["name"] or "").partition(".")[0] in PACKAGES,
56
+ )
57
+
58
+
59
+ def log_call[F: Callable[..., Any]](fn: F) -> F:
60
+ """Log each call of ``fn`` at DEBUG with its arguments, under ``fn``'s own module and
61
+ name. Arrays and tensors are logged as shape and dtype, other values cut to 80
62
+ characters. Costs one level check when DEBUG is off."""
63
+
64
+ def at_fn(record: "Record") -> None:
65
+ record["name"] = fn.__module__
66
+ record["function"] = fn.__qualname__
67
+ record["line"] = fn.__code__.co_firstlineno
68
+
69
+ bound = logger.patch(at_fn)
70
+ debug = logger.level("DEBUG").no
71
+ package = fn.__module__.partition(".")[0]
72
+
73
+ @functools.wraps(fn)
74
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
75
+ if level_for(package) <= debug:
76
+ shown = [_short(a) for a in args] + [f"{k}={_short(v)}" for k, v in kwargs.items()]
77
+ bound.debug("{}({})", fn.__qualname__, ", ".join(shown))
78
+ return fn(*args, **kwargs)
79
+
80
+ return wrapper # type: ignore[return-value]
81
+
82
+
83
+ def _short(value: Any) -> str:
84
+ shape, dtype = getattr(value, "shape", None), getattr(value, "dtype", None)
85
+ if shape is not None and dtype is not None:
86
+ return f"{type(value).__name__}(shape={tuple(shape)}, dtype={dtype})"
87
+ text = repr(value)
88
+ return text if len(text) <= 80 else text[:77] + "..."
89
+
90
+
91
+ configure_logging("pathoinfer")
pathoinfer/analysis.py ADDED
@@ -0,0 +1,68 @@
1
+ """DuckDB queries over many slides' Parquet outputs, returned as Polars frames.
2
+
3
+ Arguments are paths or globs, e.g. ``"out/*.objects.parquet"`` and
4
+ ``"out/*.summary.parquet"``. Files are read by column name, so slides from different
5
+ models can share one query.
6
+ """
7
+
8
+ from pathlib import Path
9
+
10
+ import duckdb
11
+ import polars as pl
12
+
13
+ from pathoinfer._logging import log_call
14
+
15
+
16
+ @log_call
17
+ def class_density(
18
+ objects: str | Path, summaries: str | Path, min_score: float | None = None
19
+ ) -> pl.DataFrame:
20
+ """Objects per class per slide, and per mm² of tissue. Classes with no objects get 0.
21
+ ``min_score`` drops scored objects (detections, and regions by their
22
+ ``mean_probability``) below it; unscored objects always count."""
23
+ return _query(
24
+ """
25
+ WITH counts AS (
26
+ SELECT slide_id, class_id, count(*) AS count
27
+ FROM read_parquet($objects, union_by_name = true)
28
+ WHERE $min_score IS NULL OR score IS NULL OR score >= $min_score
29
+ GROUP BY ALL
30
+ )
31
+ SELECT s.slide_id, s.slide_name, s.class_id, s.class_name,
32
+ coalesce(c.count, 0) AS count,
33
+ s.tissue_area_um2 / 1e6 AS tissue_area_mm2,
34
+ coalesce(c.count, 0) / (s.tissue_area_um2 / 1e6) AS per_mm2
35
+ FROM read_parquet($summaries, union_by_name = true) s
36
+ LEFT JOIN counts c USING (slide_id, class_id)
37
+ ORDER BY s.slide_id, s.class_id
38
+ """,
39
+ objects=str(objects),
40
+ summaries=str(summaries),
41
+ min_score=min_score,
42
+ )
43
+
44
+
45
+ @log_call
46
+ def score_histogram(objects: str | Path, bins: int = 10) -> pl.DataFrame:
47
+ """Objects per score bin, per slide and class: ``bins`` equal bins over [0, 1]
48
+ (a score of 1 falls in the last). Objects without a score are skipped."""
49
+ return _query(
50
+ """
51
+ SELECT slide_id, class_name,
52
+ least(floor(score * $bins), $bins - 1)::INTEGER AS bin,
53
+ bin / $bins AS lower, (bin + 1) / $bins AS upper,
54
+ count(*) AS count
55
+ FROM read_parquet($objects, union_by_name = true)
56
+ WHERE score IS NOT NULL
57
+ GROUP BY ALL
58
+ ORDER BY slide_id, class_name, bin
59
+ """,
60
+ objects=str(objects),
61
+ bins=bins,
62
+ )
63
+
64
+
65
+ def _query(sql: str, **params: object) -> pl.DataFrame:
66
+ with duckdb.connect() as con:
67
+ frame: pl.DataFrame = con.sql(sql, params=params).pl()
68
+ return frame
pathoinfer/cli.py ADDED
@@ -0,0 +1,480 @@
1
+ """Command line interface.
2
+
3
+ ``pathoinfer run CONFIG`` run a config's slides; exit 1 if any failed.
4
+ ``pathoinfer validate CONFIG`` check a config, its model and its slides
5
+ without running anything.
6
+ ``pathoinfer info model SOURCE`` show a model's card (folder, models:/, hf://).
7
+ ``pathoinfer info slide PATH`` show a slide's size, levels and resolution.
8
+ ``pathoinfer card create MODEL OUT`` wrap an ONNX / PyTorch / TensorRT / safetensors
9
+ file in a model folder; fields come from the
10
+ file, a legacy ``pathotrain`` key, ``--fields``
11
+ and the flags.
12
+ ``pathoinfer card validate FOLDER`` check a model folder's card and, for ONNX, that
13
+ the graph matches it.
14
+ ``pathoinfer convert fp16 SOURCE OUT`` FP32 ONNX -> FP16 ONNX model folder.
15
+ ``pathoinfer convert ptq SOURCE OUT --config QUANT.yaml``
16
+ INT8/FP8 static PTQ, calibrated on slides.
17
+ ``pathoinfer convert trt SOURCE OUT`` TensorRT plan for this GPU (cached).
18
+ ``pathoinfer convert parity REFERENCE CANDIDATE OUT --config PARITY.yaml``
19
+ compare through the real stitchers; on a pass
20
+ write OUT with the parity in its card (and
21
+ register it with --register NAME --alias A).
22
+ ``pathoinfer serve api [--jobs-dir DIR] [--max-jobs N]``
23
+ the slide job API (FastAPI + uvicorn).
24
+ ``pathoinfer serve triton-repo MODEL... --repository DIR``
25
+ a Triton model repository from model folders.
26
+ ``pathoinfer serve vllm MODEL [--config VLLM.yaml]``
27
+ print the ``vllm serve`` command for a VLM
28
+ folder (dtype and quantisation from its card).
29
+ ``pathoinfer convert vlm-merge BASE ADAPTER OUT --card CARD.yaml``
30
+ merge LoRA adapters into a bf16 VLM folder.
31
+ ``pathoinfer convert vlm SOURCE OUT --config VLM.yaml``
32
+ quantise a VLM's language model for vLLM.
33
+ ``pathoinfer convert vlm-parity REFERENCE CANDIDATE OUT --config P.yaml
34
+ --reference-url URL --candidate-url URL`` VLM parity through two vLLM servers.
35
+
36
+ ``--log-level LEVEL`` (or ``-v`` for DEBUG), before the command, sets pathoinfer's and
37
+ patchology's log level; the default comes from ``PATHOINFER_LOG_LEVEL`` and
38
+ ``PATCHOLOGY_LOG_LEVEL``.
39
+
40
+ Only ``run`` and ``convert`` import torch, so every other command starts fast.
41
+ """
42
+
43
+ import argparse
44
+ import json
45
+ import shlex
46
+ import sys
47
+ from dataclasses import asdict
48
+ from pathlib import Path
49
+ from typing import Any
50
+
51
+ import yaml
52
+ from loguru import logger
53
+ from pydantic import ValidationError
54
+
55
+ from patchology import SlideOpenError, open_slide
56
+ from pathoinfer._logging import PACKAGES, set_log_level
57
+ from pathoinfer.config import (
58
+ ParityConfig,
59
+ QuantConfig,
60
+ RunConfig,
61
+ VlmParityConfig,
62
+ VlmQuantConfig,
63
+ load_config,
64
+ load_yaml,
65
+ )
66
+ from pathoinfer.registry.create import create_folder
67
+ from pathoinfer.registry.loader import (
68
+ CardError,
69
+ graph_problems,
70
+ load_any,
71
+ load_model,
72
+ load_vlm,
73
+ validate_folder,
74
+ )
75
+ from pathoinfer.registry.model_card import SegmentationCard, VqaCard
76
+ from pathoinfer.tiling.slide_id import slide_id
77
+
78
+ LEVELS = ["TRACE", "DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL", "ALL"]
79
+
80
+
81
+ def main(argv: list[str] | None = None) -> int:
82
+ args = _parser().parse_args(argv)
83
+ if args.log_level:
84
+ for package in PACKAGES:
85
+ set_log_level(args.log_level, package)
86
+ try:
87
+ return int(args.handler(args))
88
+ except (
89
+ CardError,
90
+ ValidationError,
91
+ ValueError,
92
+ FileNotFoundError,
93
+ SlideOpenError,
94
+ NotImplementedError,
95
+ ) as e:
96
+ logger.error("{}", _describe(e))
97
+ return 1
98
+
99
+
100
+ def _parser() -> argparse.ArgumentParser:
101
+ parser = argparse.ArgumentParser(prog="pathoinfer")
102
+ level = parser.add_mutually_exclusive_group()
103
+ level.add_argument(
104
+ "--log-level",
105
+ type=str.upper,
106
+ choices=LEVELS,
107
+ help="log level for pathoinfer and patchology (default: their *_LOG_LEVEL, else INFO)",
108
+ )
109
+ level.add_argument(
110
+ "-v", "--verbose", action="store_const", const="DEBUG", dest="log_level", help="DEBUG"
111
+ )
112
+ commands = parser.add_subparsers(dest="command", required=True)
113
+
114
+ run = commands.add_parser("run", help="run a config over its slides")
115
+ run.add_argument("config", type=Path)
116
+ run.set_defaults(handler=_run)
117
+ validate = commands.add_parser("validate", help="check a config without running it")
118
+ validate.add_argument("config", type=Path)
119
+ validate.set_defaults(handler=_validate_config)
120
+
121
+ info = commands.add_parser("info", help="describe a model or a slide").add_subparsers(
122
+ dest="info_command", required=True
123
+ )
124
+ model = info.add_parser("model", help="show a model's card")
125
+ model.add_argument(
126
+ "source", help="model folder, ONNX file, models:/NAME@ALIAS or hf://ORG/REPO"
127
+ )
128
+ model.set_defaults(handler=_info_model)
129
+ slide = info.add_parser("slide", help="show a slide's size, levels and resolution")
130
+ slide.add_argument("path", type=Path)
131
+ slide.add_argument("--backend", default="openslide", choices=["openslide", "fastslide"])
132
+ slide.set_defaults(handler=_info_slide)
133
+
134
+ card = commands.add_parser("card", help="create or validate model folders").add_subparsers(
135
+ dest="card_command", required=True
136
+ )
137
+ create = card.add_parser("create", help="wrap a model file in a model folder")
138
+ create.add_argument("model", type=Path, help="model file")
139
+ create.add_argument("out", type=Path, help="new model folder")
140
+ create.add_argument("--fields", type=Path, help="YAML or JSON with (partial) card fields")
141
+ create.add_argument("--name", help="card name (default: the file stem)")
142
+ create.add_argument("--version", help="card version")
143
+ create.set_defaults(handler=_create)
144
+ check = card.add_parser("validate", help="validate a model folder")
145
+ check.add_argument("folder", type=Path)
146
+ check.set_defaults(handler=lambda args: _validate_card(args.folder))
147
+
148
+ convert = commands.add_parser("convert", help="convert models offline").add_subparsers(
149
+ dest="convert_command", required=True
150
+ )
151
+ fp16 = convert.add_parser("fp16", help="FP32 ONNX -> FP16 ONNX")
152
+ fp16.add_argument("source", help="model source (folder, ONNX file, models:/, hf://)")
153
+ fp16.add_argument("out", type=Path, help="new model folder")
154
+ fp16.add_argument(
155
+ "--fp16-io", action="store_true", help="make the graph's inputs/outputs float16 too"
156
+ )
157
+ fp16.add_argument(
158
+ "--keep-fp32", nargs="+", default=[], metavar="OP", help="op types to keep in FP32"
159
+ )
160
+ fp16.set_defaults(handler=_convert_fp16)
161
+ ptq = convert.add_parser("ptq", help="INT8/FP8 static post-training quantisation")
162
+ ptq.add_argument("source")
163
+ ptq.add_argument("out", type=Path)
164
+ ptq.add_argument("--config", type=Path, required=True, help="QuantConfig YAML")
165
+ ptq.set_defaults(handler=_convert_ptq)
166
+ plan = convert.add_parser("trt", help="TensorRT plan for this GPU")
167
+ plan.add_argument("source")
168
+ plan.add_argument("out", type=Path)
169
+ plan.add_argument(
170
+ "--batch", type=int, nargs=3, default=[1, 32, 64], metavar=("MIN", "OPT", "MAX")
171
+ )
172
+ plan.add_argument(
173
+ "--workspace-gb", type=float, default=None, help="tactic memory cap (default: the GPU's)"
174
+ )
175
+ plan.add_argument("--device", type=int, default=0, help="CUDA device index")
176
+ plan.set_defaults(handler=_convert_trt)
177
+ parity = convert.add_parser("parity", help="parity gate for a converted model")
178
+ parity.add_argument("reference")
179
+ parity.add_argument("candidate")
180
+ parity.add_argument("out", type=Path, help="new model folder written on a pass")
181
+ parity.add_argument("--config", type=Path, required=True, help="ParityConfig YAML")
182
+ parity.add_argument("--register", metavar="NAME", help="MLflow registered model name")
183
+ parity.add_argument("--alias", help="MLflow alias, e.g. fp16-blackwell (with --register)")
184
+ parity.add_argument("--tracking-uri", help="MLflow tracking URI (default: environment)")
185
+ parity.add_argument("--report", type=Path, help="write the parity report as JSON")
186
+ parity.set_defaults(handler=_convert_parity)
187
+ serve = commands.add_parser("serve", help="serve models and slide jobs").add_subparsers(
188
+ dest="serve_command", required=True
189
+ )
190
+ api = serve.add_parser("api", help="run the slide job API")
191
+ api.add_argument("--host", default="0.0.0.0")
192
+ api.add_argument("--port", type=int, default=8080)
193
+ api.add_argument("--jobs-dir", type=Path, default=Path("jobs"))
194
+ api.add_argument("--max-jobs", type=int, default=1, help="jobs running at once")
195
+ api.set_defaults(handler=_serve_api)
196
+ repo = serve.add_parser("triton-repo", help="write a Triton model repository")
197
+ repo.add_argument("models", nargs="+", help="model sources (folders, models:/, hf://)")
198
+ repo.add_argument("--repository", type=Path, required=True)
199
+ repo.add_argument("--config", type=Path, help="TritonRepoConfig YAML")
200
+ repo.set_defaults(handler=_serve_triton_repo)
201
+ vllm = serve.add_parser("vllm", help="print the vllm serve command for a VLM folder")
202
+ vllm.add_argument("model", help="VLM source (folder, models:/, hf://)")
203
+ vllm.add_argument("--config", type=Path, help="VllmServeConfig YAML")
204
+ vllm.set_defaults(handler=_serve_vllm)
205
+ merge = convert.add_parser("vlm-merge", help="merge LoRA adapters into a VLM")
206
+ merge.add_argument("base", help="base model folder or Hugging Face Hub id")
207
+ merge.add_argument("adapter", help="PEFT adapter folder or Hub id")
208
+ merge.add_argument("out", type=Path)
209
+ merge.add_argument("--card", type=Path, required=True, help="VqaCard fields (YAML)")
210
+ merge.set_defaults(handler=_convert_vlm_merge)
211
+ vlm = convert.add_parser("vlm", help="quantise a VLM's language model (llm-compressor)")
212
+ vlm.add_argument("source", help="bf16 VLM folder with a VqaCard")
213
+ vlm.add_argument("out", type=Path)
214
+ vlm.add_argument("--config", type=Path, required=True, help="VlmQuantConfig YAML")
215
+ vlm.set_defaults(handler=_convert_vlm)
216
+ vparity = convert.add_parser("vlm-parity", help="VLM parity gate through vLLM servers")
217
+ vparity.add_argument("reference")
218
+ vparity.add_argument("candidate")
219
+ vparity.add_argument("out", type=Path, help="new folder written on a pass")
220
+ vparity.add_argument("--config", type=Path, required=True, help="VlmParityConfig YAML")
221
+ vparity.add_argument("--reference-url", required=True, help="vLLM serving the reference")
222
+ vparity.add_argument("--candidate-url", required=True, help="vLLM serving the candidate")
223
+ vparity.add_argument("--register", metavar="NAME")
224
+ vparity.add_argument("--alias")
225
+ vparity.add_argument("--tracking-uri")
226
+ vparity.add_argument("--report", type=Path)
227
+ vparity.set_defaults(handler=_convert_vlm_parity)
228
+ return parser
229
+
230
+
231
+ def _run(args: argparse.Namespace) -> int:
232
+ from pathoinfer.engine.pipeline import run_batch # imports torch
233
+
234
+ results = run_batch(load_config(args.config))
235
+ return 1 if any(r.status == "failed" for r in results) else 0
236
+
237
+
238
+ def _validate_config(args: argparse.Namespace) -> int:
239
+ cfg = load_config(args.config)
240
+ problems = _config_problems(cfg)
241
+ for problem in problems:
242
+ logger.error("{}", problem)
243
+ if not problems:
244
+ logger.info("ok: {} ({}, {} slides)", args.config, cfg.task, len(cfg.slide_paths()))
245
+ return 1 if problems else 0
246
+
247
+
248
+ def _config_problems(cfg: RunConfig) -> list[str]:
249
+ problems = []
250
+ slides = cfg.slide_paths()
251
+ if not slides:
252
+ problems.append(f"no slides match {cfg.slides!r}")
253
+ problems += [f"slide not found: {p}" for p in slides if not p.exists()]
254
+ try:
255
+ card, _ = load_model(cfg.model)
256
+ except (CardError, FileNotFoundError, ImportError) as e:
257
+ return [*problems, f"model {cfg.model}: {e}"]
258
+ if card.task != cfg.task:
259
+ problems.append(f"config task is {cfg.task}, but {cfg.model} is a {card.task} model")
260
+ if card.task == "classification":
261
+ names = {c.name for c in card.classes}
262
+ stray = sorted(set(cfg.classification.thresholds) - names)
263
+ if stray:
264
+ problems.append(f"classification.thresholds names unknown classes {stray}")
265
+ renamed = set(cfg.segmentation.class_map) if card.task == "segmentation" else set()
266
+ unknown = set(cfg.class_colors) - {c.name for c in card.classes} - renamed
267
+ if unknown:
268
+ problems.append(f"class_colors names unknown classes {sorted(unknown)}")
269
+ output_mpp = cfg.segmentation.output_mpp
270
+ if card.task == "segmentation" and output_mpp is not None and output_mpp < card.input.mpp:
271
+ problems.append(f"segmentation.output_mpp {output_mpp} is finer than the model's")
272
+ if isinstance(card, SegmentationCard):
273
+ try:
274
+ cfg.segmentation.class_remap(card)
275
+ except ValueError as e:
276
+ problems.append(str(e))
277
+ return problems
278
+
279
+
280
+ def _convert_fp16(args: argparse.Namespace) -> int:
281
+ from pathoinfer.convert.fp16 import to_fp16
282
+
283
+ to_fp16(args.source, args.out, keep_io_types=not args.fp16_io, keep_fp32_ops=args.keep_fp32)
284
+ return 0
285
+
286
+
287
+ def _convert_ptq(args: argparse.Namespace) -> int:
288
+ from pathoinfer.convert.ptq import quantise
289
+
290
+ quantise(args.source, args.out, load_yaml(args.config, QuantConfig))
291
+ return 0
292
+
293
+
294
+ def _convert_trt(args: argparse.Namespace) -> int:
295
+ from pathoinfer.convert.tensorrt import build_plan
296
+
297
+ low, opt, high = args.batch
298
+ build_plan(
299
+ args.source,
300
+ args.out,
301
+ min_batch=low,
302
+ opt_batch=opt,
303
+ max_batch=high,
304
+ workspace_gb=args.workspace_gb,
305
+ device=args.device,
306
+ )
307
+ return 0
308
+
309
+
310
+ def _convert_parity(args: argparse.Namespace) -> int:
311
+ from pathoinfer.convert.parity import gate
312
+
313
+ if bool(args.register) != bool(args.alias):
314
+ raise ValueError("--register and --alias go together")
315
+ register = (args.register, args.alias) if args.register else None
316
+ report = gate(
317
+ args.reference,
318
+ args.candidate,
319
+ load_yaml(args.config, ParityConfig),
320
+ args.out,
321
+ register,
322
+ args.tracking_uri,
323
+ )
324
+ if args.report:
325
+ args.report.write_text(json.dumps(asdict(report), indent=2) + "\n")
326
+ return 0 if report.passed else 1
327
+
328
+
329
+ def _serve_api(args: argparse.Namespace) -> int:
330
+ from pathoinfer._extras import extra, require
331
+ from pathoinfer.serving.api import create_app
332
+
333
+ uvicorn = require("uvicorn", extra("serve"))
334
+ uvicorn.run(create_app(args.jobs_dir, args.max_jobs), host=args.host, port=args.port)
335
+ return 0
336
+
337
+
338
+ def _serve_triton_repo(args: argparse.Namespace) -> int:
339
+ from pathoinfer.serving.triton_repo import TritonRepoConfig, write_repository
340
+
341
+ cfg = load_yaml(args.config, TritonRepoConfig) if args.config else TritonRepoConfig()
342
+ write_repository(args.models, args.repository, cfg)
343
+ return 0
344
+
345
+
346
+ def _serve_vllm(args: argparse.Namespace) -> int:
347
+ from pathoinfer.serving.vllm import VllmServeConfig, serve_command
348
+
349
+ cfg = load_yaml(args.config, VllmServeConfig) if args.config else VllmServeConfig()
350
+ card, folder = load_vlm(args.model)
351
+ sys.stdout.write(shlex.join(serve_command(card, folder, cfg)) + "\n")
352
+ return 0
353
+
354
+
355
+ def _convert_vlm_merge(args: argparse.Namespace) -> int:
356
+ from pathoinfer.convert.vlm import merge_lora
357
+
358
+ merge_lora(args.base, args.adapter, args.out, yaml.safe_load(args.card.read_text()))
359
+ return 0
360
+
361
+
362
+ def _convert_vlm(args: argparse.Namespace) -> int:
363
+ from pathoinfer.convert.vlm import quantise_vlm
364
+
365
+ quantise_vlm(args.source, args.out, load_yaml(args.config, VlmQuantConfig))
366
+ return 0
367
+
368
+
369
+ def _convert_vlm_parity(args: argparse.Namespace) -> int:
370
+ from pathoinfer.convert.vlm_parity import gate, report_json
371
+
372
+ if bool(args.register) != bool(args.alias):
373
+ raise ValueError("--register and --alias go together")
374
+ report = gate(
375
+ args.reference,
376
+ args.candidate,
377
+ load_yaml(args.config, VlmParityConfig),
378
+ args.out,
379
+ args.reference_url,
380
+ args.candidate_url,
381
+ (args.register, args.alias) if args.register else None,
382
+ args.tracking_uri,
383
+ )
384
+ if args.report:
385
+ args.report.write_text(report_json(report))
386
+ return 0 if report.passed else 1
387
+
388
+
389
+ def _info_model(args: argparse.Namespace) -> int:
390
+ any_card, model_dir = load_any(args.source)
391
+ if isinstance(any_card, VqaCard):
392
+ logger.info(
393
+ "{} {} | vqa | {} {} | {} px at {} mpp | grounding {} | folder {}",
394
+ any_card.name,
395
+ any_card.version,
396
+ any_card.architecture,
397
+ any_card.precision,
398
+ any_card.input.tile_size,
399
+ any_card.input.mpp,
400
+ any_card.output.grounding,
401
+ model_dir,
402
+ )
403
+ return 0
404
+ card = any_card
405
+ logger.info(
406
+ "{} {} | {} | {} {} ({}) | {} px at {} mpp, {} {} {} | overlap {:.2f} | folder {}",
407
+ card.name,
408
+ card.version,
409
+ card.task,
410
+ card.framework,
411
+ card.file,
412
+ card.precision,
413
+ card.input.tile_size,
414
+ card.input.mpp,
415
+ card.input.channel_order,
416
+ card.input.layout,
417
+ card.input.dtype,
418
+ card.recommended_overlap,
419
+ model_dir,
420
+ )
421
+ background = getattr(card, "background_id", None)
422
+ for c in card.classes:
423
+ logger.info(
424
+ "class {} {} {}{}", c.id, c.name, list(c.color), " (background)" * (c.id == background)
425
+ )
426
+ logger.info("output {}", card.output.model_dump_json())
427
+ return 0
428
+
429
+
430
+ def _info_slide(args: argparse.Namespace) -> int:
431
+ with open_slide(args.path, args.backend) as slide:
432
+ mpp = slide.mpp
433
+ logger.info(
434
+ "{} | {} x {} px | mpp {} | slide_id {}",
435
+ args.path.name,
436
+ *slide.dimensions,
437
+ "missing (inference will refuse this slide)"
438
+ if mpp is None
439
+ else f"{mpp[0]:.4g} x {mpp[1]:.4g}",
440
+ slide_id(args.path),
441
+ )
442
+ for level, ((w, h), d) in enumerate(
443
+ zip(slide.level_dimensions, slide.level_downsamples, strict=True)
444
+ ):
445
+ logger.info("level {}: {} x {} px, downsample {:.4g}", level, w, h, d)
446
+ return 0
447
+
448
+
449
+ def _create(args: argparse.Namespace) -> int:
450
+ fields: dict[str, Any] = yaml.safe_load(args.fields.read_text()) if args.fields else {}
451
+ fields |= {k: v for k in ("name", "version") if (v := getattr(args, k)) is not None}
452
+ card = create_folder(args.model, args.out, fields)
453
+ logger.info("wrote {} ({}, {} {})", args.out, card.task, card.name, card.version)
454
+ return 0
455
+
456
+
457
+ def _validate_card(folder: Path) -> int:
458
+ card = validate_folder(folder)
459
+ try:
460
+ problems = graph_problems(card, folder)
461
+ except ImportError as e:
462
+ logger.warning("graph not checked: {}", e)
463
+ problems = []
464
+ for problem in problems:
465
+ logger.error("{}", problem)
466
+ if not problems:
467
+ logger.info("ok: {} ({}, {} {})", folder, card.task, card.name, card.version)
468
+ return 1 if problems else 0
469
+
470
+
471
+ def _describe(error: Exception) -> str:
472
+ if isinstance(error, ValidationError):
473
+ return "invalid config:\n" + "\n".join(
474
+ f" {'.'.join(map(str, e['loc']))}: {e['msg']}" for e in error.errors()
475
+ )
476
+ return str(error)
477
+
478
+
479
+ if __name__ == "__main__":
480
+ sys.exit(main())