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,139 @@
1
+ """Build TensorRT plans from ONNX model folders, per GPU.
2
+
3
+ A plan is built as a strongly typed network: its precision is the ONNX graph's (FP32,
4
+ FP16 from ``convert fp16``, or INT8/FP8 Q/DQ from ``convert ptq``), so the plan computes
5
+ what parity checked. One optimisation profile covers batch sizes ``min_batch`` to
6
+ ``max_batch``, tuned for ``opt_batch``. Plans run only on the GPU architecture and
7
+ TensorRT version they were built with, so built plans are cached under ``cache`` by
8
+ (model hash, GPU, compute capability, TensorRT version, precision, profile). The model
9
+ hash covers the graph and any external weights beside it (models over 2 GB).
10
+ """
11
+
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import shutil
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import torch
20
+ from loguru import logger
21
+
22
+ from pathoinfer._extras import extra, require
23
+ from pathoinfer._logging import log_call
24
+ from pathoinfer.convert.common import write_variant
25
+ from pathoinfer.registry.loader import load_model
26
+ from pathoinfer.registry.model_card import ModelCard
27
+
28
+ CACHE = Path.home() / ".cache" / "pathoinfer" / "plans"
29
+
30
+
31
+ @log_call
32
+ def build_plan(
33
+ source: str | Path,
34
+ out: Path,
35
+ *,
36
+ min_batch: int = 1,
37
+ opt_batch: int = 32,
38
+ max_batch: int = 64,
39
+ workspace_gb: float | None = None,
40
+ cache: Path = CACHE,
41
+ device: int = 0,
42
+ ) -> ModelCard:
43
+ """Build (or reuse from ``cache``) a plan for the ONNX model at ``source`` on CUDA
44
+ device ``device`` and write it as the new model folder ``out``. ``workspace_gb`` caps
45
+ the scratch memory tactics may use; None leaves TensorRT's default (the GPU's memory):
46
+ 4 GB was too little for an FP32 HoVer-Net."""
47
+ trt = require("tensorrt", extra("trt"))
48
+ if not 1 <= min_batch <= opt_batch <= max_batch:
49
+ raise ValueError(
50
+ f"need 1 <= min <= opt <= max batch, got {min_batch}, {opt_batch}, {max_batch}"
51
+ )
52
+ card, model_dir = load_model(str(source))
53
+ if card.framework != "onnx":
54
+ raise ValueError(f"expected an ONNX model, got {card.framework}")
55
+ gpu = torch.cuda.get_device_name(device)
56
+ capability = "{}.{}".format(*torch.cuda.get_device_capability(device))
57
+ key_fields = {
58
+ "model": _model_hash(model_dir),
59
+ "gpu": gpu,
60
+ "compute_capability": capability,
61
+ "tensorrt": trt.__version__,
62
+ "precision": card.precision,
63
+ "profile": [min_batch, opt_batch, max_batch],
64
+ }
65
+ key = hashlib.sha256(json.dumps(key_fields, sort_keys=True).encode()).hexdigest()[:16]
66
+ cached = cache / f"{key}.plan"
67
+ if cached.is_file():
68
+ logger.info("plan cache hit: {}", cached)
69
+ else:
70
+ with torch.cuda.device(device):
71
+ plan = _build(
72
+ trt, model_dir / card.file, card, (min_batch, opt_batch, max_batch), workspace_gb
73
+ )
74
+ cache.mkdir(parents=True, exist_ok=True)
75
+ partial = cached.with_suffix(".partial")
76
+ partial.write_bytes(plan)
77
+ os.replace(partial, cached)
78
+ logger.info("built plan {} ({:.1f} MB)", cached, len(plan) / 1e6)
79
+ tag = f"{gpu.replace(' ', '-').lower()}-sm{capability.replace('.', '')}"
80
+ return write_variant(
81
+ card,
82
+ out,
83
+ lambda path: shutil.copyfile(cached, path),
84
+ framework="tensorrt",
85
+ file="model.plan",
86
+ version=f"{card.version}+trt-{tag}",
87
+ **{
88
+ "provenance.source_metadata": {
89
+ **card.provenance.source_metadata,
90
+ "tensorrt": key_fields | {"cache_key": key},
91
+ }
92
+ },
93
+ )
94
+
95
+
96
+ def _model_hash(model_dir: Path) -> str:
97
+ """The graph and every other file in its folder but the card: external weights live
98
+ beside the graph, and a graph-only hash would reuse a plan across retrained weights."""
99
+ digest = hashlib.sha256()
100
+ for path in sorted(model_dir.iterdir()):
101
+ if path.is_file() and path.name != "model_card.json":
102
+ with path.open("rb") as f:
103
+ while chunk := f.read(1 << 24):
104
+ digest.update(chunk)
105
+ return digest.hexdigest()[:16]
106
+
107
+
108
+ def _build(
109
+ trt: Any,
110
+ onnx_path: Path,
111
+ card: ModelCard,
112
+ batches: tuple[int, int, int],
113
+ workspace_gb: float | None,
114
+ ) -> bytes:
115
+ log = trt.Logger(trt.Logger.WARNING)
116
+ builder = trt.Builder(log)
117
+ network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
118
+ parser = trt.OnnxParser(network, log)
119
+ if not parser.parse_from_file(str(onnx_path)): # finds external weights beside it
120
+ errors = [str(parser.get_error(i)) for i in range(parser.num_errors)]
121
+ raise ValueError("TensorRT could not parse the ONNX model:\n" + "\n".join(errors))
122
+ config = builder.create_builder_config()
123
+ if workspace_gb is not None:
124
+ config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, int(workspace_gb * 2**30))
125
+ profile = builder.create_optimization_profile()
126
+ size = card.input.tile_size
127
+ shape = (3, size, size) if card.input.layout == "NCHW" else (size, size, 3)
128
+ profile.set_shape(card.input.name, *[(b, *shape) for b in batches])
129
+ config.add_optimization_profile(profile)
130
+ plan = builder.build_serialized_network(network, config)
131
+ if plan is None:
132
+ hint = (
133
+ f"; with --workspace-gb {workspace_gb:g}, 'Could not find any implementation' means "
134
+ "too little workspace: raise it or leave it unset"
135
+ if workspace_gb is not None
136
+ else ""
137
+ )
138
+ raise RuntimeError(f"TensorRT failed to build the plan (see its log above){hint}")
139
+ return bytes(plan)
@@ -0,0 +1,359 @@
1
+ """Vision-language models (Qwen3-VL, SmolVLM) fine-tuned with TRL + PEFT, for vLLM.
2
+
3
+ 1. ``merge_lora``: fold LoRA adapters into the base weights and save a bf16 Hugging Face
4
+ folder (safetensors) with its processor and a VqaCard.
5
+ 2. ``quantise_vlm``: an llm-compressor recipe on the **language model only**. The ignore
6
+ list is built from the model's own module names (``ignore_list``): every child of
7
+ ``model`` except the language model (vision encoder, merger/projector) and ``lm_head``
8
+ stay bf16, and the list is checked to cover exactly the non-language Linear layers.
9
+ Schemes: ``fp8`` (W8A8, dynamic activations), ``w4a16-awq``, ``w4a16-gptq``; the
10
+ 4-bit ones calibrate on pathology image + question pairs. The output is
11
+ compressed-tensors safetensors, which vLLM loads.
12
+ 3. Parity against bf16 runs in ``convert.vlm_parity`` over HTTP. pathoinfer never
13
+ imports vllm.
14
+
15
+ Heavy imports (transformers, peft, llmcompressor) are inside the functions, so this
16
+ module imports without the ``[vlm-convert]`` extra.
17
+ """
18
+
19
+ import hashlib
20
+ import json
21
+ import os
22
+ import random
23
+ import re
24
+ import shutil
25
+ from collections.abc import Mapping
26
+ from dataclasses import dataclass
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ import cv2
31
+ import numpy as np
32
+ import polars as pl
33
+ import yaml
34
+ from loguru import logger
35
+ from numpy.typing import NDArray
36
+
37
+ from pathoinfer._extras import extra, require
38
+ from pathoinfer._logging import log_call
39
+ from pathoinfer.config import VlmQuantConfig, VqaDataConfig
40
+ from pathoinfer.convert.common import CARD_FILE
41
+ from pathoinfer.registry.loader import load_vlm
42
+ from pathoinfer.registry.model_card import VqaCard
43
+
44
+ # Where the language model lives, by attribute of ``model.model``; everything else there
45
+ # (vision tower, merger/projector) is kept in bf16.
46
+ LANGUAGE_MODELS = ("language_model", "text_model")
47
+ SCHEMES: dict[str, dict[str, Any]] = {
48
+ "fp8": {"modifier": "QuantizationModifier", "scheme": "FP8_DYNAMIC", "calibrated": False},
49
+ "w4a16-awq": {"modifier": "QuantizationModifier", "scheme": "W4A16_ASYM", "calibrated": True},
50
+ "w4a16-gptq": {"modifier": "GPTQModifier", "scheme": "W4A16", "calibrated": True},
51
+ }
52
+ # AWQ smoothing pairs (smooth layer -> balance layers) of Qwen3 and Llama decoder layers,
53
+ # the text models of Qwen3-VL and SmolVLM. llm-compressor has no mappings for the VLM
54
+ # classes, so these are anchored to the language model path: the vision tower has
55
+ # similarly named layers that must not be touched.
56
+ AWQ_PAIRS = [
57
+ ("input_layernorm", ["q_proj", "k_proj", "v_proj"]),
58
+ ("v_proj", ["o_proj"]),
59
+ ("post_attention_layernorm", ["gate_proj", "up_proj"]),
60
+ ("up_proj", ["down_proj"]),
61
+ ]
62
+ PRECISIONS = {"fp8": "fp8", "w4a16-awq": "int4", "w4a16-gptq": "int4"}
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class IgnoreList:
67
+ """Which Linear layers a recipe quantises and which it keeps in bf16."""
68
+
69
+ language_model: str # module path of the language model, e.g. model.language_model
70
+ patterns: list[str] # llm-compressor ``ignore`` entries
71
+ quantised: list[str] # Linear module names the recipe will quantise
72
+ kept: list[str] # Linear module names left in bf16
73
+
74
+
75
+ def ignore_list(model: Any, extra_patterns: list[str] | None = None) -> IgnoreList:
76
+ """Ignore everything but the language model's Linear layers, verified against the
77
+ model's module names.
78
+
79
+ Raises:
80
+ ValueError: no language model found, a pattern matches no module, or the
81
+ patterns would quantise a non-language Linear or skip a language one.
82
+ """
83
+ import torch
84
+
85
+ inner = model.model
86
+ names = [n for n in LANGUAGE_MODELS if hasattr(inner, n)]
87
+ if len(names) != 1:
88
+ raise ValueError(
89
+ f"cannot find the language model among {[n for n, _ in inner.named_children()]}"
90
+ )
91
+ language = f"model.{names[0]}"
92
+ others = [n for n, child in inner.named_children() if n != names[0] and _has_linear(child)]
93
+ patterns = [f"re:^model\\.{re.escape(n)}\\." for n in others] + [
94
+ "lm_head",
95
+ *(extra_patterns or []),
96
+ ]
97
+ linear = [n for n, m in model.named_modules() if isinstance(m, torch.nn.Linear)]
98
+ kept = [n for n in linear if any(_matches(p, n) for p in patterns)]
99
+ quantised = [n for n in linear if n not in kept]
100
+ unused = [p for p in patterns if not any(_matches(p, n) for n in linear)]
101
+ if unused:
102
+ raise ValueError(f"ignore patterns match no Linear layer: {unused}")
103
+ outside = [n for n in quantised if not n.startswith(language + ".")]
104
+ if outside:
105
+ raise ValueError(f"would quantise layers outside the language model: {outside[:5]}")
106
+ if not quantised:
107
+ raise ValueError("nothing left to quantise")
108
+ return IgnoreList(language, patterns, quantised, kept)
109
+
110
+
111
+ def awq_mappings(model: Any, language_model: str) -> list[dict[str, Any]]:
112
+ """:data:`AWQ_PAIRS` as llm-compressor mappings inside ``language_model``, each
113
+ checked to match modules of ``model``.
114
+
115
+ Raises:
116
+ ValueError: a mapping matches nothing (an unsupported text model).
117
+ """
118
+ names = [n for n, _ in model.named_modules()]
119
+ prefix = "re:^" + re.escape(language_model) + r"\..*"
120
+ mappings = []
121
+ for smooth, balance in AWQ_PAIRS:
122
+ smooth_layer = f"{prefix}{smooth}$"
123
+ balance_layers = [f"{prefix}{b}$" for b in balance]
124
+ for pattern in [smooth_layer, *balance_layers]:
125
+ if not any(_matches(pattern, n) for n in names):
126
+ raise ValueError(f"AWQ mapping {pattern} matches no module of {language_model}")
127
+ mappings.append({"smooth_layer": smooth_layer, "balance_layers": balance_layers})
128
+ return mappings
129
+
130
+
131
+ def recipe(
132
+ scheme: str, ignore: list[str], mappings: list[dict[str, Any]] | None = None
133
+ ) -> dict[str, Any]:
134
+ """The llm-compressor recipe for ``scheme`` on Linear layers, minus ``ignore``.
135
+ ``w4a16-awq`` smooths with ``mappings`` (:func:`awq_mappings`) before quantising."""
136
+ spec = SCHEMES[scheme]
137
+ modifiers: dict[str, Any] = {}
138
+ if scheme == "w4a16-awq":
139
+ if not mappings:
140
+ raise ValueError("w4a16-awq needs AWQ mappings")
141
+ modifiers["AWQModifier"] = {"mappings": mappings, "duo_scaling": True}
142
+ modifiers[spec["modifier"]] = {
143
+ "targets": ["Linear"],
144
+ "scheme": spec["scheme"],
145
+ "ignore": ignore,
146
+ }
147
+ return {"quant_stage": {"quant_modifiers": modifiers}}
148
+
149
+
150
+ def recipe_yaml(
151
+ scheme: str, ignore: list[str], mappings: list[dict[str, Any]] | None = None
152
+ ) -> str:
153
+ """:func:`recipe` as the YAML text llm-compressor takes."""
154
+ return str(yaml.safe_dump(recipe(scheme, ignore, mappings), sort_keys=False))
155
+
156
+
157
+ @log_call
158
+ def merge_lora(
159
+ base: str | Path, adapter: str | Path, out: Path, card: Mapping[str, Any]
160
+ ) -> VqaCard:
161
+ """Merge the PEFT adapter at ``adapter`` into ``base`` (a local folder or Hub id) and
162
+ write a bf16 model folder with its processor and a VqaCard. ``card`` gives the card
163
+ fields the weights cannot (name, version, input, output)."""
164
+ peft = require("peft", extra("vlm-convert"))
165
+ transformers = require("transformers", extra("vlm-convert"))
166
+ import torch
167
+
168
+ if out.exists():
169
+ raise FileExistsError(f"{out} exists; choose a new folder")
170
+ model = transformers.AutoModelForImageTextToText.from_pretrained(base, dtype=torch.bfloat16)
171
+ merged = peft.PeftModel.from_pretrained(model, adapter).merge_and_unload()
172
+ processor = transformers.AutoProcessor.from_pretrained(base)
173
+ partial = out.with_name(out.name + ".partial")
174
+ shutil.rmtree(partial, ignore_errors=True)
175
+ merged.save_pretrained(partial, safe_serialization=True)
176
+ processor.save_pretrained(partial)
177
+ vqa = _card(
178
+ card,
179
+ architecture=merged.config.architectures[0],
180
+ precision="bf16",
181
+ provenance={"parent_model": str(base), "source_metadata": {"adapter": str(adapter)}},
182
+ )
183
+ (partial / CARD_FILE).write_text(vqa.model_dump_json(indent=2) + "\n")
184
+ os.replace(partial, out)
185
+ logger.info("merged {} into {}: {}", adapter, base, out)
186
+ return vqa
187
+
188
+
189
+ @log_call
190
+ def quantise_vlm(source: str | Path, out: Path, cfg: VlmQuantConfig) -> VqaCard:
191
+ """Quantise the bf16 VLM folder at ``source`` (with a VqaCard) into the new folder
192
+ ``out``, written as compressed-tensors safetensors that vLLM loads."""
193
+ llmcompressor = require("llmcompressor", extra("vlm-convert"))
194
+ transformers = require("transformers", extra("vlm-convert"))
195
+ import torch
196
+
197
+ card, folder = load_vlm(source)
198
+ if card.precision != "bf16":
199
+ raise ValueError(f"expected a bf16 VLM, got {card.precision}")
200
+ if out.exists():
201
+ raise FileExistsError(f"{out} exists; choose a new folder")
202
+ model = transformers.AutoModelForImageTextToText.from_pretrained(folder, dtype=torch.bfloat16)
203
+ processor = transformers.AutoProcessor.from_pretrained(folder)
204
+ ignore = ignore_list(model, cfg.extra_ignore)
205
+ logger.info(
206
+ "{}: quantising {} Linear layers of {}, keeping {} in bf16",
207
+ card.name,
208
+ len(ignore.quantised),
209
+ ignore.language_model,
210
+ len(ignore.kept),
211
+ )
212
+ kwargs: dict[str, Any] = {}
213
+ calibration_hash = None
214
+ if SCHEMES[cfg.scheme]["calibrated"]:
215
+ assert cfg.calibration is not None
216
+ rows, calibration_hash = load_pairs(cfg.calibration)
217
+ kwargs = {
218
+ "dataset": _calibration_dataset(rows, processor, cfg.max_seq_len),
219
+ "data_collator": _collate,
220
+ "num_calibration_samples": len(rows),
221
+ "max_seq_length": cfg.max_seq_len,
222
+ "sequential_targets": [_decoder_layer(model, ignore.language_model)],
223
+ }
224
+ mappings = awq_mappings(model, ignore.language_model) if cfg.scheme == "w4a16-awq" else None
225
+ llmcompressor.oneshot(
226
+ model=model,
227
+ processor=processor,
228
+ recipe=recipe_yaml(cfg.scheme, ignore.patterns, mappings),
229
+ **kwargs,
230
+ )
231
+ partial = out.with_name(out.name + ".partial")
232
+ shutil.rmtree(partial, ignore_errors=True)
233
+ model.save_pretrained(partial, save_compressed=True)
234
+ processor.save_pretrained(partial)
235
+ variant = write_card(
236
+ card,
237
+ partial,
238
+ PRECISIONS[cfg.scheme],
239
+ calibration_hash,
240
+ {
241
+ "scheme": cfg.scheme,
242
+ "ignore": ignore.patterns,
243
+ "quantised_layers": len(ignore.quantised),
244
+ },
245
+ )
246
+ os.replace(partial, out)
247
+ logger.info("wrote {} ({} {}, {})", out, variant.name, variant.version, variant.precision)
248
+ return variant
249
+
250
+
251
+ def write_card(
252
+ card: VqaCard,
253
+ folder: Path,
254
+ precision: str,
255
+ calibration_hash: str | None,
256
+ settings: dict[str, Any],
257
+ ) -> VqaCard:
258
+ """Write the quantised variant's card into ``folder``: precision, parent model,
259
+ calibration hash and the recipe settings; parity cleared."""
260
+ data = card.model_dump(mode="json")
261
+ data["precision"] = precision
262
+ data["version"] = f"{card.version}+{settings['scheme']}"
263
+ data["provenance"] = data["provenance"] | {
264
+ "parent_model": f"{card.name}@{card.version}",
265
+ "calibration_set_hash": calibration_hash,
266
+ "parity": None,
267
+ "source_metadata": {**card.provenance.source_metadata, "quantisation": settings},
268
+ }
269
+ variant = VqaCard.model_validate(data)
270
+ (folder / CARD_FILE).write_text(variant.model_dump_json(indent=2) + "\n")
271
+ return variant
272
+
273
+
274
+ def load_pairs(cfg: VqaDataConfig) -> tuple[list[dict[str, Any]], str]:
275
+ """The rows of ``cfg.path`` (a seeded subset of ``cfg.samples``), with ``image``
276
+ resolved to an absolute path, and a hash of exactly which images (by content) and
277
+ questions they are."""
278
+ path = Path(cfg.path)
279
+ if path.suffix == ".jsonl":
280
+ table = pl.read_ndjson(path)
281
+ elif path.suffix == ".csv":
282
+ table = pl.read_csv(path)
283
+ elif path.suffix == ".parquet":
284
+ table = pl.read_parquet(path)
285
+ else:
286
+ raise ValueError(f"{path}: expected .jsonl, .csv or .parquet")
287
+ missing = {"image", "question"} - set(table.columns)
288
+ if missing:
289
+ raise ValueError(f"{path} lacks columns {sorted(missing)}")
290
+ rows = table.to_dicts()
291
+ if cfg.samples is not None and cfg.samples < len(rows):
292
+ rows = random.Random(cfg.seed).sample(rows, cfg.samples)
293
+ digest = hashlib.sha256()
294
+ for row in rows:
295
+ row["image"] = str((path.parent / row["image"]).resolve())
296
+ image_hash = hashlib.sha256(Path(row["image"]).read_bytes()).hexdigest()
297
+ digest.update(json.dumps([image_hash, row["question"]]).encode())
298
+ return rows, digest.hexdigest()[:16]
299
+
300
+
301
+ def read_rgb(path: str | Path) -> NDArray[np.uint8]:
302
+ """An image file as an ``(H, W, 3)`` uint8 RGB array."""
303
+ image = cv2.imread(str(path), cv2.IMREAD_COLOR)
304
+ if image is None:
305
+ raise ValueError(f"cannot read image {path}")
306
+ return np.asarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), dtype=np.uint8)
307
+
308
+
309
+ def _card(fields: Mapping[str, Any], **overrides: Any) -> VqaCard:
310
+ data = {"task": "vqa", **fields, **overrides}
311
+ return VqaCard.model_validate(data)
312
+
313
+
314
+ def _calibration_dataset(rows: list[dict[str, Any]], processor: Any, max_len: int) -> Any:
315
+ datasets = require("datasets", extra("vlm-convert"))
316
+ encoded = []
317
+ for row in rows:
318
+ content = [{"type": "image"}, {"type": "text", "text": row["question"]}]
319
+ messages = [{"role": "user", "content": content}]
320
+ if row.get("answer"):
321
+ messages.append(
322
+ {"role": "assistant", "content": [{"type": "text", "text": str(row["answer"])}]}
323
+ )
324
+ text = processor.apply_chat_template(messages, add_generation_prompt=len(messages) == 1)
325
+ image = read_rgb(row["image"])
326
+ inputs = processor(text=[text], images=[image], max_length=max_len, truncation=False)
327
+ # Kept exactly as the processor returns them (one sample): processors differ in
328
+ # which outputs carry a batch axis (Qwen flattens patches, SmolVLM does not).
329
+ encoded.append({k: _as_list(v) for k, v in inputs.items()})
330
+ return datasets.Dataset.from_list(encoded)
331
+
332
+
333
+ def _as_list(value: Any) -> Any:
334
+ return value.tolist() if hasattr(value, "tolist") else value
335
+
336
+
337
+ def _collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
338
+ import torch
339
+
340
+ assert len(batch) == 1, "VLM calibration runs one sample at a time"
341
+ return {key: torch.tensor(value) for key, value in batch[0].items()}
342
+
343
+
344
+ def _decoder_layer(model: Any, language_model: str) -> str:
345
+ """The class name of the language model's decoder layers, for sequential calibration."""
346
+ module = model.get_submodule(language_model)
347
+ return type(module.layers[0]).__name__
348
+
349
+
350
+ def _has_linear(module: Any) -> bool:
351
+ import torch
352
+
353
+ return any(isinstance(m, torch.nn.Linear) for m in module.modules())
354
+
355
+
356
+ def _matches(pattern: str, name: str) -> bool:
357
+ if pattern.startswith("re:"):
358
+ return re.match(pattern[3:], name) is not None
359
+ return name == pattern or name.endswith("." + pattern)