pathotrain 0.1.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.
- pathotrain/__init__.py +10 -0
- pathotrain/cellseg/README.md +121 -0
- pathotrain/cellseg/__init__.py +12 -0
- pathotrain/cellseg/classify.py +199 -0
- pathotrain/cellseg/configs/classify.example.yaml +53 -0
- pathotrain/cellseg/configs/config.example.yaml +65 -0
- pathotrain/cellseg/configs/instance.example.yaml +71 -0
- pathotrain/cellseg/configs/prompted.example.yaml +42 -0
- pathotrain/cellseg/eval.py +53 -0
- pathotrain/cellseg/export.py +136 -0
- pathotrain/cellseg/instances.py +174 -0
- pathotrain/cellseg/models.py +293 -0
- pathotrain/cellseg/prompted.py +160 -0
- pathotrain/cellseg/task.py +189 -0
- pathotrain/cellseg/train.py +94 -0
- pathotrain/dataloader/README.md +376 -0
- pathotrain/dataloader/__init__.py +43 -0
- pathotrain/dataloader/augmentation.py +467 -0
- pathotrain/dataloader/base.py +126 -0
- pathotrain/dataloader/caption.py +131 -0
- pathotrain/dataloader/classification.py +84 -0
- pathotrain/dataloader/detection.py +235 -0
- pathotrain/dataloader/instance.py +114 -0
- pathotrain/dataloader/pathogen.py +93 -0
- pathotrain/dataloader/registration.py +140 -0
- pathotrain/dataloader/sampling.py +122 -0
- pathotrain/dataloader/segmentation.py +223 -0
- pathotrain/dataloader/unlabelled.py +182 -0
- pathotrain/dataloader/vqa.py +160 -0
- pathotrain/detection/README.md +213 -0
- pathotrain/detection/__init__.py +6 -0
- pathotrain/detection/config.example.yaml +121 -0
- pathotrain/detection/eval.py +75 -0
- pathotrain/detection/export.py +173 -0
- pathotrain/detection/models.py +92 -0
- pathotrain/detection/task.py +175 -0
- pathotrain/detection/train.py +154 -0
- pathotrain/engine/__init__.py +33 -0
- pathotrain/engine/callbacks.py +132 -0
- pathotrain/engine/config.py +41 -0
- pathotrain/engine/logger.py +121 -0
- pathotrain/engine/schedules.py +20 -0
- pathotrain/engine/sweep.py +101 -0
- pathotrain/engine/task.py +54 -0
- pathotrain/engine/trainer.py +345 -0
- pathotrain/experiment.py +553 -0
- pathotrain/histossl/README.md +269 -0
- pathotrain/histossl/__init__.py +25 -0
- pathotrain/histossl/adaptation.py +163 -0
- pathotrain/histossl/backbones.py +147 -0
- pathotrain/histossl/config.py +315 -0
- pathotrain/histossl/configs/dinov2.example.yaml +80 -0
- pathotrain/histossl/configs/dinov2_openmidnight.example.yaml +82 -0
- pathotrain/histossl/configs/lejepa.example.yaml +66 -0
- pathotrain/histossl/configs/teacher_jepa.example.yaml +69 -0
- pathotrain/histossl/eval/__init__.py +6 -0
- pathotrain/histossl/eval/dense_probe.py +198 -0
- pathotrain/histossl/eval/linear_probe.py +239 -0
- pathotrain/histossl/export.py +55 -0
- pathotrain/histossl/masking.py +79 -0
- pathotrain/histossl/methods/__init__.py +8 -0
- pathotrain/histossl/methods/base.py +95 -0
- pathotrain/histossl/methods/dinov2.py +385 -0
- pathotrain/histossl/methods/lejepa.py +158 -0
- pathotrain/histossl/methods/teacher_jepa.py +181 -0
- pathotrain/histossl/train.py +236 -0
- pathotrain/pathoclip/README.md +152 -0
- pathotrain/pathoclip/__init__.py +8 -0
- pathotrain/pathoclip/config.py +153 -0
- pathotrain/pathoclip/configs/midnight-lit.example.yaml +57 -0
- pathotrain/pathoclip/configs/siglip2-base.example.yaml +53 -0
- pathotrain/pathoclip/data.py +52 -0
- pathotrain/pathoclip/eval.py +101 -0
- pathotrain/pathoclip/export.py +58 -0
- pathotrain/pathoclip/models.py +123 -0
- pathotrain/pathoclip/task.py +124 -0
- pathotrain/pathoclip/train.py +242 -0
- pathotrain/pathoclip/zero_shot.py +95 -0
- pathotrain/pathocls/README.md +119 -0
- pathotrain/pathocls/__init__.py +8 -0
- pathotrain/pathocls/backbones.py +82 -0
- pathotrain/pathocls/config.example.yaml +64 -0
- pathotrain/pathocls/eval.py +67 -0
- pathotrain/pathocls/export.py +101 -0
- pathotrain/pathocls/model.py +49 -0
- pathotrain/pathocls/task.py +102 -0
- pathotrain/pathocls/train.py +222 -0
- pathotrain/pathofm/README.md +281 -0
- pathotrain/pathofm/__init__.py +25 -0
- pathotrain/pathofm/models.py +200 -0
- pathotrain/pathofm/sam3.py +125 -0
- pathotrain/pathogen/README.md +235 -0
- pathotrain/pathogen/__init__.py +19 -0
- pathotrain/pathogen/cache.py +246 -0
- pathotrain/pathogen/config.example.yaml +91 -0
- pathotrain/pathogen/diffusion.py +273 -0
- pathotrain/pathogen/eval.py +82 -0
- pathotrain/pathogen/export.py +117 -0
- pathotrain/pathogen/flow.py +284 -0
- pathotrain/pathogen/train.py +166 -0
- pathotrain/pathogen/translate.py +65 -0
- pathotrain/pathosam/README.md +216 -0
- pathotrain/pathosam/__init__.py +5 -0
- pathotrain/pathosam/configs/concept.example.yaml +79 -0
- pathotrain/pathosam/configs/interactive.example.yaml +63 -0
- pathotrain/pathosam/configs/zeroshot.example.yaml +78 -0
- pathotrain/pathosam/eval.py +480 -0
- pathotrain/pathosam/export.py +540 -0
- pathotrain/pathosam/model.py +128 -0
- pathotrain/pathosam/prompts.py +55 -0
- pathotrain/pathosam/task.py +388 -0
- pathotrain/pathosam/train.py +93 -0
- pathotrain/pathovlm/README.md +543 -0
- pathotrain/pathovlm/__init__.py +6 -0
- pathotrain/pathovlm/callbacks.py +73 -0
- pathotrain/pathovlm/collate.py +100 -0
- pathotrain/pathovlm/config.py +213 -0
- pathotrain/pathovlm/configs/qwen3-vl-2b.example.yaml +52 -0
- pathotrain/pathovlm/configs/qwen3-vl-4b.example.yaml +52 -0
- pathotrain/pathovlm/eval.py +140 -0
- pathotrain/pathovlm/export.py +145 -0
- pathotrain/pathovlm/metrics.py +67 -0
- pathotrain/pathovlm/models.py +77 -0
- pathotrain/pathovlm/sample.py +80 -0
- pathotrain/pathovlm/stages.py +267 -0
- pathotrain/pathovlm/train.py +299 -0
- pathotrain/py.typed +0 -0
- pathotrain/registration/README.md +115 -0
- pathotrain/registration/__init__.py +6 -0
- pathotrain/registration/affine.py +287 -0
- pathotrain/registration/batch.py +147 -0
- pathotrain/segmentation/README.md +421 -0
- pathotrain/segmentation/__init__.py +15 -0
- pathotrain/segmentation/config.example.yaml +134 -0
- pathotrain/segmentation/encoders.py +183 -0
- pathotrain/segmentation/eval.py +73 -0
- pathotrain/segmentation/export.py +116 -0
- pathotrain/segmentation/losses.py +84 -0
- pathotrain/segmentation/models.py +97 -0
- pathotrain/segmentation/task.py +172 -0
- pathotrain/segmentation/train.py +152 -0
- pathotrain-0.1.0.dist-info/METADATA +290 -0
- pathotrain-0.1.0.dist-info/RECORD +145 -0
- pathotrain-0.1.0.dist-info/WHEEL +4 -0
- pathotrain-0.1.0.dist-info/licenses/LICENSE +202 -0
pathotrain/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from patchology.log import configure_logging
|
|
4
|
+
|
|
5
|
+
# Every MLflow run in a process that imports pathotrain records system metrics (CPU, RAM,
|
|
6
|
+
# GPU, disk, network); MLflow's own default is off. Export the variable as 0 to turn it off.
|
|
7
|
+
os.environ.setdefault("MLFLOW_ENABLE_SYSTEM_METRICS_LOGGING", "1")
|
|
8
|
+
|
|
9
|
+
# INFO by default; export PATHOTRAIN_LOG_LEVEL=DEBUG (or ALL) for more, see patchology.log.
|
|
10
|
+
configure_logging("pathotrain")
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# pathotrain - cellseg
|
|
2
|
+
|
|
3
|
+
Cell (nucleus) segmentation, written from the papers. The authors' code and trained
|
|
4
|
+
weights are not used. Only encoder weights are loaded: timm ImageNet weights, or a
|
|
5
|
+
`pathofm` foundation model.
|
|
6
|
+
|
|
7
|
+
Three ways to train, and one to use SAM 3 without training:
|
|
8
|
+
|
|
9
|
+
| What | Command | Config |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| Semantic: a nucleus type per pixel | `python -m pathotrain.segmentation.train` | `configs/config.example.yaml` |
|
|
12
|
+
| Instance: each nucleus and its type (HoVer-Net style) | `python -m pathotrain.cellseg.train` (`.eval`, `.export`) | `configs/instance.example.yaml` |
|
|
13
|
+
| CellViT++ cell classifier on frozen foundation-model tokens | `python -m pathotrain.cellseg.classify` | `configs/classify.example.yaml` |
|
|
14
|
+
| Zero-shot SAM 3 from text prompts, scored with the same PQ | `python -m pathotrain.cellseg.prompted` | `configs/prompted.example.yaml` |
|
|
15
|
+
|
|
16
|
+
## Models
|
|
17
|
+
|
|
18
|
+
| `model.name` | Paper | Encoder | Decoder |
|
|
19
|
+
|---|---|---|---|
|
|
20
|
+
| `cellseg:hovernet` | HoVer-Net, Graham et al. 2019 | pre-activation ResNet-50 (timm `resnetv2_50`), stride-1 stem | HoVer-Net dense decoder ("fast" mode, padded convs), one per branch |
|
|
21
|
+
| `cellseg:hovernext` | HoVer-NeXt, Baumann et al. 2024 | ConvNeXt (timm, `encoder`; ConvNeXt-V2 in the paper) | U-Net (SMP), shared by the branches |
|
|
22
|
+
| `cellseg:cellvit` | CellViT, Hörst et al. 2024 | `pathofm` ViT (`backbone`), four layers | CellViT transposed-conv decoder, one per branch |
|
|
23
|
+
|
|
24
|
+
A semantic model outputs the nuclear-type (NT) logits, `(B, num_classes, H, W)`. An
|
|
25
|
+
instance model (`instance=True`, which `cellseg.train` sets) returns HoVer-Net's three
|
|
26
|
+
branches as a dict: `np` (nucleus vs background, 2 logits), `hv` (horizontal and
|
|
27
|
+
vertical offsets from the nucleus centre, in [-1, 1]) and `nt`.
|
|
28
|
+
|
|
29
|
+
Options per model:
|
|
30
|
+
|
|
31
|
+
- **hovernet:** `encoder_weights: imagenet` (timm, Apache-2.0) or `null`. Input
|
|
32
|
+
sides must be divisible by 8.
|
|
33
|
+
- **hovernext:** `encoder` (default `convnext_base`), `encoder_weights` (default
|
|
34
|
+
`imagenet`: timm's `fb_in22k_ft_in1k` weights, Apache-2.0; `null` from scratch). The
|
|
35
|
+
paper's ConvNeXt-V2 (`encoder: convnextv2_base`) has ImageNet weights under
|
|
36
|
+
CC-BY-NC-4.0 only. Other keys go to `smp.Unet`.
|
|
37
|
+
- **cellvit:** `backbone` (`midnight-12k`, `sam3`, ...; both normalise with
|
|
38
|
+
`MIDNIGHT_MEAN` / `MIDNIGHT_STD`), `layers` (four 1-based layers, default evenly
|
|
39
|
+
spaced), `freeze` (default `true`), `adaptation` (e.g. `{type: lora, rank: 8}` to
|
|
40
|
+
fine-tune the backbone with LoRA, needs peft; overrides `freeze`), `skip_dims`,
|
|
41
|
+
`bottleneck_dim`. Input sides must be divisible by 16. `sam3` is gated and under the
|
|
42
|
+
SAM License (see the pathofm README).
|
|
43
|
+
|
|
44
|
+
## Instance segmentation
|
|
45
|
+
|
|
46
|
+
`cellseg.train` uses HoVer-Net's loss: cross-entropy plus Dice on NP and NT, MSE and
|
|
47
|
+
gradient MSE on HV (`task.loss_weights`). Validation turns each tile's outputs into
|
|
48
|
+
nuclei with HoVer-Net's watershed (`cellseg.instances.postprocess`, options in
|
|
49
|
+
`task.postprocess`) and logs:
|
|
50
|
+
|
|
51
|
+
- `val/bpq`: binary PQ, the mean over tiles (PanNuke's convention).
|
|
52
|
+
- `val/mpq`: multi-class PQ+, each type's PQ over the whole set, averaged over types (CoNIC's).
|
|
53
|
+
- `val/pq_<type>`, and the binary `val/dq` (detection) and `val/sq` (segmentation quality).
|
|
54
|
+
|
|
55
|
+
`best.ckpt` is chosen on `val/mpq`. `python -m pathotrain.cellseg.eval best.ckpt` scores
|
|
56
|
+
the test split.
|
|
57
|
+
|
|
58
|
+
### ONNX export
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
python -m pathotrain.cellseg.export best.ckpt out/model.onnx --size 256 --mpp 0.25 --no-icc
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The graph returns the three branches before any activation: `np`, `hv` and `nt`. The
|
|
65
|
+
watershed runs outside the graph. On one tile's outputs,
|
|
66
|
+
`cellseg.instances.instances_from_outputs(np[i], hv[i], nt[i])` returns the instance map
|
|
67
|
+
and each instance's type, the same code validation uses.
|
|
68
|
+
|
|
69
|
+
`model_card.json` is written beside the graph and embedded in it. It is an instance card
|
|
70
|
+
(`task: instance`, outputs `np`, `hv`, `nt`): pathoinfer runs the same watershed per tile
|
|
71
|
+
and writes typed nucleus polygons as GeoJSON and Parquet. Classes need
|
|
72
|
+
names (`task.class_names`). Tile folders record no resolution, so `--mpp`,
|
|
73
|
+
`--icc`/`--no-icc` and `--size` are required. A ViT-g CellViT writes its 4.8 GB of
|
|
74
|
+
weights to `model.onnx.data`, which must stay beside the graph.
|
|
75
|
+
|
|
76
|
+
## CellViT++ cell classifier
|
|
77
|
+
|
|
78
|
+
`cellseg.classify` follows CellViT++ (Hörst et al. 2025). New cell classes need only a
|
|
79
|
+
small head on a frozen CellViT, not a new segmentation model:
|
|
80
|
+
|
|
81
|
+
1. A `cellseg:cellvit` instance model trained with `cellseg.train` (`model.checkpoint`,
|
|
82
|
+
frozen) detects each tile's cells. The same forward pass gives its encoder's deepest
|
|
83
|
+
tokens.
|
|
84
|
+
2. A cell's embedding is the mean of the tokens of the 16 px patches its bounding box
|
|
85
|
+
touches.
|
|
86
|
+
3. Detected cells are paired one to one with ground-truth cells by centroid distance
|
|
87
|
+
(Hungarian, within `match_radius`, 15 px), and take the paired cell's type.
|
|
88
|
+
4. The embeddings are computed once, without augmentation, and a head trains on them:
|
|
89
|
+
pathocls's `Head` (an MLP of width `head.hidden`, 100 as CellViT++), with pathocls's
|
|
90
|
+
metrics (`val/balanced_acc`, `val/macro_f1`, `val/recall_<class>`, ...).
|
|
91
|
+
|
|
92
|
+
The training log records how many cells were detected, how many are in the ground truth
|
|
93
|
+
and how many were paired. At inference,
|
|
94
|
+
`classify_cells(detector, head, image)` detects and classifies the cells in one pass, with
|
|
95
|
+
`load_detector(cfg["model"]["checkpoint"])` and `load_head(best.ckpt)`. Two differences
|
|
96
|
+
from CellViT++: the head standardises its inputs and uses GELU where CellViT++ uses ReLU.
|
|
97
|
+
|
|
98
|
+
## Zero-shot SAM 3 (text prompts)
|
|
99
|
+
|
|
100
|
+
`cellseg.prompted` scores SAM 3 (`facebook/sam3`, gated, SAM License) without training. It
|
|
101
|
+
finds every instance of a text concept in a tile. With one prompt per nucleus type
|
|
102
|
+
(`prompts: {1: inflammatory cell, ...}`), each detection takes its prompt's type; with a
|
|
103
|
+
single prompt (`prompts: cell`), nuclei are untyped. Overlaps go to the higher score.
|
|
104
|
+
Every threshold in `thresholds` is scored in one pass: choose one on `val` and report it
|
|
105
|
+
on `test`. Metrics match `cellseg.eval`'s, keyed `<split>/<metric>@<threshold>`.
|
|
106
|
+
|
|
107
|
+
The wording of a prompt matters. On PanNuke, SAM 3 finds nuclei from "cell" but almost
|
|
108
|
+
none from "nucleus", and "neoplastic cell" works far better than "tumor cell".
|
|
109
|
+
|
|
110
|
+
## Data
|
|
111
|
+
|
|
112
|
+
- **Semantic** (`segmentation.train`): `images` and `masks` folders, as in
|
|
113
|
+
`segmentation`. `image_prefix` / `mask_prefix` are removed before pairing, so
|
|
114
|
+
PanNuke's `img_X.png` pairs with `sem_X.png`.
|
|
115
|
+
- **Instance, classifier and prompted** (`InstanceTileFolderDataset` from
|
|
116
|
+
`pathotrain.dataloader`): `images`, `instances` and `types` folders, each with an
|
|
117
|
+
optional prefix. Instance masks hold one id per nucleus. With `contours: true`, they
|
|
118
|
+
hold nucleus outlines instead, as in the PanNuke conversion at `pannuke_split`, and the
|
|
119
|
+
ids are derived (see the dataloader README). Type masks hold the class per pixel
|
|
120
|
+
(0 background, 255 ignored). `cellseg.train` adds HoVer-Net's HV maps to each target
|
|
121
|
+
with `cellseg.instances.add_hv_maps`, in the loader workers after augmentation.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from pathotrain.cellseg.models import BRANCHES, CellViT, HoVerNet, build_model, hovernext
|
|
2
|
+
from pathotrain.cellseg.task import CellInstanceTask, PanopticQuality
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
"BRANCHES",
|
|
6
|
+
"CellInstanceTask",
|
|
7
|
+
"CellViT",
|
|
8
|
+
"HoVerNet",
|
|
9
|
+
"PanopticQuality",
|
|
10
|
+
"build_model",
|
|
11
|
+
"hovernext",
|
|
12
|
+
]
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""CellViT++'s cell classifier: a small head on the tokens of the cells a frozen CellViT
|
|
2
|
+
detects, so new cell classes need no new segmentation model::
|
|
3
|
+
|
|
4
|
+
python -m pathotrain.cellseg.classify classify.yaml
|
|
5
|
+
|
|
6
|
+
Start from ``configs/classify.example.yaml`` beside this module. As CellViT++ (Hörst et al. 2025):
|
|
7
|
+
|
|
8
|
+
1. A trained ``cellseg:cellvit`` instance model (``model.checkpoint``, written by
|
|
9
|
+
:mod:`pathotrain.cellseg.train`) detects each tile's cells, and the same forward pass
|
|
10
|
+
gives its encoder's deepest tokens.
|
|
11
|
+
2. A cell's embedding is the mean of the tokens of the 16 px patches its bounding box
|
|
12
|
+
touches.
|
|
13
|
+
3. Detected cells are paired one to one with ground-truth cells by centroid distance
|
|
14
|
+
(Hungarian, within ``match_radius`` px, 15 as in CellViT++) and take the paired cell's
|
|
15
|
+
type. Unpaired detections, and ground-truth cells no detection reaches, are left out.
|
|
16
|
+
4. The embeddings are computed once, without augmentation, and a head trains on them.
|
|
17
|
+
|
|
18
|
+
Classes are the types of ``data``'s type masks without background: type ``t`` is class
|
|
19
|
+
``t - 1``. They need not be the detector's types. Normalisation is the detector's, read
|
|
20
|
+
from its checkpoint. At inference, :func:`classify_cells` detects and types cells in one pass.
|
|
21
|
+
|
|
22
|
+
Sections as in ``pathotrain.pathocls.train`` (``task``, ``trainer``, ``checkpoint``,
|
|
23
|
+
``loader``, ...), except::
|
|
24
|
+
|
|
25
|
+
model: {checkpoint: path, num_classes: 5, head?: {hidden: 100, dropout: 0.0}}
|
|
26
|
+
match_radius?: 15 # px
|
|
27
|
+
features?: {batch_size: 16, num_workers: 0} # tiles per batch while embedding
|
|
28
|
+
data: {train: {...}, val?: {...}} # InstanceTileFolderDataset (images, instances, types, ...)
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
import argparse
|
|
32
|
+
import math
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
import numpy as np
|
|
36
|
+
import torch
|
|
37
|
+
from loguru import logger
|
|
38
|
+
from scipy import ndimage as ndi
|
|
39
|
+
from torch import Tensor, nn
|
|
40
|
+
from torch.utils.data import DataLoader, TensorDataset
|
|
41
|
+
|
|
42
|
+
from pathotrain import experiment
|
|
43
|
+
from pathotrain.cellseg import train as cell_train
|
|
44
|
+
from pathotrain.cellseg.instances import (
|
|
45
|
+
centroids,
|
|
46
|
+
instance_types,
|
|
47
|
+
instances_from_outputs,
|
|
48
|
+
pair_centroids,
|
|
49
|
+
)
|
|
50
|
+
from pathotrain.cellseg.models import CellViT
|
|
51
|
+
from pathotrain.dataloader import InstanceTileFolderDataset
|
|
52
|
+
from pathotrain.dataloader.augmentation import eval_transform
|
|
53
|
+
from pathotrain.engine import load_config
|
|
54
|
+
from pathotrain.pathocls.model import Head
|
|
55
|
+
from pathotrain.pathocls.task import ClassificationTask
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def cell_tokens(tokens: Tensor, instances: np.ndarray) -> tuple[np.ndarray, Tensor]:
|
|
59
|
+
"""The instance ids of ``instances`` ``(H, W)`` and their ``(N, D)`` embeddings: the
|
|
60
|
+
mean of ``tokens`` ``(D, H/16, W/16)`` over the 16 px patches each bounding box touches."""
|
|
61
|
+
ids, out = [], []
|
|
62
|
+
h, w = tokens.shape[-2:]
|
|
63
|
+
for i, box in enumerate(ndi.find_objects(instances), start=1):
|
|
64
|
+
if box is None:
|
|
65
|
+
continue
|
|
66
|
+
ys, xs = box
|
|
67
|
+
y0, x0 = ys.start // 16, xs.start // 16
|
|
68
|
+
y1, x1 = min(math.ceil(ys.stop / 16), h), min(math.ceil(xs.stop / 16), w)
|
|
69
|
+
if y0 >= y1 or x0 >= x1: # wholly beyond the last full patch
|
|
70
|
+
continue
|
|
71
|
+
ids.append(i)
|
|
72
|
+
out.append(tokens[:, y0:y1, x0:x1].float().mean((1, 2)))
|
|
73
|
+
if not out:
|
|
74
|
+
return np.zeros(0, np.int64), tokens.new_zeros(0, tokens.shape[0])
|
|
75
|
+
return np.array(ids), torch.stack(out)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def detect_cells(
|
|
79
|
+
model: CellViT, image: Tensor, postprocess: dict | None = None
|
|
80
|
+
) -> list[tuple[np.ndarray, np.ndarray, Tensor]]:
|
|
81
|
+
"""Per image of the batch: the detected instance map, its ids and their ``(N, D)``
|
|
82
|
+
embeddings, from one forward pass of the instance ``model``."""
|
|
83
|
+
with torch.no_grad():
|
|
84
|
+
out, tokens = model(image, return_tokens=True)
|
|
85
|
+
outputs = [out[k].float().cpu().numpy() for k in ("np", "hv", "nt")]
|
|
86
|
+
cells = []
|
|
87
|
+
for i in range(len(image)):
|
|
88
|
+
inst, _ = instances_from_outputs(*(o[i] for o in outputs), **(postprocess or {}))
|
|
89
|
+
cells.append((inst, *cell_tokens(tokens[i], inst)))
|
|
90
|
+
return cells
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@torch.no_grad()
|
|
94
|
+
def classify_cells(
|
|
95
|
+
model: CellViT, head: nn.Module, image: Tensor, postprocess: dict | None = None
|
|
96
|
+
) -> list[tuple[np.ndarray, np.ndarray]]:
|
|
97
|
+
"""CellViT++ inference: per image, the detected instance map and the class of each
|
|
98
|
+
instance id (indexed by id; 0 for ids without one, as for ``instance_types``)."""
|
|
99
|
+
results = []
|
|
100
|
+
for inst, ids, emb in detect_cells(model, image, postprocess):
|
|
101
|
+
types = np.zeros(int(inst.max()) + 1, np.int64)
|
|
102
|
+
if len(ids):
|
|
103
|
+
types[ids] = head(emb.to(next(head.parameters()).device)).argmax(1).cpu().numpy()
|
|
104
|
+
results.append((inst, types))
|
|
105
|
+
return results
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def embed_cells(cfg: dict, model: CellViT, postprocess: dict, split: str) -> TensorDataset:
|
|
109
|
+
"""``(embedding, class)`` of every detected cell of ``data[split]`` paired with a
|
|
110
|
+
ground-truth cell of a known type, on CPU."""
|
|
111
|
+
norm = {"mean": cfg["mean"], "std": cfg["std"]}
|
|
112
|
+
dataset = InstanceTileFolderDataset(transform=eval_transform(**norm), **cfg["data"][split])
|
|
113
|
+
features = {"batch_size": 16, "num_workers": 0, **cfg.get("features", {})}
|
|
114
|
+
loader = DataLoader(dataset, **features)
|
|
115
|
+
num_types = cfg["model"]["num_classes"] + 1 # with background
|
|
116
|
+
radius = cfg.get("match_radius", 15)
|
|
117
|
+
device = next(model.parameters()).device
|
|
118
|
+
xs, ys, counts = [], [], np.zeros(3, np.int64) # detected, ground truth, paired
|
|
119
|
+
for image, target in loader:
|
|
120
|
+
cells = detect_cells(model, image.to(device), postprocess)
|
|
121
|
+
for (pred, ids, emb), true, types in zip(
|
|
122
|
+
cells, target["inst"], target["type"], strict=True
|
|
123
|
+
):
|
|
124
|
+
true = true.numpy()
|
|
125
|
+
true_ids, true_xy = centroids(true)
|
|
126
|
+
true_types = instance_types(true, types.numpy(), num_types)[true_ids]
|
|
127
|
+
_, pred_xy = centroids(pred, ids) # in the order of emb
|
|
128
|
+
pairs = pair_centroids(true_xy, pred_xy, radius)
|
|
129
|
+
pairs = pairs[true_types[pairs[:, 0]] > 0] # paired with a typed cell
|
|
130
|
+
counts += (len(ids), len(true_ids), len(pairs))
|
|
131
|
+
xs.append(emb[torch.from_numpy(pairs[:, 1])].cpu())
|
|
132
|
+
ys.append(torch.from_numpy(true_types[pairs[:, 0]] - 1))
|
|
133
|
+
logger.info("{}: {} cells detected, {} in the ground truth, {} paired", split, *counts)
|
|
134
|
+
if not counts[2]:
|
|
135
|
+
raise ValueError(f"no detected cell of {split} is within {radius} px of a typed cell")
|
|
136
|
+
return TensorDataset(torch.cat(xs), torch.cat(ys))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def build_head(cfg: dict) -> Head:
|
|
140
|
+
model = cfg["model"]
|
|
141
|
+
return Head(model["embedding_dim"], model["num_classes"], **model.get("head", {}))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def load_detector(path: str | Path, device: str = "cpu") -> tuple[CellViT, dict]:
|
|
145
|
+
"""The frozen CellViT instance model of a :mod:`pathotrain.cellseg.train` checkpoint,
|
|
146
|
+
in eval mode on ``device``, and its config."""
|
|
147
|
+
task, cfg = cell_train.load_task(path)
|
|
148
|
+
if cfg["model"]["name"].removeprefix("cellseg:") != "cellvit":
|
|
149
|
+
raise ValueError(f"{path} is a {cfg['model']['name']} model; CellViT++ needs cellvit")
|
|
150
|
+
return task.model.eval().requires_grad_(False).to(device), cfg
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def train(cfg: dict, resume: str | Path | None = None) -> dict[str, float]:
|
|
154
|
+
"""Detect and embed the cells, train the head, and return the last validation metrics."""
|
|
155
|
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
156
|
+
model, detector = load_detector(cfg["model"]["checkpoint"], device)
|
|
157
|
+
# The run's config records the detector's normalisation and the embedding width.
|
|
158
|
+
cfg = cfg | {
|
|
159
|
+
"mean": experiment.normalisation(detector, "mean"),
|
|
160
|
+
"std": experiment.normalisation(detector, "std"),
|
|
161
|
+
"model": cfg["model"] | {"embedding_dim": model.backbone.config.hidden_size},
|
|
162
|
+
}
|
|
163
|
+
config_path = experiment.start(cfg, resume)
|
|
164
|
+
postprocess = detector.get("task", {}).get("postprocess", {})
|
|
165
|
+
train_set = embed_cells(cfg, model, postprocess, "train")
|
|
166
|
+
val_set = embed_cells(cfg, model, postprocess, "val") if "val" in cfg["data"] else None
|
|
167
|
+
del model # the head trains on the embeddings alone
|
|
168
|
+
torch.cuda.empty_cache()
|
|
169
|
+
head = build_head(cfg)
|
|
170
|
+
x = train_set.tensors[0]
|
|
171
|
+
head.mean.copy_(x.mean(0))
|
|
172
|
+
head.std.copy_(x.std(0).clamp_min(1e-6))
|
|
173
|
+
task = ClassificationTask(head, cfg["model"]["num_classes"], **cfg.get("task", {}))
|
|
174
|
+
return experiment.fit(
|
|
175
|
+
cfg, task, train_set, val_set, config_path, resume, monitor="val/balanced_acc"
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def load_head(path: str | Path, map_location: str = "cpu") -> tuple[Head, dict]:
|
|
180
|
+
"""The head of a checkpoint written by :func:`train`, and its config (whose
|
|
181
|
+
``model.checkpoint`` is the detector to run it with, see :func:`load_detector`)."""
|
|
182
|
+
ckpt = torch.load(path, map_location=map_location, weights_only=True)
|
|
183
|
+
if "config" not in ckpt:
|
|
184
|
+
raise ValueError(f"{path} has no config; it was not written by pathotrain's train")
|
|
185
|
+
head = build_head(ckpt["config"])
|
|
186
|
+
head.load_state_dict(ckpt["model"])
|
|
187
|
+
return head.eval(), ckpt["config"]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def main(argv: list[str] | None = None) -> None:
|
|
191
|
+
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
192
|
+
parser.add_argument("config", help="experiment YAML")
|
|
193
|
+
parser.add_argument("--resume", help="last.ckpt to continue from")
|
|
194
|
+
args = parser.parse_args(argv)
|
|
195
|
+
train(load_config(args.config), args.resume)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
if __name__ == "__main__":
|
|
199
|
+
main()
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# CellViT++ cell classifier: a head on the tokens of the cells a frozen CellViT detects.
|
|
2
|
+
# python -m pathotrain.cellseg.classify classify.yaml
|
|
3
|
+
# Detected cells are paired with ground-truth cells by centroid distance and take their
|
|
4
|
+
# type; the head is scored on data.val's paired cells (val/balanced_acc, val/macro_f1,
|
|
5
|
+
# val/recall_<class>, ...). Copy this file and set the paths.
|
|
6
|
+
|
|
7
|
+
name: cellseg-classify
|
|
8
|
+
seed: 0
|
|
9
|
+
output_dir: runs/cellseg-classify
|
|
10
|
+
# mean/std are the detector's, from its checkpoint.
|
|
11
|
+
|
|
12
|
+
model:
|
|
13
|
+
# A cellseg:cellvit instance model trained with pathotrain.cellseg.train (frozen).
|
|
14
|
+
checkpoint: runs/cellseg-cellvit/checkpoints/best.ckpt
|
|
15
|
+
num_classes: 5 # cell types without background (type t is class t - 1); the
|
|
16
|
+
# types of data's masks, which need not be the detector's
|
|
17
|
+
head: {hidden: 100, dropout: 0.0} # CellViT++'s MLP width; hidden: null for linear
|
|
18
|
+
|
|
19
|
+
match_radius: 15 # px between a detection's and a ground-truth cell's centroid
|
|
20
|
+
|
|
21
|
+
task:
|
|
22
|
+
lr: 1.0e-3
|
|
23
|
+
class_names: [inflammatory, connective, necrosis, epithelial, neoplastic] # labels 1..5 of
|
|
24
|
+
# the pannuke_split conversion (neoplastic is label 5); other conversions may differ
|
|
25
|
+
|
|
26
|
+
trainer:
|
|
27
|
+
max_epochs: 50
|
|
28
|
+
|
|
29
|
+
features: # embedding the cells, once
|
|
30
|
+
batch_size: 16 # tiles per batch
|
|
31
|
+
num_workers: 8
|
|
32
|
+
|
|
33
|
+
loader: # training the head on the embeddings
|
|
34
|
+
batch_size: 512
|
|
35
|
+
num_workers: 0 # embeddings are in memory
|
|
36
|
+
|
|
37
|
+
data:
|
|
38
|
+
train:
|
|
39
|
+
images: /path/to/pannuke_split/train/images
|
|
40
|
+
instances: /path/to/pannuke_split/train/inst_masks
|
|
41
|
+
types: /path/to/pannuke_split/train/sem_masks
|
|
42
|
+
image_prefix: img_
|
|
43
|
+
instance_prefix: inst_
|
|
44
|
+
type_prefix: sem_
|
|
45
|
+
contours: true
|
|
46
|
+
val:
|
|
47
|
+
images: /path/to/pannuke_split/val/images
|
|
48
|
+
instances: /path/to/pannuke_split/val/inst_masks
|
|
49
|
+
types: /path/to/pannuke_split/val/sem_masks
|
|
50
|
+
image_prefix: img_
|
|
51
|
+
instance_prefix: inst_
|
|
52
|
+
type_prefix: sem_
|
|
53
|
+
contours: true
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Semantic cell segmentation on PanNuke-style tile folders:
|
|
2
|
+
# python -m pathotrain.segmentation.train config.yaml
|
|
3
|
+
# Same sections and defaults as segmentation/config.example.yaml; this file sets only
|
|
4
|
+
# what differs for cells. Copy it and set the paths under `data`.
|
|
5
|
+
|
|
6
|
+
name: cellseg-hovernet
|
|
7
|
+
seed: 0
|
|
8
|
+
output_dir: runs/cellseg-hovernet
|
|
9
|
+
mean: IMAGENET_MEAN # MIDNIGHT_MEAN / MIDNIGHT_STD for cellvit on midnight-12k
|
|
10
|
+
std: IMAGENET_STD
|
|
11
|
+
|
|
12
|
+
model:
|
|
13
|
+
name: cellseg:hovernet # or cellseg:hovernext, cellseg:cellvit
|
|
14
|
+
num_classes: 6 # background + 5 PanNuke nucleus types
|
|
15
|
+
encoder_weights: imagenet # hovernet: timm ResNetV2-50 (Apache-2.0); null from scratch
|
|
16
|
+
# cellseg:hovernext: encoder: convnext_base, encoder_weights: imagenet (Apache-2.0);
|
|
17
|
+
# the paper's convnextv2_base has CC-BY-NC-4.0 ImageNet weights only
|
|
18
|
+
# cellseg:cellvit: backbone: midnight-12k (or sam3), freeze: true, layers: [10, 20, 30, 40]
|
|
19
|
+
# adaptation: {type: lora, rank: 8} # LoRA fine-tuning instead of freeze (needs peft)
|
|
20
|
+
|
|
21
|
+
loss:
|
|
22
|
+
name: CEDiceLoss
|
|
23
|
+
dice_weight: 1.0
|
|
24
|
+
|
|
25
|
+
task:
|
|
26
|
+
lr: 1.0e-3
|
|
27
|
+
warmup_epochs: 1
|
|
28
|
+
# Label order of the pannuke_split conversion: PanNuke's neoplastic channel (0) is label 5,
|
|
29
|
+
# the other types keep their channel number. Other conversions may differ; check counts.
|
|
30
|
+
class_names: [background, inflammatory, connective, necrosis, epithelial, neoplastic]
|
|
31
|
+
|
|
32
|
+
trainer:
|
|
33
|
+
max_epochs: 50
|
|
34
|
+
precision: bf16-mixed
|
|
35
|
+
|
|
36
|
+
checkpoint:
|
|
37
|
+
monitor: val/miou_fg # nuclei only; background dominates val/miou
|
|
38
|
+
mode: max
|
|
39
|
+
|
|
40
|
+
augmentation:
|
|
41
|
+
n: 3
|
|
42
|
+
m: 5
|
|
43
|
+
|
|
44
|
+
loader:
|
|
45
|
+
batch_size: 16
|
|
46
|
+
num_workers: 8
|
|
47
|
+
|
|
48
|
+
# PanNuke tiles: 256 px at 40x (~0.25 um/px). Images and masks are paired by name once
|
|
49
|
+
# the prefixes are removed (img_X.png with sem_X.png).
|
|
50
|
+
data:
|
|
51
|
+
train:
|
|
52
|
+
images: /path/to/pannuke_split/train/images
|
|
53
|
+
masks: /path/to/pannuke_split/train/sem_masks
|
|
54
|
+
image_prefix: img_
|
|
55
|
+
mask_prefix: sem_
|
|
56
|
+
val:
|
|
57
|
+
images: /path/to/pannuke_split/val/images
|
|
58
|
+
masks: /path/to/pannuke_split/val/sem_masks
|
|
59
|
+
image_prefix: img_
|
|
60
|
+
mask_prefix: sem_
|
|
61
|
+
test:
|
|
62
|
+
images: /path/to/pannuke_split/test/images
|
|
63
|
+
masks: /path/to/pannuke_split/test/sem_masks
|
|
64
|
+
image_prefix: img_
|
|
65
|
+
mask_prefix: sem_
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# Nucleus instance segmentation and typing (HoVer-Net style) on PanNuke-style folders:
|
|
2
|
+
# python -m pathotrain.cellseg.train instance.yaml
|
|
3
|
+
# python -m pathotrain.cellseg.eval runs/cellseg-instance/checkpoints/best.ckpt
|
|
4
|
+
# python -m pathotrain.cellseg.export runs/cellseg-instance/checkpoints/best.ckpt out/model.onnx \
|
|
5
|
+
# --size 256 --mpp 0.25 --no-icc # needs task.class_names
|
|
6
|
+
# Sections not shown (early_stopping, val_loader, mlflow_db, ...) are as in
|
|
7
|
+
# segmentation/config.example.yaml. Copy this file and set the paths under `data`.
|
|
8
|
+
|
|
9
|
+
name: cellseg-instance
|
|
10
|
+
seed: 0
|
|
11
|
+
output_dir: runs/cellseg-instance
|
|
12
|
+
mean: IMAGENET_MEAN # MIDNIGHT_MEAN / MIDNIGHT_STD for cellvit on midnight-12k
|
|
13
|
+
std: IMAGENET_STD
|
|
14
|
+
|
|
15
|
+
model:
|
|
16
|
+
name: cellseg:hovernet # or cellseg:hovernext, cellseg:cellvit (options as in config.example.yaml)
|
|
17
|
+
num_classes: 6 # background + 5 PanNuke nucleus types
|
|
18
|
+
encoder_weights: imagenet
|
|
19
|
+
|
|
20
|
+
task:
|
|
21
|
+
lr: 1.0e-3
|
|
22
|
+
warmup_epochs: 1
|
|
23
|
+
# Label order of the pannuke_split conversion: PanNuke's neoplastic channel (0) is label 5,
|
|
24
|
+
# the other types keep their channel number. Other conversions may differ; check counts.
|
|
25
|
+
class_names: [background, inflammatory, connective, necrosis, epithelial, neoplastic] # val/pq_<name>
|
|
26
|
+
# loss_weights: {np: 1.0, hv_mse: 1.0, hv_msge: 1.0, nt: 1.0} # HoVer-Net's
|
|
27
|
+
# postprocess: {threshold: 0.5, marker_threshold: 0.4, min_size: 10}
|
|
28
|
+
|
|
29
|
+
trainer:
|
|
30
|
+
max_epochs: 50
|
|
31
|
+
precision: bf16-mixed
|
|
32
|
+
|
|
33
|
+
checkpoint:
|
|
34
|
+
monitor: val/mpq # or val/bpq
|
|
35
|
+
mode: max
|
|
36
|
+
|
|
37
|
+
augmentation:
|
|
38
|
+
n: 3
|
|
39
|
+
m: 5
|
|
40
|
+
|
|
41
|
+
loader:
|
|
42
|
+
batch_size: 16
|
|
43
|
+
num_workers: 8
|
|
44
|
+
|
|
45
|
+
# Images, instance masks and type masks paired by name once the prefixes are removed.
|
|
46
|
+
# This PanNuke conversion stores nucleus outlines, not ids: contours: true derives the ids.
|
|
47
|
+
data:
|
|
48
|
+
train:
|
|
49
|
+
images: /path/to/pannuke_split/train/images
|
|
50
|
+
instances: /path/to/pannuke_split/train/inst_masks
|
|
51
|
+
types: /path/to/pannuke_split/train/sem_masks
|
|
52
|
+
image_prefix: img_
|
|
53
|
+
instance_prefix: inst_
|
|
54
|
+
type_prefix: sem_
|
|
55
|
+
contours: true
|
|
56
|
+
val:
|
|
57
|
+
images: /path/to/pannuke_split/val/images
|
|
58
|
+
instances: /path/to/pannuke_split/val/inst_masks
|
|
59
|
+
types: /path/to/pannuke_split/val/sem_masks
|
|
60
|
+
image_prefix: img_
|
|
61
|
+
instance_prefix: inst_
|
|
62
|
+
type_prefix: sem_
|
|
63
|
+
contours: true
|
|
64
|
+
test:
|
|
65
|
+
images: /path/to/pannuke_split/test/images
|
|
66
|
+
instances: /path/to/pannuke_split/test/inst_masks
|
|
67
|
+
types: /path/to/pannuke_split/test/sem_masks
|
|
68
|
+
image_prefix: img_
|
|
69
|
+
instance_prefix: inst_
|
|
70
|
+
type_prefix: sem_
|
|
71
|
+
contours: true
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Zero-shot SAM 3 nucleus segmentation and typing from text prompts, scored with PQ:
|
|
2
|
+
# python -m pathotrain.cellseg.prompted prompted.yaml --split val # choose the threshold
|
|
3
|
+
# python -m pathotrain.cellseg.prompted prompted.yaml --split test # report it
|
|
4
|
+
# Needs access to the gated facebook/sam3 (SAM License). Copy this file and set the paths.
|
|
5
|
+
|
|
6
|
+
name: cellseg-prompted
|
|
7
|
+
|
|
8
|
+
# One prompt per nucleus type (label: prompt), in your masks' label order (here the
|
|
9
|
+
# pannuke_split conversion's: neoplastic is label 5); or a single
|
|
10
|
+
# prompt, e.g. `prompts: cell`, for untyped nuclei (binary PQ only). On PanNuke, "cell"
|
|
11
|
+
# finds nuclei and "nucleus" almost nothing.
|
|
12
|
+
prompts:
|
|
13
|
+
1: inflammatory cell
|
|
14
|
+
2: connective tissue cell
|
|
15
|
+
3: dead cell
|
|
16
|
+
4: epithelial cell
|
|
17
|
+
5: neoplastic cell
|
|
18
|
+
num_classes: 6 # types plus background
|
|
19
|
+
class_names: [background, inflammatory, connective, necrosis, epithelial, neoplastic]
|
|
20
|
+
|
|
21
|
+
thresholds: [0.4, 0.5, 0.6] # detection score thresholds, all scored in one pass
|
|
22
|
+
mask_threshold: 0.5
|
|
23
|
+
min_size: 10 # px a detection must keep after higher-scoring overlaps
|
|
24
|
+
batch_size: 8 # tiles per SAM 3 forward pass
|
|
25
|
+
|
|
26
|
+
data:
|
|
27
|
+
val:
|
|
28
|
+
images: /path/to/pannuke_split/val/images
|
|
29
|
+
instances: /path/to/pannuke_split/val/inst_masks
|
|
30
|
+
types: /path/to/pannuke_split/val/sem_masks
|
|
31
|
+
image_prefix: img_
|
|
32
|
+
instance_prefix: inst_
|
|
33
|
+
type_prefix: sem_
|
|
34
|
+
contours: true
|
|
35
|
+
test:
|
|
36
|
+
images: /path/to/pannuke_split/test/images
|
|
37
|
+
instances: /path/to/pannuke_split/test/inst_masks
|
|
38
|
+
types: /path/to/pannuke_split/test/sem_masks
|
|
39
|
+
image_prefix: img_
|
|
40
|
+
instance_prefix: inst_
|
|
41
|
+
type_prefix: sem_
|
|
42
|
+
contours: true
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Score a checkpoint written by :mod:`pathotrain.cellseg.train` on one split::
|
|
2
|
+
|
|
3
|
+
python -m pathotrain.cellseg.eval runs/exp/checkpoints/best.ckpt
|
|
4
|
+
python -m pathotrain.cellseg.eval best.ckpt --split val --config instance.yaml
|
|
5
|
+
|
|
6
|
+
Prints the metrics as JSON, keyed ``<split>/...`` (``test/bpq``, ``test/mpq``,
|
|
7
|
+
``test/pq_<type>``, ``test/dq``, ``test/sq``, ``test/loss``). ``--config`` replaces the
|
|
8
|
+
checkpoint's ``data``, ``loader``, ``val_loader``, ``trainer`` and ``mlflow_db``, as in
|
|
9
|
+
``pathotrain.segmentation.eval``; with an MLflow store, the metrics are logged there too.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from pathotrain import experiment
|
|
17
|
+
from pathotrain.cellseg import train
|
|
18
|
+
from pathotrain.engine import load_config
|
|
19
|
+
from pathotrain.segmentation.eval import OVERRIDES
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def evaluate(
|
|
23
|
+
checkpoint: str | Path,
|
|
24
|
+
split: str = "test",
|
|
25
|
+
config: dict | None = None,
|
|
26
|
+
mlflow_db: str | Path | None = None,
|
|
27
|
+
) -> dict[str, float]:
|
|
28
|
+
"""Score ``checkpoint`` on ``data[split]`` and return the metrics keyed ``<split>/...``."""
|
|
29
|
+
task, cfg = train.load_task(checkpoint)
|
|
30
|
+
if config is not None:
|
|
31
|
+
cfg = {**cfg, **{k: config[k] for k in OVERRIDES if k in config}}
|
|
32
|
+
if split not in cfg["data"]:
|
|
33
|
+
raise ValueError(f"data has no {split!r} split; pass --config with one")
|
|
34
|
+
metrics = experiment.evaluate(cfg, task, train.build_dataset(cfg, split), split)
|
|
35
|
+
experiment.log_eval(cfg, checkpoint, split, metrics, mlflow_db)
|
|
36
|
+
return metrics
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def main(argv: list[str] | None = None) -> None:
|
|
40
|
+
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
41
|
+
parser.add_argument("checkpoint", help="best.ckpt or last.ckpt written by train")
|
|
42
|
+
parser.add_argument("--split", default="test", help="data split to score (default: test)")
|
|
43
|
+
parser.add_argument(
|
|
44
|
+
"--config", help="YAML whose data, loader, val_loader and trainer sections apply"
|
|
45
|
+
)
|
|
46
|
+
parser.add_argument("--mlflow-db", help="also log the metrics to this MLflow SQLite file")
|
|
47
|
+
args = parser.parse_args(argv)
|
|
48
|
+
config = load_config(args.config) if args.config else None
|
|
49
|
+
print(json.dumps(evaluate(args.checkpoint, args.split, config, args.mlflow_db), indent=2))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
main()
|