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.
Files changed (145) hide show
  1. pathotrain/__init__.py +10 -0
  2. pathotrain/cellseg/README.md +121 -0
  3. pathotrain/cellseg/__init__.py +12 -0
  4. pathotrain/cellseg/classify.py +199 -0
  5. pathotrain/cellseg/configs/classify.example.yaml +53 -0
  6. pathotrain/cellseg/configs/config.example.yaml +65 -0
  7. pathotrain/cellseg/configs/instance.example.yaml +71 -0
  8. pathotrain/cellseg/configs/prompted.example.yaml +42 -0
  9. pathotrain/cellseg/eval.py +53 -0
  10. pathotrain/cellseg/export.py +136 -0
  11. pathotrain/cellseg/instances.py +174 -0
  12. pathotrain/cellseg/models.py +293 -0
  13. pathotrain/cellseg/prompted.py +160 -0
  14. pathotrain/cellseg/task.py +189 -0
  15. pathotrain/cellseg/train.py +94 -0
  16. pathotrain/dataloader/README.md +376 -0
  17. pathotrain/dataloader/__init__.py +43 -0
  18. pathotrain/dataloader/augmentation.py +467 -0
  19. pathotrain/dataloader/base.py +126 -0
  20. pathotrain/dataloader/caption.py +131 -0
  21. pathotrain/dataloader/classification.py +84 -0
  22. pathotrain/dataloader/detection.py +235 -0
  23. pathotrain/dataloader/instance.py +114 -0
  24. pathotrain/dataloader/pathogen.py +93 -0
  25. pathotrain/dataloader/registration.py +140 -0
  26. pathotrain/dataloader/sampling.py +122 -0
  27. pathotrain/dataloader/segmentation.py +223 -0
  28. pathotrain/dataloader/unlabelled.py +182 -0
  29. pathotrain/dataloader/vqa.py +160 -0
  30. pathotrain/detection/README.md +213 -0
  31. pathotrain/detection/__init__.py +6 -0
  32. pathotrain/detection/config.example.yaml +121 -0
  33. pathotrain/detection/eval.py +75 -0
  34. pathotrain/detection/export.py +173 -0
  35. pathotrain/detection/models.py +92 -0
  36. pathotrain/detection/task.py +175 -0
  37. pathotrain/detection/train.py +154 -0
  38. pathotrain/engine/__init__.py +33 -0
  39. pathotrain/engine/callbacks.py +132 -0
  40. pathotrain/engine/config.py +41 -0
  41. pathotrain/engine/logger.py +121 -0
  42. pathotrain/engine/schedules.py +20 -0
  43. pathotrain/engine/sweep.py +101 -0
  44. pathotrain/engine/task.py +54 -0
  45. pathotrain/engine/trainer.py +345 -0
  46. pathotrain/experiment.py +553 -0
  47. pathotrain/histossl/README.md +269 -0
  48. pathotrain/histossl/__init__.py +25 -0
  49. pathotrain/histossl/adaptation.py +163 -0
  50. pathotrain/histossl/backbones.py +147 -0
  51. pathotrain/histossl/config.py +315 -0
  52. pathotrain/histossl/configs/dinov2.example.yaml +80 -0
  53. pathotrain/histossl/configs/dinov2_openmidnight.example.yaml +82 -0
  54. pathotrain/histossl/configs/lejepa.example.yaml +66 -0
  55. pathotrain/histossl/configs/teacher_jepa.example.yaml +69 -0
  56. pathotrain/histossl/eval/__init__.py +6 -0
  57. pathotrain/histossl/eval/dense_probe.py +198 -0
  58. pathotrain/histossl/eval/linear_probe.py +239 -0
  59. pathotrain/histossl/export.py +55 -0
  60. pathotrain/histossl/masking.py +79 -0
  61. pathotrain/histossl/methods/__init__.py +8 -0
  62. pathotrain/histossl/methods/base.py +95 -0
  63. pathotrain/histossl/methods/dinov2.py +385 -0
  64. pathotrain/histossl/methods/lejepa.py +158 -0
  65. pathotrain/histossl/methods/teacher_jepa.py +181 -0
  66. pathotrain/histossl/train.py +236 -0
  67. pathotrain/pathoclip/README.md +152 -0
  68. pathotrain/pathoclip/__init__.py +8 -0
  69. pathotrain/pathoclip/config.py +153 -0
  70. pathotrain/pathoclip/configs/midnight-lit.example.yaml +57 -0
  71. pathotrain/pathoclip/configs/siglip2-base.example.yaml +53 -0
  72. pathotrain/pathoclip/data.py +52 -0
  73. pathotrain/pathoclip/eval.py +101 -0
  74. pathotrain/pathoclip/export.py +58 -0
  75. pathotrain/pathoclip/models.py +123 -0
  76. pathotrain/pathoclip/task.py +124 -0
  77. pathotrain/pathoclip/train.py +242 -0
  78. pathotrain/pathoclip/zero_shot.py +95 -0
  79. pathotrain/pathocls/README.md +119 -0
  80. pathotrain/pathocls/__init__.py +8 -0
  81. pathotrain/pathocls/backbones.py +82 -0
  82. pathotrain/pathocls/config.example.yaml +64 -0
  83. pathotrain/pathocls/eval.py +67 -0
  84. pathotrain/pathocls/export.py +101 -0
  85. pathotrain/pathocls/model.py +49 -0
  86. pathotrain/pathocls/task.py +102 -0
  87. pathotrain/pathocls/train.py +222 -0
  88. pathotrain/pathofm/README.md +281 -0
  89. pathotrain/pathofm/__init__.py +25 -0
  90. pathotrain/pathofm/models.py +200 -0
  91. pathotrain/pathofm/sam3.py +125 -0
  92. pathotrain/pathogen/README.md +235 -0
  93. pathotrain/pathogen/__init__.py +19 -0
  94. pathotrain/pathogen/cache.py +246 -0
  95. pathotrain/pathogen/config.example.yaml +91 -0
  96. pathotrain/pathogen/diffusion.py +273 -0
  97. pathotrain/pathogen/eval.py +82 -0
  98. pathotrain/pathogen/export.py +117 -0
  99. pathotrain/pathogen/flow.py +284 -0
  100. pathotrain/pathogen/train.py +166 -0
  101. pathotrain/pathogen/translate.py +65 -0
  102. pathotrain/pathosam/README.md +216 -0
  103. pathotrain/pathosam/__init__.py +5 -0
  104. pathotrain/pathosam/configs/concept.example.yaml +79 -0
  105. pathotrain/pathosam/configs/interactive.example.yaml +63 -0
  106. pathotrain/pathosam/configs/zeroshot.example.yaml +78 -0
  107. pathotrain/pathosam/eval.py +480 -0
  108. pathotrain/pathosam/export.py +540 -0
  109. pathotrain/pathosam/model.py +128 -0
  110. pathotrain/pathosam/prompts.py +55 -0
  111. pathotrain/pathosam/task.py +388 -0
  112. pathotrain/pathosam/train.py +93 -0
  113. pathotrain/pathovlm/README.md +543 -0
  114. pathotrain/pathovlm/__init__.py +6 -0
  115. pathotrain/pathovlm/callbacks.py +73 -0
  116. pathotrain/pathovlm/collate.py +100 -0
  117. pathotrain/pathovlm/config.py +213 -0
  118. pathotrain/pathovlm/configs/qwen3-vl-2b.example.yaml +52 -0
  119. pathotrain/pathovlm/configs/qwen3-vl-4b.example.yaml +52 -0
  120. pathotrain/pathovlm/eval.py +140 -0
  121. pathotrain/pathovlm/export.py +145 -0
  122. pathotrain/pathovlm/metrics.py +67 -0
  123. pathotrain/pathovlm/models.py +77 -0
  124. pathotrain/pathovlm/sample.py +80 -0
  125. pathotrain/pathovlm/stages.py +267 -0
  126. pathotrain/pathovlm/train.py +299 -0
  127. pathotrain/py.typed +0 -0
  128. pathotrain/registration/README.md +115 -0
  129. pathotrain/registration/__init__.py +6 -0
  130. pathotrain/registration/affine.py +287 -0
  131. pathotrain/registration/batch.py +147 -0
  132. pathotrain/segmentation/README.md +421 -0
  133. pathotrain/segmentation/__init__.py +15 -0
  134. pathotrain/segmentation/config.example.yaml +134 -0
  135. pathotrain/segmentation/encoders.py +183 -0
  136. pathotrain/segmentation/eval.py +73 -0
  137. pathotrain/segmentation/export.py +116 -0
  138. pathotrain/segmentation/losses.py +84 -0
  139. pathotrain/segmentation/models.py +97 -0
  140. pathotrain/segmentation/task.py +172 -0
  141. pathotrain/segmentation/train.py +152 -0
  142. pathotrain-0.1.0.dist-info/METADATA +290 -0
  143. pathotrain-0.1.0.dist-info/RECORD +145 -0
  144. pathotrain-0.1.0.dist-info/WHEEL +4 -0
  145. pathotrain-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,136 @@
1
+ """Export a checkpoint written by :mod:`pathotrain.cellseg.train` to ONNX::
2
+
3
+ python -m pathotrain.cellseg.export best.ckpt model.onnx --size 256 --mpp 0.25 --icc
4
+
5
+ Needs the export extra (``pip install 'pathotrain[export]'``). The graph takes ``image``
6
+ (batch, 3, size, size) float32, normalised as in training, and returns the network's
7
+ three branches, before any activation:
8
+
9
+ - ``np``: (batch, 2, size, size) logits, background and nucleus.
10
+ - ``hv``: (batch, 2, size, size) horizontal and vertical offsets from the nucleus centre.
11
+ - ``nt``: (batch, num_classes, size, size) nucleus-type logits.
12
+
13
+ The watershed runs outside the graph: on one tile's outputs,
14
+ ``pathotrain.cellseg.instances.instances_from_outputs(np[i], hv[i], nt[i])`` returns the
15
+ instance map and each instance's type. Tiles must overlap and their nuclei be merged
16
+ across tile borders when inferring a slide.
17
+
18
+ Export writes ``model_card.json`` beside the ONNX file and embeds it, as
19
+ ``pathotrain.segmentation.export`` does. It is an **instance** card naming the three
20
+ outputs: pathoinfer runs the same watershed on each tile and writes typed nucleus
21
+ polygons. Classes need real names (``task.class_names``). Tile folders record no resolution,
22
+ so ``--mpp`` and ``--icc``/``--no-icc`` are required, and ``--size`` without a training crop.
23
+ """
24
+
25
+ import argparse
26
+ from pathlib import Path
27
+
28
+ from torch import Tensor, nn
29
+
30
+ from pathotrain import experiment
31
+ from pathotrain.cellseg import train
32
+ from pathotrain.cellseg.models import BRANCHES
33
+ from pathotrain.segmentation.task import input_multiple
34
+
35
+
36
+ class _Branches(nn.Module):
37
+ """The model's branches as a tuple, in :data:`BRANCHES` order, for tracing."""
38
+
39
+ def __init__(self, model: nn.Module) -> None:
40
+ super().__init__()
41
+ self.model = model
42
+
43
+ def forward(self, image: Tensor) -> tuple[Tensor, ...]:
44
+ out = self.model(image)
45
+ return tuple(out[k] for k in BRANCHES)
46
+
47
+
48
+ def export(
49
+ checkpoint: str | Path,
50
+ path: str | Path,
51
+ size: int | None = None,
52
+ register: str | None = None,
53
+ mlflow_db: str | Path | None = None,
54
+ *,
55
+ mpp: float | None = None,
56
+ icc: bool | None = None,
57
+ name: str | None = None,
58
+ version: str = "1",
59
+ overlap: float = 0.25,
60
+ ) -> Path:
61
+ """Write ``checkpoint``'s model to ``path`` as ONNX at ``size`` px (default the training
62
+ crop), with ``model_card.json`` beside it, and return the path. Options as for
63
+ :func:`pathotrain.segmentation.export.export`."""
64
+ model, cfg = train.load_model(checkpoint)
65
+ size = size or experiment.input_size(cfg)
66
+ if size is None:
67
+ raise ValueError("the config trained on tile folders without a crop; pass a size")
68
+ multiple = input_multiple(model)
69
+ if size % multiple:
70
+ raise ValueError(f"size must be divisible by {multiple} for {cfg['model']['name']}")
71
+ path = Path(path)
72
+ outputs = {
73
+ "np": "(batch, 2, size, size) float32 logits: background, nucleus",
74
+ "hv": "(batch, 2, size, size) float32: horizontal, vertical offset from the centre",
75
+ "nt": "(batch, num_classes, size, size) float32 nucleus-type logits",
76
+ }
77
+ metadata = experiment.onnx_metadata(cfg, "instance_segmentation", size, outputs)
78
+ n_classes = cfg["model"]["num_classes"]
79
+ output = {"np": "np", "hv": "hv", "nt": "nt", "activation": "logits", "n_classes": n_classes}
80
+ card = experiment.model_card(
81
+ cfg,
82
+ "instance",
83
+ size,
84
+ path.name,
85
+ output,
86
+ mpp=mpp,
87
+ icc=icc,
88
+ name=name,
89
+ version=version,
90
+ overlap=overlap,
91
+ run_id=experiment.checkpoint_run_id(checkpoint),
92
+ )
93
+ experiment.export_onnx(_Branches(model), path, size, list(BRANCHES), metadata, card=card)
94
+ experiment.write_card(card, path)
95
+ if register is not None:
96
+ experiment.register_onnx(path, register, cfg, checkpoint, mlflow_db)
97
+ return path
98
+
99
+
100
+ def main(argv: list[str] | None = None) -> None:
101
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
102
+ parser.add_argument("checkpoint", help="best.ckpt or last.ckpt written by train")
103
+ parser.add_argument("output", help="the .onnx file to write")
104
+ parser.add_argument("--size", type=int, help="input side in px (default: training crop)")
105
+ parser.add_argument("--mpp", type=float, help="tile resolution; required for tile folders")
106
+ parser.add_argument(
107
+ "--icc",
108
+ action=argparse.BooleanOptionalAction,
109
+ help="whether training tiles were ICC-converted; required for tile folders",
110
+ )
111
+ parser.add_argument("--name", help="card name (default: the experiment name)")
112
+ parser.add_argument("--version", default="1", help="card version (default: 1)")
113
+ parser.add_argument(
114
+ "--overlap", type=float, default=0.25, help="recommended tile overlap (default 0.25)"
115
+ )
116
+ parser.add_argument("--register", help="also register the graph in MLflow under this name")
117
+ parser.add_argument(
118
+ "--mlflow-db", help="MLflow SQLite file for --register (default: the config's mlflow_db)"
119
+ )
120
+ args = parser.parse_args(argv)
121
+ export(
122
+ args.checkpoint,
123
+ args.output,
124
+ args.size,
125
+ args.register,
126
+ args.mlflow_db,
127
+ mpp=args.mpp,
128
+ icc=args.icc,
129
+ name=args.name,
130
+ version=args.version,
131
+ overlap=args.overlap,
132
+ )
133
+
134
+
135
+ if __name__ == "__main__":
136
+ main()
@@ -0,0 +1,174 @@
1
+ """Nucleus instance maps: targets from labels, HoVer-Net post-processing, PQ matching.
2
+
3
+ An instance map is an ``(H, W)`` integer array, 0 for background and one id per
4
+ nucleus. A type map gives each pixel its class, 0 for background.
5
+ """
6
+
7
+ import math
8
+
9
+ import numpy as np
10
+ import torch
11
+ from scipy import ndimage as ndi
12
+ from scipy.optimize import linear_sum_assignment
13
+ from scipy.spatial.distance import cdist
14
+ from skimage.segmentation import watershed
15
+
16
+ # HoVer-Net takes HV-map gradients with a 21 px Sobel kernel (cv2), whose smoothing is a
17
+ # binomial of variance 20 / 4 = 5: here a Gaussian derivative of that sigma. The maps
18
+ # are min-max scaled afterwards, so the kernel's scale does not matter.
19
+ SOBEL_SIGMA = math.sqrt(5)
20
+
21
+
22
+ def instance_types(instances: np.ndarray, types: np.ndarray, num_classes: int) -> np.ndarray:
23
+ """The type of each instance id, indexed by id (``out[0]`` is 0): the most common
24
+ nucleus type (``1..num_classes-1``) under it, 0 if it has none."""
25
+ size = int(instances.max()) + 1
26
+ labels = np.where((types > 0) & (types < num_classes), types, 0)
27
+ counts = np.bincount(
28
+ instances.ravel() * num_classes + labels.ravel(), minlength=size * num_classes
29
+ ).reshape(size, num_classes)
30
+ counts[:, 0] = 0 # background votes only when nothing else does
31
+ out = counts.argmax(1)
32
+ out[0] = 0
33
+ return out
34
+
35
+
36
+ def hv_maps(instances: np.ndarray) -> np.ndarray:
37
+ """HoVer-Net's ``(2, H, W)`` float32 targets: each nucleus pixel's horizontal and
38
+ vertical offset from its nucleus's centre of mass, scaled to [-1, 1] on each side
39
+ of the centre separately; 0 on background."""
40
+ hv = np.zeros((2, *instances.shape), np.float32)
41
+ for i, box in enumerate(ndi.find_objects(instances), start=1):
42
+ if box is None:
43
+ continue
44
+ inside = instances[box] == i
45
+ cy, cx = ndi.center_of_mass(inside)
46
+ ys, xs = np.nonzero(inside)
47
+ for channel, offset in ((0, xs - cx), (1, ys - cy)):
48
+ offset = offset.astype(np.float32)
49
+ neg, pos = offset < 0, offset > 0
50
+ if neg.any():
51
+ offset[neg] /= -offset[neg].min()
52
+ if pos.any():
53
+ offset[pos] /= offset[pos].max()
54
+ hv[channel][box][inside] = offset
55
+ return hv
56
+
57
+
58
+ def add_hv_maps(target: dict) -> dict:
59
+ """``target`` with the HV maps of its ``inst`` map as ``hv``, ``(2, H, W)`` float32: the
60
+ ``target_transform`` of an ``InstanceTileFolderDataset`` for HoVer-Net-style training.
61
+ It runs in the loader workers, after augmentation."""
62
+ return {**target, "hv": torch.from_numpy(hv_maps(target["inst"].numpy()))}
63
+
64
+
65
+ def _minmax(x: np.ndarray) -> np.ndarray:
66
+ span = x.max() - x.min()
67
+ return (x - x.min()) / span if span > 0 else np.zeros_like(x)
68
+
69
+
70
+ def _remove_small(labels: np.ndarray, min_size: int) -> np.ndarray:
71
+ sizes = np.bincount(labels.ravel())
72
+ small = sizes < min_size
73
+ small[0] = False
74
+ return np.where(small[labels], 0, labels)
75
+
76
+
77
+ def postprocess(
78
+ foreground: np.ndarray,
79
+ hv: np.ndarray,
80
+ threshold: float = 0.5,
81
+ marker_threshold: float = 0.4,
82
+ min_size: int = 10,
83
+ ) -> np.ndarray:
84
+ """HoVer-Net's watershed: an instance map from the nucleus probability ``(H, W)``
85
+ and the predicted HV maps ``(2, H, W)``.
86
+
87
+ Nuclei are where ``foreground >= threshold``. Strong HV gradients mark boundaries
88
+ between touching nuclei; the nucleus pixels away from them (gradient energy below
89
+ ``marker_threshold``) seed a watershed over the nuclei. Blobs and seeds smaller than
90
+ ``min_size`` pixels are dropped.
91
+ """
92
+ blobs, _ = ndi.label(foreground >= threshold)
93
+ nuclei = _remove_small(blobs, min_size) > 0
94
+ if not nuclei.any():
95
+ return np.zeros(foreground.shape, np.int32)
96
+ h, v = _minmax(hv[0]), _minmax(hv[1])
97
+ # Signed, as HoVer-Net: the maps rise across a nucleus and fall steeply between two
98
+ # touching ones, so the most negative gradients mark the boundaries (energy near 1).
99
+ grad_h = 1 - _minmax(ndi.gaussian_filter(h, SOBEL_SIGMA, order=(0, 1)))
100
+ grad_v = 1 - _minmax(ndi.gaussian_filter(v, SOBEL_SIGMA, order=(1, 0)))
101
+ energy = np.clip(np.maximum(grad_h, grad_v) - ~nuclei, 0, None)
102
+ # HoVer-Net blurs with a 3 px kernel (cv2 sigma 0.8 for that size).
103
+ dist = -ndi.gaussian_filter((1 - energy) * nuclei, 0.8)
104
+ markers = ndi.binary_fill_holes(nuclei & (energy < marker_threshold))
105
+ disk = np.hypot(*np.mgrid[-2:3, -2:3]) <= 2.5 # 5 x 5 ellipse
106
+ markers, _ = ndi.label(ndi.binary_opening(markers, disk))
107
+ markers = _remove_small(markers, min_size).astype(np.int32)
108
+ return watershed(dist, markers, mask=nuclei).astype(np.int32)
109
+
110
+
111
+ def predicted_types(instances: np.ndarray, type_probs: np.ndarray) -> np.ndarray:
112
+ """The type of each predicted instance, indexed by id: the most common nucleus type
113
+ of the per-pixel argmax of ``type_probs`` ``(C, H, W)`` (or logits) under it."""
114
+ return instance_types(instances, type_probs.argmax(0), type_probs.shape[0])
115
+
116
+
117
+ def _softmax(logits: np.ndarray) -> np.ndarray:
118
+ e = np.exp(logits - logits.max(0, keepdims=True))
119
+ return e / e.sum(0, keepdims=True)
120
+
121
+
122
+ def instances_from_outputs(
123
+ np_logits: np.ndarray, hv: np.ndarray, nt_logits: np.ndarray, **options
124
+ ) -> tuple[np.ndarray, np.ndarray]:
125
+ """One tile's nuclei from a model's ``np`` ``(2, H, W)``, ``hv`` ``(2, H, W)`` and
126
+ ``nt`` ``(C, H, W)`` outputs (PyTorch or ONNX, as numpy): the instance map and the
127
+ type of each instance id. ``options`` go to :func:`postprocess`."""
128
+ inst = postprocess(_softmax(np_logits)[1], hv, **options)
129
+ return inst, predicted_types(inst, nt_logits)
130
+
131
+
132
+ def centroids(
133
+ instances: np.ndarray, ids: np.ndarray | None = None
134
+ ) -> tuple[np.ndarray, np.ndarray]:
135
+ """``ids`` (default every instance id of ``instances``) and their ``(N, 2)`` centres
136
+ of mass, ``(y, x)``."""
137
+ if ids is None:
138
+ ids = np.unique(instances)
139
+ ids = ids[ids > 0]
140
+ if not len(ids):
141
+ return ids, np.zeros((0, 2))
142
+ return ids, np.array(ndi.center_of_mass(np.ones_like(instances), instances, ids))
143
+
144
+
145
+ def pair_centroids(true: np.ndarray, pred: np.ndarray, radius: float) -> np.ndarray:
146
+ """``(K, 2)`` index pairs ``[i_true, i_pred]`` of two ``(N, 2)`` point sets: the
147
+ pairing with the least total distance (Hungarian), keeping pairs within ``radius``."""
148
+ if not len(true) or not len(pred):
149
+ return np.zeros((0, 2), np.int64)
150
+ distance = cdist(true, pred)
151
+ rows, cols = linear_sum_assignment(distance)
152
+ near = distance[rows, cols] <= radius
153
+ return np.stack([rows[near], cols[near]], 1)
154
+
155
+
156
+ def match(true: np.ndarray, pred: np.ndarray) -> tuple[int, int, int, float]:
157
+ """``(tp, fp, fn, iou_sum)`` of two instance maps: an instance pair matches when
158
+ their IoU exceeds 0.5 (which makes the matching unique)."""
159
+ t_ids, t = np.unique(true, return_inverse=True)
160
+ p_ids, p = np.unique(pred, return_inverse=True)
161
+ # Index 0 is background whenever it is present; shift so ids start at 1.
162
+ t = t.ravel() + (t_ids[0] != 0)
163
+ p = p.ravel() + (p_ids[0] != 0)
164
+ n_t, n_p = int(t.max()), int(p.max())
165
+ if n_t == 0 or n_p == 0:
166
+ return 0, n_p, n_t, 0.0
167
+ joint = np.bincount(t * (n_p + 1) + p, minlength=(n_t + 1) * (n_p + 1))
168
+ joint = joint.reshape(n_t + 1, n_p + 1)
169
+ inter = joint[1:, 1:]
170
+ union = joint[1:].sum(1, keepdims=True) + joint[:, 1:].sum(0, keepdims=True) - inter
171
+ iou = inter / union
172
+ matched = iou > 0.5
173
+ tp = int(matched.sum())
174
+ return tp, n_p - tp, n_t - tp, float(iou[matched].sum())
@@ -0,0 +1,293 @@
1
+ """Cell (nucleus) segmentation networks, written from their papers. No authors' code or weights.
2
+
3
+ Each maps ``(B, 3, H, W)`` images to ``(B, num_classes, H, W)`` semantic logits, the
4
+ nuclear-type (NT) branch; train these with :mod:`pathotrain.segmentation.train`, naming
5
+ the model ``cellseg:<arch>``. With ``instance=True`` each returns HoVer-Net's three
6
+ branches as a dict (see :data:`BRANCHES`) for :mod:`pathotrain.cellseg.train`.
7
+
8
+ - ``hovernet``: HoVer-Net (Graham et al. 2019). Pre-activation ResNet-50 encoder whose
9
+ stem keeps full resolution, and HoVer-Net's dense decoder; its "fast" variant, with
10
+ padded convolutions, so the output has the input's size.
11
+ - ``hovernext``: HoVer-NeXt (Baumann et al. 2024). ConvNeXt encoder and U-Net decoder.
12
+ - ``cellvit``: CellViT (Hörst et al. 2024). A ``pathotrain.pathofm`` ViT encoder and the
13
+ CellViT decoder. CellViT++'s cell classifier on the encoder's tokens is in
14
+ :mod:`pathotrain.cellseg.classify`.
15
+
16
+ Encoder weights are the only pretrained weights: timm ImageNet weights, or a
17
+ ``pathofm`` foundation model.
18
+ """
19
+
20
+ import segmentation_models_pytorch as smp
21
+ import timm
22
+ import torch
23
+ import torch.nn.functional as F
24
+ from torch import Tensor, nn
25
+
26
+ from pathotrain.pathofm import load_backbone
27
+ from pathotrain.segmentation.encoders import adapt_backbone, token_grids
28
+
29
+ # The instance branches, as HoVer-Net: nucleus vs background (NP, 2 logits), horizontal and
30
+ # vertical distance maps (HV, 2 values) and nucleus type (NT, num_classes logits).
31
+ BRANCHES = ("np", "hv", "nt")
32
+
33
+
34
+ def _channels(num_classes: int, instance: bool) -> dict[str, int]:
35
+ return {"np": 2, "hv": 2, "nt": num_classes} if instance else {"nt": num_classes}
36
+
37
+
38
+ def _outputs(out: dict[str, Tensor], instance: bool) -> Tensor | dict[str, Tensor]:
39
+ return out if instance else out["nt"]
40
+
41
+
42
+ def build_model(arch: str, num_classes: int, in_channels: int = 3, **kwargs) -> nn.Module:
43
+ """Build ``"hovernet"``, ``"hovernext"`` or ``"cellvit"``; ``kwargs`` go to its class."""
44
+ if arch == "hovernet":
45
+ return HoVerNet(num_classes, in_channels, **kwargs)
46
+ if arch == "hovernext":
47
+ return hovernext(num_classes, in_channels, **kwargs)
48
+ if arch == "cellvit":
49
+ if in_channels != 3:
50
+ raise ValueError("CellViT's foundation-model encoders take RGB input only")
51
+ kwargs.pop("encoder_weights", None) # the foundation model loads its own weights
52
+ return CellViT(num_classes=num_classes, **kwargs)
53
+ raise ValueError(
54
+ f"unknown cell segmentation model {arch!r}, expected hovernet, hovernext or cellvit"
55
+ )
56
+
57
+
58
+ def _bn_relu(channels: int) -> nn.Sequential:
59
+ return nn.Sequential(nn.BatchNorm2d(channels), nn.ReLU(inplace=True))
60
+
61
+
62
+ class _DenseBlock(nn.Module):
63
+ """HoVer-Net's dense block: ``units`` times (BN-ReLU, 1x1 conv to 128, BN-ReLU,
64
+ ``ksize`` grouped conv to 32), each unit's output concatenated to its input."""
65
+
66
+ def __init__(self, channels: int, units: int, ksize: int = 5) -> None:
67
+ super().__init__()
68
+ self.units = nn.ModuleList(
69
+ nn.Sequential(
70
+ _bn_relu(channels + i * 32),
71
+ nn.Conv2d(channels + i * 32, 128, 1, bias=False),
72
+ _bn_relu(128),
73
+ nn.Conv2d(128, 32, ksize, padding=ksize // 2, groups=4, bias=False),
74
+ )
75
+ for i in range(units)
76
+ )
77
+ self.out = _bn_relu(channels + units * 32)
78
+
79
+ def forward(self, x: Tensor) -> Tensor:
80
+ for unit in self.units:
81
+ x = torch.cat([x, unit(x)], 1)
82
+ return self.out(x)
83
+
84
+
85
+ class _HoVerBranch(nn.Module):
86
+ """One HoVer-Net decoder branch: stride 8 to 1, adding the encoder skips."""
87
+
88
+ def __init__(self, channels: int) -> None:
89
+ super().__init__()
90
+ self.u3 = nn.Sequential(
91
+ nn.Conv2d(1024, 256, 5, padding=2, bias=False),
92
+ _DenseBlock(256, 8),
93
+ nn.Conv2d(512, 512, 1, bias=False),
94
+ )
95
+ self.u2 = nn.Sequential(
96
+ nn.Conv2d(512, 128, 5, padding=2, bias=False),
97
+ _DenseBlock(128, 4),
98
+ nn.Conv2d(256, 256, 1, bias=False),
99
+ )
100
+ self.u1 = nn.Conv2d(256, 64, 5, padding=2, bias=False)
101
+ self.head = nn.Sequential(_bn_relu(64), nn.Conv2d(64, channels, 1))
102
+
103
+ def forward(self, d0: Tensor, d1: Tensor, d2: Tensor, d3: Tensor) -> Tensor:
104
+ u = self.u3(F.interpolate(d3, scale_factor=2) + d2)
105
+ u = self.u2(F.interpolate(u, scale_factor=2) + d1)
106
+ u = self.u1(F.interpolate(u, scale_factor=2) + d0)
107
+ return self.head(u)
108
+
109
+
110
+ class HoVerNet(nn.Module):
111
+ """HoVer-Net: one decoder branch per output (NT; with ``instance``, also NP and HV).
112
+
113
+ The encoder is timm's pre-activation ResNet-50 (``resnetv2_50``) with HoVer-Net's
114
+ changes: stride-1 stem, no max pool, so its four stages sit at strides 1, 2, 4 and 8.
115
+
116
+ Args:
117
+ num_classes: Output channels, including background.
118
+ in_channels: Image channels.
119
+ encoder_weights: ``"imagenet"`` loads timm's ImageNet weights (Apache-2.0),
120
+ ``None`` trains from scratch.
121
+ instance: Return the NP, HV and NT branches as a dict.
122
+ """
123
+
124
+ output_stride = 8 # input sides must be divisible by this
125
+
126
+ def __init__(
127
+ self,
128
+ num_classes: int,
129
+ in_channels: int = 3,
130
+ encoder_weights: str | None = "imagenet",
131
+ instance: bool = False,
132
+ ) -> None:
133
+ super().__init__()
134
+ if encoder_weights not in ("imagenet", None):
135
+ raise ValueError(f"encoder_weights must be 'imagenet' or None, got {encoder_weights!r}")
136
+ self.encoder = timm.create_model(
137
+ "resnetv2_50", pretrained=encoder_weights == "imagenet", in_chans=in_channels
138
+ )
139
+ self.encoder.stem.conv.stride = (1, 1)
140
+ self.encoder.stem.pool = nn.Identity()
141
+ self.encoder.head = nn.Identity()
142
+ self.conv_bot = nn.Conv2d(2048, 1024, 1, bias=False)
143
+ self.instance = instance
144
+ self.branches = nn.ModuleDict(
145
+ {k: _HoVerBranch(c) for k, c in _channels(num_classes, instance).items()}
146
+ )
147
+
148
+ def forward(self, x: Tensor) -> Tensor | dict[str, Tensor]:
149
+ e = self.encoder
150
+ d0 = e.stages[0](e.stem(x))
151
+ d1 = e.stages[1](d0)
152
+ d2 = e.stages[2](d1)
153
+ d3 = self.conv_bot(e.norm(e.stages[3](d2)))
154
+ out = {k: branch(d0, d1, d2, d3) for k, branch in self.branches.items()}
155
+ return _outputs(out, self.instance)
156
+
157
+
158
+ def hovernext(
159
+ num_classes: int,
160
+ in_channels: int = 3,
161
+ encoder: str = "convnext_base",
162
+ encoder_weights: str | None = "imagenet",
163
+ instance: bool = False,
164
+ **kwargs,
165
+ ) -> nn.Module:
166
+ """HoVer-NeXt's network: a timm ``encoder`` under SMP's U-Net decoder; ``kwargs`` go
167
+ to ``smp.Unet``. With ``instance``, the NP, HV and NT branches are channel groups of one
168
+ shared decoder's output (a dict).
169
+
170
+ The default is ConvNeXt (V1) Base with timm's ImageNet weights (``fb_in22k_ft_in1k``,
171
+ Apache-2.0); ``encoder_weights=None`` trains from scratch. The paper's ConvNeXt-V2
172
+ (``encoder="convnextv2_base"``) has ImageNet weights under CC-BY-NC-4.0 only.
173
+ """
174
+ channels = _channels(num_classes, instance)
175
+ model = smp.create_model(
176
+ "unet",
177
+ encoder_name=f"tu-{encoder}",
178
+ encoder_weights=encoder_weights,
179
+ in_channels=in_channels,
180
+ classes=sum(channels.values()),
181
+ **kwargs,
182
+ )
183
+ return _SplitChannels(model, channels) if instance else model
184
+
185
+
186
+ class _SplitChannels(nn.Module):
187
+ """``model``'s output channels as a dict of consecutive groups of ``channels``."""
188
+
189
+ def __init__(self, model: nn.Module, channels: dict[str, int]) -> None:
190
+ super().__init__()
191
+ self.model, self.channels = model, channels
192
+ self.output_stride = model.encoder.output_stride
193
+
194
+ def forward(self, x: Tensor) -> dict[str, Tensor]:
195
+ parts = self.model(x).split(list(self.channels.values()), 1)
196
+ return dict(zip(self.channels, parts, strict=True))
197
+
198
+
199
+ def _conv(cin: int, cout: int) -> nn.Sequential:
200
+ return nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU(True))
201
+
202
+
203
+ def _deconv(cin: int, cout: int) -> nn.Sequential:
204
+ """2x upsampling: transposed conv, then a conv block (CellViT's Deconv2DBlock)."""
205
+ return nn.Sequential(nn.ConvTranspose2d(cin, cout, 2, stride=2), _conv(cout, cout))
206
+
207
+
208
+ class _CellViTBranch(nn.Module):
209
+ """One CellViT decoder branch: upsamples the deepest tokens, merging the shared skips."""
210
+
211
+ def __init__(self, dim: int, bottleneck: int, channels: int) -> None:
212
+ super().__init__()
213
+ b = bottleneck
214
+ self.bottleneck_upsampler = nn.ConvTranspose2d(dim, b, 2, stride=2)
215
+ self.decoder3_upsampler = nn.Sequential(
216
+ _conv(2 * b, b), _conv(b, b), _conv(b, b), nn.ConvTranspose2d(b, 256, 2, stride=2)
217
+ )
218
+ self.decoder2_upsampler = nn.Sequential(
219
+ _conv(512, 256), _conv(256, 256), nn.ConvTranspose2d(256, 128, 2, stride=2)
220
+ )
221
+ self.decoder1_upsampler = nn.Sequential(
222
+ _conv(256, 128), _conv(128, 128), nn.ConvTranspose2d(128, 64, 2, stride=2)
223
+ )
224
+ self.head = nn.Sequential(_conv(128, 64), _conv(64, 64), nn.Conv2d(64, channels, 1))
225
+
226
+ def forward(self, z4: Tensor, s3: Tensor, s2: Tensor, s1: Tensor, s0: Tensor) -> Tensor:
227
+ u = self.bottleneck_upsampler(z4) # stride 8
228
+ u = self.decoder3_upsampler(torch.cat([s3, u], 1)) # 4
229
+ u = self.decoder2_upsampler(torch.cat([s2, u], 1)) # 2
230
+ u = self.decoder1_upsampler(torch.cat([s1, u], 1)) # 1
231
+ return self.head(torch.cat([s0, u], 1))
232
+
233
+
234
+ class CellViT(nn.Module):
235
+ """CellViT on a ViT encoder: shared skips, one decoder branch per output (NT; with
236
+ ``instance``, also NP and HV).
237
+
238
+ Tokens of four layers (as ``(B, D, H/16, W/16)`` grids, see
239
+ :func:`~pathotrain.segmentation.encoders.token_grids`) and the image itself are the
240
+ skips of a U-Net-like decoder that upsamples by transposed convolutions.
241
+
242
+ Args:
243
+ backbone: A foundation model name from ``pathotrain.pathofm`` or a ViT with the
244
+ ``transformers`` interface ``ViTPyramidEncoder`` takes.
245
+ num_classes: Output channels, including background.
246
+ layers: Four 1-based transformer layers, shallow to deep. Default: evenly
247
+ spaced, ending with the last layer.
248
+ freeze: Keep the backbone fixed (only the decoder trains). ``False`` fine-tunes it.
249
+ adaptation: Train the backbone partly instead, e.g. ``{type: lora, rank: 8}``; see
250
+ :func:`~pathotrain.segmentation.encoders.adapt_backbone`. Overrides ``freeze``.
251
+ skip_dims: Channels of the stride-8 and stride-4 steps of the shallowest skip.
252
+ bottleneck_dim: Channels of the deepest skip.
253
+ instance: Return the NP, HV and NT branches as a dict.
254
+ """
255
+
256
+ output_stride = 16
257
+
258
+ def __init__(
259
+ self,
260
+ backbone: str | nn.Module,
261
+ num_classes: int,
262
+ layers: tuple[int, int, int, int] | None = None,
263
+ freeze: bool = True,
264
+ skip_dims: tuple[int, int] = (512, 256),
265
+ bottleneck_dim: int = 512,
266
+ instance: bool = False,
267
+ adaptation: dict | None = None,
268
+ ) -> None:
269
+ super().__init__()
270
+ self.backbone = load_backbone(backbone) if isinstance(backbone, str) else backbone
271
+ n, dim = self.backbone.config.num_hidden_layers, self.backbone.config.hidden_size
272
+ self.layers = tuple(layers or (round(n * i / 4) for i in range(1, 5)))
273
+ if len(self.layers) != 4 or not all(1 <= i <= n for i in self.layers):
274
+ raise ValueError(f"layers must be four indices in [1, {n}], got {self.layers}")
275
+ self.backbone, self.freeze = adapt_backbone(self.backbone, freeze, adaptation)
276
+ s1, s2, b = *skip_dims, bottleneck_dim
277
+ self.decoder0 = nn.Sequential(_conv(3, 32), _conv(32, 64)) # stride 1, the image
278
+ self.decoder1 = nn.Sequential(_deconv(dim, s1), _deconv(s1, s2), _deconv(s2, 128))
279
+ self.decoder2 = nn.Sequential(_deconv(dim, s1), _deconv(s1, 256))
280
+ self.decoder3 = _deconv(dim, b)
281
+ self.instance = instance
282
+ self.branches = nn.ModuleDict(
283
+ {k: _CellViTBranch(dim, b, c) for k, c in _channels(num_classes, instance).items()}
284
+ )
285
+
286
+ def forward(self, x: Tensor, return_tokens: bool = False):
287
+ """The outputs; with ``return_tokens``, also the deepest layer's tokens as a
288
+ ``(B, D, H/16, W/16)`` grid (CellViT++ embeds the detected cells with them)."""
289
+ z1, z2, z3, z4 = token_grids(self.backbone, x, self.layers, self.freeze)
290
+ skips = (self.decoder3(z3), self.decoder2(z2), self.decoder1(z1), self.decoder0(x))
291
+ out = {k: branch(z4, *skips) for k, branch in self.branches.items()}
292
+ out = _outputs(out, self.instance)
293
+ return (out, z4) if return_tokens else out