comploss 0.1.0__tar.gz
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.
- comploss-0.1.0/LICENSE +28 -0
- comploss-0.1.0/PKG-INFO +243 -0
- comploss-0.1.0/README.md +200 -0
- comploss-0.1.0/pyproject.toml +52 -0
- comploss-0.1.0/setup.cfg +4 -0
- comploss-0.1.0/src/comploss/__init__.py +22 -0
- comploss-0.1.0/src/comploss/cli.py +114 -0
- comploss-0.1.0/src/comploss/components/__init__.py +5 -0
- comploss-0.1.0/src/comploss/components/labeling.py +67 -0
- comploss-0.1.0/src/comploss/components/voronoi.py +46 -0
- comploss-0.1.0/src/comploss/integrations/__init__.py +1 -0
- comploss-0.1.0/src/comploss/integrations/nnunet/__init__.py +202 -0
- comploss-0.1.0/src/comploss/integrations/nnunet/install.py +99 -0
- comploss-0.1.0/src/comploss/losses/__init__.py +16 -0
- comploss-0.1.0/src/comploss/losses/_utils.py +126 -0
- comploss-0.1.0/src/comploss/losses/component/__init__.py +11 -0
- comploss-0.1.0/src/comploss/losses/component/cat.py +106 -0
- comploss-0.1.0/src/comploss/losses/component/catmil.py +118 -0
- comploss-0.1.0/src/comploss/losses/component/cc_dice_ce.py +90 -0
- comploss-0.1.0/src/comploss/losses/component/mil.py +87 -0
- comploss-0.1.0/src/comploss/losses/deep_supervision.py +33 -0
- comploss-0.1.0/src/comploss/losses/registry.py +60 -0
- comploss-0.1.0/src/comploss/losses/voxel/__init__.py +5 -0
- comploss-0.1.0/src/comploss/losses/voxel/_common.py +23 -0
- comploss-0.1.0/src/comploss/losses/voxel/dice.py +86 -0
- comploss-0.1.0/src/comploss/losses/voxel/tversky.py +66 -0
- comploss-0.1.0/src/comploss/metrics/__init__.py +7 -0
- comploss-0.1.0/src/comploss/metrics/detection.py +162 -0
- comploss-0.1.0/src/comploss/transforms.py +54 -0
- comploss-0.1.0/src/comploss.egg-info/PKG-INFO +243 -0
- comploss-0.1.0/src/comploss.egg-info/SOURCES.txt +37 -0
- comploss-0.1.0/src/comploss.egg-info/dependency_links.txt +1 -0
- comploss-0.1.0/src/comploss.egg-info/entry_points.txt +2 -0
- comploss-0.1.0/src/comploss.egg-info/requires.txt +26 -0
- comploss-0.1.0/src/comploss.egg-info/top_level.txt +1 -0
- comploss-0.1.0/tests/test_losses.py +159 -0
- comploss-0.1.0/tests/test_metrics.py +83 -0
- comploss-0.1.0/tests/test_nnunet.py +155 -0
- comploss-0.1.0/tests/test_parity.py +97 -0
comploss-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Minh Sao Khue Luu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
The directory `slsseg/` contains a modified copy of nnU-Net
|
|
26
|
+
(https://github.com/MIC-DKFZ/nnUNet), Copyright German Cancer Research Center
|
|
27
|
+
(DKFZ), licensed under the Apache License, Version 2.0. Those files remain
|
|
28
|
+
subject to the Apache License 2.0: https://www.apache.org/licenses/LICENSE-2.0
|
comploss-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: comploss
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Component-aware loss functions and object-level metrics for segmenting small and multiple structures (CATMIL, CC-DiceCE, ...), with nnU-Net v2 and MONAI support.
|
|
5
|
+
Author: Minh Sao Khue Luu
|
|
6
|
+
Maintainer: Minh Sao Khue Luu
|
|
7
|
+
License: MIT
|
|
8
|
+
Project-URL: Repository, https://github.com/luumsk/comploss
|
|
9
|
+
Project-URL: Issues, https://github.com/luumsk/comploss/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/luumsk/comploss/blob/main/CHANGELOG.md
|
|
11
|
+
Project-URL: CATMIL paper code, https://github.com/luumsk/SmallLesionMRI
|
|
12
|
+
Keywords: segmentation,loss function,connected components,small objects,instance imbalance,medical image segmentation,nnU-Net,pytorch
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: torch>=2.0
|
|
23
|
+
Requires-Dist: numpy
|
|
24
|
+
Requires-Dist: scipy
|
|
25
|
+
Provides-Extra: nnunet
|
|
26
|
+
Requires-Dist: nnunetv2>=2.1; extra == "nnunet"
|
|
27
|
+
Provides-Extra: monai
|
|
28
|
+
Requires-Dist: monai>=1.3; extra == "monai"
|
|
29
|
+
Provides-Extra: fast-cc
|
|
30
|
+
Requires-Dist: connected-components-3d>=3.12; extra == "fast-cc"
|
|
31
|
+
Provides-Extra: io
|
|
32
|
+
Requires-Dist: nibabel; extra == "io"
|
|
33
|
+
Provides-Extra: test
|
|
34
|
+
Requires-Dist: pytest; extra == "test"
|
|
35
|
+
Requires-Dist: monai>=1.3; extra == "test"
|
|
36
|
+
Provides-Extra: dev
|
|
37
|
+
Requires-Dist: pytest; extra == "dev"
|
|
38
|
+
Requires-Dist: monai>=1.3; extra == "dev"
|
|
39
|
+
Requires-Dist: ruff; extra == "dev"
|
|
40
|
+
Requires-Dist: build; extra == "dev"
|
|
41
|
+
Requires-Dist: twine; extra == "dev"
|
|
42
|
+
Dynamic: license-file
|
|
43
|
+
|
|
44
|
+
# comploss
|
|
45
|
+
|
|
46
|
+
**Component-aware loss functions and object-level metrics for segmentation in PyTorch.**
|
|
47
|
+
|
|
48
|
+
Voxel-wise losses such as Dice, cross entropy and Tversky sum over voxels, so a few large
|
|
49
|
+
objects dominate the gradient. A missed 5-voxel object barely changes the loss. That matters
|
|
50
|
+
whenever an image holds many objects of very different sizes: small lesions in MRI, nodules in
|
|
51
|
+
CT, cells and nuclei in microscopy, defects in industrial inspection, small buildings or
|
|
52
|
+
vehicles in remote sensing.
|
|
53
|
+
|
|
54
|
+
The losses in `comploss` are defined over the **connected components** of the ground
|
|
55
|
+
truth, so every object counts. The package includes:
|
|
56
|
+
|
|
57
|
+
* **Component-aware losses**: CATMIL and its two terms, CAT and MIL (Luu et al.), and CC-DiceCE
|
|
58
|
+
(Bouteille et al., ISBI 2026).
|
|
59
|
+
* **Voxel-wise baselines** with the same interface: DiceCE (identical to nnU-Net's default),
|
|
60
|
+
Tversky (identical to MONAI's), Focal Tversky.
|
|
61
|
+
* **Object-level metrics**: object recall, precision and F1, recall by object size, a per-object
|
|
62
|
+
table, size profiling of a dataset.
|
|
63
|
+
* **Integrations**: nnU-Net v2 trainers for every loss, MONAI-style transforms, deep supervision.
|
|
64
|
+
|
|
65
|
+
All losses take raw logits `(B, C, *spatial)` and integer targets `(B, 1, *spatial)` (the
|
|
66
|
+
nnU-Net layout), in 2D or 3D. Tests check every port against its reference implementation
|
|
67
|
+
(values and gradients).
|
|
68
|
+
|
|
69
|
+
## Install
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
pip install comploss # torch, numpy, scipy
|
|
73
|
+
pip install "comploss[nnunet]" # + nnU-Net v2 trainers
|
|
74
|
+
pip install "comploss[fast-cc]" # + faster connected components (cc3d)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
From source (for development):
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
git clone https://github.com/luumsk/comploss && cd comploss
|
|
81
|
+
pip install -e ".[dev,nnunet,fast-cc]"
|
|
82
|
+
pytest
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Available losses
|
|
86
|
+
|
|
87
|
+
| name (`get_loss`) | class | type | reference |
|
|
88
|
+
|---|---|---|---|
|
|
89
|
+
| `catmil` | `CATMILLoss` | DiceCE + CAT + MIL | Luu et al., arXiv:2604.08015 |
|
|
90
|
+
| `cat` | `ComponentAdaptiveTverskyLoss` | component-weighted Tversky | Luu et al. |
|
|
91
|
+
| `mil` | `ComponentMILLoss` | one bag per object, `-log max p` | Luu et al. |
|
|
92
|
+
| `cc_dice_ce` | `CCDiceCEGlobalLoss` | Voronoi component DiceCE + global DiceCE | Bouteille et al., arXiv:2511.17146 |
|
|
93
|
+
| `cc_dice_ce_component` | `CCDiceCELoss` | Voronoi component DiceCE only | Bouteille et al. |
|
|
94
|
+
| `dice_ce` | `DiceCELoss` | voxel-wise (nnU-Net default) | Isensee et al. |
|
|
95
|
+
| `tversky` | `TverskyLoss` | voxel-wise | Salehi et al. |
|
|
96
|
+
| `focal_tversky` | `FocalTverskyLoss` | voxel-wise | Abraham & Khan |
|
|
97
|
+
|
|
98
|
+
## Usage in PyTorch or MONAI
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from comploss import get_loss
|
|
102
|
+
|
|
103
|
+
loss_fn = get_loss("catmil") # DiceCE + 0.1*CAT (linear warm-up over 50 epochs) + 0.2*MIL
|
|
104
|
+
for epoch in range(n_epochs):
|
|
105
|
+
loss_fn.set_epoch(epoch) # drives the CAT warm-up
|
|
106
|
+
for image, label in loader: # label: (B, 1, D, H, W) integer map
|
|
107
|
+
logits = model(image) # (B, C, D, H, W); or a list for deep supervision
|
|
108
|
+
out = loss_fn(logits, label, return_components=True)
|
|
109
|
+
out["loss"].backward()
|
|
110
|
+
log(base=out["base"], cat=out["cat"], mil=out["mil"])
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
You can pick any loss by name, for example to compare losses from a config file:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from comploss import get_loss, list_losses, register_loss
|
|
117
|
+
list_losses()
|
|
118
|
+
loss_fn = get_loss("focal_tversky", deep_supervision=True) # takes lists of outputs/targets
|
|
119
|
+
register_loss("my_loss", MyLoss) # compare your own loss the same way
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
A runnable example with synthetic data is in [examples/train_pytorch.py](examples/train_pytorch.py).
|
|
123
|
+
|
|
124
|
+
### Options shared by the component losses
|
|
125
|
+
|
|
126
|
+
| option | meaning |
|
|
127
|
+
|---|---|
|
|
128
|
+
| `mode="union"` / `"per_class"` / `"auto"` | one object mask = any foreground, or one mask per class (multi-class) |
|
|
129
|
+
| `activation="sigmoid"` | region-based / multi-label outputs (binary target per channel) |
|
|
130
|
+
| `ignore_index=k` | voxels labelled `k` are ignored (never part of an object) |
|
|
131
|
+
| `connectivity=1` | 1 = face neighbours (6 in 3D, 4 in 2D), up to `ndim` = all neighbours |
|
|
132
|
+
| `components=` | precomputed GT components from `LabelComponentsd` in the data loader (avoids a GPU→CPU copy per step) |
|
|
133
|
+
|
|
134
|
+
CATMIL also takes `base_loss=` (your own voxel loss instead of DiceCE), `ds_mode="highest"` or
|
|
135
|
+
`"all"` (component terms on the full-resolution output only, or on every deep-supervision output),
|
|
136
|
+
and `cat_kwargs=dict(alpha, beta, gamma, eps_cc, w_bg)`.
|
|
137
|
+
|
|
138
|
+
The CATMIL defaults are the paper's values: alpha 0.3, beta 0.7, gamma 1, eps_cc 5, w_bg 0.01,
|
|
139
|
+
lambda_cat 0.1 (50-epoch warm-up), lambda_mil 0.2, connectivity 1.
|
|
140
|
+
|
|
141
|
+
## nnU-Net v2
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
pip install "comploss[nnunet]"
|
|
145
|
+
comploss nnunet install # puts a stub in nnunetv2/training/nnUNetTrainer/ (nnU-Net only looks there)
|
|
146
|
+
comploss nnunet status # shows which module each trainer resolves to
|
|
147
|
+
nnUNetv2_train DATASET 3d_fullres FOLD -tr nnUNetTrainerCATMIL
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
The trainers are `nnUNetTrainerCATMIL`, `nnUNetTrainerCAT`, `nnUNetTrainerMIL`,
|
|
151
|
+
`nnUNetTrainerCCDiceCE`, `nnUNetTrainerDiceCE`, `nnUNetTrainerTversky` and
|
|
152
|
+
`nnUNetTrainerFocalTversky`.
|
|
153
|
+
|
|
154
|
+
* The base term is nnU-Net's own loss (DiceCE, or Dice+BCE for regions), with nnU-Net's deep
|
|
155
|
+
supervision, DDP batch Dice and ignore label.
|
|
156
|
+
* The CAT warm-up follows `current_epoch`, including when you resume from a checkpoint.
|
|
157
|
+
* The component terms run in float32 even under AMP, and stay out of `torch.compile`.
|
|
158
|
+
* Tested with nnU-Net 2.1.1 and 2.8.1.
|
|
159
|
+
|
|
160
|
+
To change hyperparameters, write a subclass and put it in a file inside
|
|
161
|
+
`nnunetv2/training/nnUNetTrainer/`:
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
from comploss.integrations.nnunet import nnUNetTrainerCATMIL
|
|
165
|
+
|
|
166
|
+
class nnUNetTrainerCATMIL_lmil05(nnUNetTrainerCATMIL):
|
|
167
|
+
loss_lambda_mil = 0.5 # any loss_* attribute, see comploss/integrations/nnunet/__init__.py
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
For a quick test you can set environment variables instead, for example
|
|
171
|
+
`COMPLOSS_LAMBDA_MIL=0.5 nnUNetv2_train ...`. `COMPLOSS_NUM_EPOCHS` overrides the
|
|
172
|
+
epoch count.
|
|
173
|
+
|
|
174
|
+
`comploss nnunet uninstall` removes the stub. Run `install` again after you upgrade nnunetv2.
|
|
175
|
+
|
|
176
|
+
## Object-level evaluation
|
|
177
|
+
|
|
178
|
+
Voxel Dice hides missed small objects. A ground-truth object is a connected component, and it
|
|
179
|
+
counts as detected if any predicted voxel overlaps it.
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from comploss.metrics import object_detection_metrics, recall_by_size, object_table, object_size_profile
|
|
183
|
+
object_detection_metrics(gt, pred, spacing=(1, 1, 1)) # object F1/precision/recall, small-object recall, FP count, missed volume
|
|
184
|
+
recall_by_size(gt, pred) # tiny <=10, small <=50, medium <=200, large voxels
|
|
185
|
+
object_table(gt, pred, prob) # one row per object: size, detected, coverage, max prob
|
|
186
|
+
object_size_profile([gt1, gt2, ...]) # object-size distribution of a dataset
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
For medical imaging, `lesion_detection_metrics`, `lesion_table` and `lesion_size_profile` return
|
|
190
|
+
the same values with lesion key names (`lesion_recall`, `gt_lesion_count`, ...), as in the CATMIL
|
|
191
|
+
paper. `SmallLesionMILLoss`, the paper's name for `ComponentMILLoss`, also still works.
|
|
192
|
+
|
|
193
|
+
## Command line
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
comploss profile path/to/labelsTr # object-size distribution: does your dataset have many small objects?
|
|
197
|
+
comploss bench --shape 2 2 128 128 128 --device cuda # ms per forward+backward for each loss
|
|
198
|
+
comploss losses
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## Tests
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
pip install -e ".[test]"
|
|
205
|
+
pytest # the nnU-Net tests run when nnunetv2 is installed
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
`tests/_reference_losses.py` and `tests/_reference_metrics.py` hold frozen copies of the
|
|
209
|
+
research code. The parity tests compare values and gradients against them, against nnU-Net's
|
|
210
|
+
`DC_and_CE_loss` / `DC_and_BCE_loss`, and against MONAI's `TverskyLoss`.
|
|
211
|
+
|
|
212
|
+
## Adding a loss
|
|
213
|
+
|
|
214
|
+
1. Put a component-aware loss in `src/comploss/losses/component/`, or a voxel-wise one in
|
|
215
|
+
`losses/voxel/`, using the `forward(logits, target)` interface. Use
|
|
216
|
+
`comploss.components` for labelling and `losses._utils.binary_problems` for the
|
|
217
|
+
softmax / sigmoid / ignore-label handling.
|
|
218
|
+
2. Register it in `losses/registry.py`.
|
|
219
|
+
3. If you port it from published code, add a frozen copy of that code to `tests/` and a parity
|
|
220
|
+
test. Cite the paper in the docstring and in the table above.
|
|
221
|
+
|
|
222
|
+
## Citation
|
|
223
|
+
|
|
224
|
+
If you use this package, please cite it (see [CITATION.cff](CITATION.cff)). If you use CATMIL,
|
|
225
|
+
CAT or MIL, please also cite:
|
|
226
|
+
|
|
227
|
+
```bibtex
|
|
228
|
+
@article{luu2026catmil,
|
|
229
|
+
title = {Component-Adaptive and Lesion-Level Supervision for Improved Small Structure Segmentation in Brain MRI},
|
|
230
|
+
author = {Luu, Minh Sao Khue and Pavlovskiy, Evgeniy N. and Tuchinov, Bair N.},
|
|
231
|
+
journal = {arXiv preprint arXiv:2604.08015},
|
|
232
|
+
year = {2026}
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
If you use CC-DiceCE, please cite Bouteille et al., ISBI 2026 (arXiv:2511.17146).
|
|
237
|
+
|
|
238
|
+
The code to reproduce the CATMIL paper is at
|
|
239
|
+
[github.com/luumsk/SmallLesionMRI](https://github.com/luumsk/SmallLesionMRI).
|
|
240
|
+
|
|
241
|
+
## License
|
|
242
|
+
|
|
243
|
+
MIT, see [LICENSE](LICENSE).
|
comploss-0.1.0/README.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# comploss
|
|
2
|
+
|
|
3
|
+
**Component-aware loss functions and object-level metrics for segmentation in PyTorch.**
|
|
4
|
+
|
|
5
|
+
Voxel-wise losses such as Dice, cross entropy and Tversky sum over voxels, so a few large
|
|
6
|
+
objects dominate the gradient. A missed 5-voxel object barely changes the loss. That matters
|
|
7
|
+
whenever an image holds many objects of very different sizes: small lesions in MRI, nodules in
|
|
8
|
+
CT, cells and nuclei in microscopy, defects in industrial inspection, small buildings or
|
|
9
|
+
vehicles in remote sensing.
|
|
10
|
+
|
|
11
|
+
The losses in `comploss` are defined over the **connected components** of the ground
|
|
12
|
+
truth, so every object counts. The package includes:
|
|
13
|
+
|
|
14
|
+
* **Component-aware losses**: CATMIL and its two terms, CAT and MIL (Luu et al.), and CC-DiceCE
|
|
15
|
+
(Bouteille et al., ISBI 2026).
|
|
16
|
+
* **Voxel-wise baselines** with the same interface: DiceCE (identical to nnU-Net's default),
|
|
17
|
+
Tversky (identical to MONAI's), Focal Tversky.
|
|
18
|
+
* **Object-level metrics**: object recall, precision and F1, recall by object size, a per-object
|
|
19
|
+
table, size profiling of a dataset.
|
|
20
|
+
* **Integrations**: nnU-Net v2 trainers for every loss, MONAI-style transforms, deep supervision.
|
|
21
|
+
|
|
22
|
+
All losses take raw logits `(B, C, *spatial)` and integer targets `(B, 1, *spatial)` (the
|
|
23
|
+
nnU-Net layout), in 2D or 3D. Tests check every port against its reference implementation
|
|
24
|
+
(values and gradients).
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install comploss # torch, numpy, scipy
|
|
30
|
+
pip install "comploss[nnunet]" # + nnU-Net v2 trainers
|
|
31
|
+
pip install "comploss[fast-cc]" # + faster connected components (cc3d)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
From source (for development):
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
git clone https://github.com/luumsk/comploss && cd comploss
|
|
38
|
+
pip install -e ".[dev,nnunet,fast-cc]"
|
|
39
|
+
pytest
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Available losses
|
|
43
|
+
|
|
44
|
+
| name (`get_loss`) | class | type | reference |
|
|
45
|
+
|---|---|---|---|
|
|
46
|
+
| `catmil` | `CATMILLoss` | DiceCE + CAT + MIL | Luu et al., arXiv:2604.08015 |
|
|
47
|
+
| `cat` | `ComponentAdaptiveTverskyLoss` | component-weighted Tversky | Luu et al. |
|
|
48
|
+
| `mil` | `ComponentMILLoss` | one bag per object, `-log max p` | Luu et al. |
|
|
49
|
+
| `cc_dice_ce` | `CCDiceCEGlobalLoss` | Voronoi component DiceCE + global DiceCE | Bouteille et al., arXiv:2511.17146 |
|
|
50
|
+
| `cc_dice_ce_component` | `CCDiceCELoss` | Voronoi component DiceCE only | Bouteille et al. |
|
|
51
|
+
| `dice_ce` | `DiceCELoss` | voxel-wise (nnU-Net default) | Isensee et al. |
|
|
52
|
+
| `tversky` | `TverskyLoss` | voxel-wise | Salehi et al. |
|
|
53
|
+
| `focal_tversky` | `FocalTverskyLoss` | voxel-wise | Abraham & Khan |
|
|
54
|
+
|
|
55
|
+
## Usage in PyTorch or MONAI
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from comploss import get_loss
|
|
59
|
+
|
|
60
|
+
loss_fn = get_loss("catmil") # DiceCE + 0.1*CAT (linear warm-up over 50 epochs) + 0.2*MIL
|
|
61
|
+
for epoch in range(n_epochs):
|
|
62
|
+
loss_fn.set_epoch(epoch) # drives the CAT warm-up
|
|
63
|
+
for image, label in loader: # label: (B, 1, D, H, W) integer map
|
|
64
|
+
logits = model(image) # (B, C, D, H, W); or a list for deep supervision
|
|
65
|
+
out = loss_fn(logits, label, return_components=True)
|
|
66
|
+
out["loss"].backward()
|
|
67
|
+
log(base=out["base"], cat=out["cat"], mil=out["mil"])
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
You can pick any loss by name, for example to compare losses from a config file:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from comploss import get_loss, list_losses, register_loss
|
|
74
|
+
list_losses()
|
|
75
|
+
loss_fn = get_loss("focal_tversky", deep_supervision=True) # takes lists of outputs/targets
|
|
76
|
+
register_loss("my_loss", MyLoss) # compare your own loss the same way
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
A runnable example with synthetic data is in [examples/train_pytorch.py](examples/train_pytorch.py).
|
|
80
|
+
|
|
81
|
+
### Options shared by the component losses
|
|
82
|
+
|
|
83
|
+
| option | meaning |
|
|
84
|
+
|---|---|
|
|
85
|
+
| `mode="union"` / `"per_class"` / `"auto"` | one object mask = any foreground, or one mask per class (multi-class) |
|
|
86
|
+
| `activation="sigmoid"` | region-based / multi-label outputs (binary target per channel) |
|
|
87
|
+
| `ignore_index=k` | voxels labelled `k` are ignored (never part of an object) |
|
|
88
|
+
| `connectivity=1` | 1 = face neighbours (6 in 3D, 4 in 2D), up to `ndim` = all neighbours |
|
|
89
|
+
| `components=` | precomputed GT components from `LabelComponentsd` in the data loader (avoids a GPU→CPU copy per step) |
|
|
90
|
+
|
|
91
|
+
CATMIL also takes `base_loss=` (your own voxel loss instead of DiceCE), `ds_mode="highest"` or
|
|
92
|
+
`"all"` (component terms on the full-resolution output only, or on every deep-supervision output),
|
|
93
|
+
and `cat_kwargs=dict(alpha, beta, gamma, eps_cc, w_bg)`.
|
|
94
|
+
|
|
95
|
+
The CATMIL defaults are the paper's values: alpha 0.3, beta 0.7, gamma 1, eps_cc 5, w_bg 0.01,
|
|
96
|
+
lambda_cat 0.1 (50-epoch warm-up), lambda_mil 0.2, connectivity 1.
|
|
97
|
+
|
|
98
|
+
## nnU-Net v2
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
pip install "comploss[nnunet]"
|
|
102
|
+
comploss nnunet install # puts a stub in nnunetv2/training/nnUNetTrainer/ (nnU-Net only looks there)
|
|
103
|
+
comploss nnunet status # shows which module each trainer resolves to
|
|
104
|
+
nnUNetv2_train DATASET 3d_fullres FOLD -tr nnUNetTrainerCATMIL
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
The trainers are `nnUNetTrainerCATMIL`, `nnUNetTrainerCAT`, `nnUNetTrainerMIL`,
|
|
108
|
+
`nnUNetTrainerCCDiceCE`, `nnUNetTrainerDiceCE`, `nnUNetTrainerTversky` and
|
|
109
|
+
`nnUNetTrainerFocalTversky`.
|
|
110
|
+
|
|
111
|
+
* The base term is nnU-Net's own loss (DiceCE, or Dice+BCE for regions), with nnU-Net's deep
|
|
112
|
+
supervision, DDP batch Dice and ignore label.
|
|
113
|
+
* The CAT warm-up follows `current_epoch`, including when you resume from a checkpoint.
|
|
114
|
+
* The component terms run in float32 even under AMP, and stay out of `torch.compile`.
|
|
115
|
+
* Tested with nnU-Net 2.1.1 and 2.8.1.
|
|
116
|
+
|
|
117
|
+
To change hyperparameters, write a subclass and put it in a file inside
|
|
118
|
+
`nnunetv2/training/nnUNetTrainer/`:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from comploss.integrations.nnunet import nnUNetTrainerCATMIL
|
|
122
|
+
|
|
123
|
+
class nnUNetTrainerCATMIL_lmil05(nnUNetTrainerCATMIL):
|
|
124
|
+
loss_lambda_mil = 0.5 # any loss_* attribute, see comploss/integrations/nnunet/__init__.py
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
For a quick test you can set environment variables instead, for example
|
|
128
|
+
`COMPLOSS_LAMBDA_MIL=0.5 nnUNetv2_train ...`. `COMPLOSS_NUM_EPOCHS` overrides the
|
|
129
|
+
epoch count.
|
|
130
|
+
|
|
131
|
+
`comploss nnunet uninstall` removes the stub. Run `install` again after you upgrade nnunetv2.
|
|
132
|
+
|
|
133
|
+
## Object-level evaluation
|
|
134
|
+
|
|
135
|
+
Voxel Dice hides missed small objects. A ground-truth object is a connected component, and it
|
|
136
|
+
counts as detected if any predicted voxel overlaps it.
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
from comploss.metrics import object_detection_metrics, recall_by_size, object_table, object_size_profile
|
|
140
|
+
object_detection_metrics(gt, pred, spacing=(1, 1, 1)) # object F1/precision/recall, small-object recall, FP count, missed volume
|
|
141
|
+
recall_by_size(gt, pred) # tiny <=10, small <=50, medium <=200, large voxels
|
|
142
|
+
object_table(gt, pred, prob) # one row per object: size, detected, coverage, max prob
|
|
143
|
+
object_size_profile([gt1, gt2, ...]) # object-size distribution of a dataset
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
For medical imaging, `lesion_detection_metrics`, `lesion_table` and `lesion_size_profile` return
|
|
147
|
+
the same values with lesion key names (`lesion_recall`, `gt_lesion_count`, ...), as in the CATMIL
|
|
148
|
+
paper. `SmallLesionMILLoss`, the paper's name for `ComponentMILLoss`, also still works.
|
|
149
|
+
|
|
150
|
+
## Command line
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
comploss profile path/to/labelsTr # object-size distribution: does your dataset have many small objects?
|
|
154
|
+
comploss bench --shape 2 2 128 128 128 --device cuda # ms per forward+backward for each loss
|
|
155
|
+
comploss losses
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Tests
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
pip install -e ".[test]"
|
|
162
|
+
pytest # the nnU-Net tests run when nnunetv2 is installed
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
`tests/_reference_losses.py` and `tests/_reference_metrics.py` hold frozen copies of the
|
|
166
|
+
research code. The parity tests compare values and gradients against them, against nnU-Net's
|
|
167
|
+
`DC_and_CE_loss` / `DC_and_BCE_loss`, and against MONAI's `TverskyLoss`.
|
|
168
|
+
|
|
169
|
+
## Adding a loss
|
|
170
|
+
|
|
171
|
+
1. Put a component-aware loss in `src/comploss/losses/component/`, or a voxel-wise one in
|
|
172
|
+
`losses/voxel/`, using the `forward(logits, target)` interface. Use
|
|
173
|
+
`comploss.components` for labelling and `losses._utils.binary_problems` for the
|
|
174
|
+
softmax / sigmoid / ignore-label handling.
|
|
175
|
+
2. Register it in `losses/registry.py`.
|
|
176
|
+
3. If you port it from published code, add a frozen copy of that code to `tests/` and a parity
|
|
177
|
+
test. Cite the paper in the docstring and in the table above.
|
|
178
|
+
|
|
179
|
+
## Citation
|
|
180
|
+
|
|
181
|
+
If you use this package, please cite it (see [CITATION.cff](CITATION.cff)). If you use CATMIL,
|
|
182
|
+
CAT or MIL, please also cite:
|
|
183
|
+
|
|
184
|
+
```bibtex
|
|
185
|
+
@article{luu2026catmil,
|
|
186
|
+
title = {Component-Adaptive and Lesion-Level Supervision for Improved Small Structure Segmentation in Brain MRI},
|
|
187
|
+
author = {Luu, Minh Sao Khue and Pavlovskiy, Evgeniy N. and Tuchinov, Bair N.},
|
|
188
|
+
journal = {arXiv preprint arXiv:2604.08015},
|
|
189
|
+
year = {2026}
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
If you use CC-DiceCE, please cite Bouteille et al., ISBI 2026 (arXiv:2511.17146).
|
|
194
|
+
|
|
195
|
+
The code to reproduce the CATMIL paper is at
|
|
196
|
+
[github.com/luumsk/SmallLesionMRI](https://github.com/luumsk/SmallLesionMRI).
|
|
197
|
+
|
|
198
|
+
## License
|
|
199
|
+
|
|
200
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "comploss"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Component-aware loss functions and object-level metrics for segmenting small and multiple structures (CATMIL, CC-DiceCE, ...), with nnU-Net v2 and MONAI support."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
authors = [{ name = "Minh Sao Khue Luu" }]
|
|
12
|
+
maintainers = [{ name = "Minh Sao Khue Luu" }]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
dependencies = ["torch>=2.0", "numpy", "scipy"]
|
|
15
|
+
keywords = ["segmentation", "loss function", "connected components", "small objects", "instance imbalance",
|
|
16
|
+
"medical image segmentation", "nnU-Net", "pytorch"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Intended Audience :: Science/Research",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
22
|
+
"Topic :: Scientific/Engineering :: Image Processing",
|
|
23
|
+
"Topic :: Scientific/Engineering :: Medical Science Apps.",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
nnunet = ["nnunetv2>=2.1"]
|
|
28
|
+
monai = ["monai>=1.3"]
|
|
29
|
+
fast-cc = ["connected-components-3d>=3.12"]
|
|
30
|
+
io = ["nibabel"]
|
|
31
|
+
test = ["pytest", "monai>=1.3"]
|
|
32
|
+
dev = ["pytest", "monai>=1.3", "ruff", "build", "twine"]
|
|
33
|
+
|
|
34
|
+
[project.scripts]
|
|
35
|
+
comploss = "comploss.cli:main"
|
|
36
|
+
|
|
37
|
+
[project.urls]
|
|
38
|
+
Repository = "https://github.com/luumsk/comploss"
|
|
39
|
+
Issues = "https://github.com/luumsk/comploss/issues"
|
|
40
|
+
Changelog = "https://github.com/luumsk/comploss/blob/main/CHANGELOG.md"
|
|
41
|
+
"CATMIL paper code" = "https://github.com/luumsk/SmallLesionMRI"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.packages.find]
|
|
44
|
+
where = ["src"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
testpaths = ["tests"]
|
|
48
|
+
|
|
49
|
+
[tool.ruff]
|
|
50
|
+
line-length = 120
|
|
51
|
+
# frozen verbatim copies of research code, kept as-is for the parity tests
|
|
52
|
+
extend-exclude = ["tests/_reference_losses.py", "tests/_reference_metrics.py"]
|
comploss-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""comploss: component-aware losses and object-level metrics for segmentation.
|
|
2
|
+
|
|
3
|
+
Voxel-wise losses (Dice, cross entropy, Tversky) are dominated by large objects, so small
|
|
4
|
+
structures can be missed at almost no cost. The losses here are defined over the connected
|
|
5
|
+
components of the ground truth instead, so every object counts.
|
|
6
|
+
|
|
7
|
+
Quick start::
|
|
8
|
+
|
|
9
|
+
from comploss import get_loss
|
|
10
|
+
loss_fn = get_loss("catmil") # DiceCE + 0.1 * CAT (50-epoch warm-up) + 0.2 * MIL
|
|
11
|
+
for epoch in range(n_epochs):
|
|
12
|
+
loss_fn.set_epoch(epoch)
|
|
13
|
+
...
|
|
14
|
+
loss = loss_fn(logits, labels) # logits (B, C, *spatial), labels (B, 1, *spatial)
|
|
15
|
+
"""
|
|
16
|
+
from .components import label_components, set_backend
|
|
17
|
+
from .losses import * # noqa: F401,F403
|
|
18
|
+
from .losses import __all__ as _losses_all
|
|
19
|
+
from .transforms import LabelComponents, LabelComponentsd
|
|
20
|
+
|
|
21
|
+
__version__ = "0.1.0"
|
|
22
|
+
__all__ = list(_losses_all) + ["LabelComponents", "LabelComponentsd", "label_components", "set_backend"]
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Command line: ``comploss losses | profile <labels_dir> | bench | nnunet {install,uninstall,status}``."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _load_mask(path: Path) -> np.ndarray:
|
|
14
|
+
name = path.name
|
|
15
|
+
if name.endswith((".nii.gz", ".nii")):
|
|
16
|
+
try:
|
|
17
|
+
import nibabel as nib
|
|
18
|
+
except ImportError as e: # pragma: no cover
|
|
19
|
+
raise SystemExit("reading NIfTI needs nibabel: pip install 'comploss[io]'") from e
|
|
20
|
+
return np.asarray(nib.load(str(path)).dataobj) > 0
|
|
21
|
+
if name.endswith(".npy"):
|
|
22
|
+
return np.load(path) > 0
|
|
23
|
+
if name.endswith(".npz"):
|
|
24
|
+
with np.load(path) as z:
|
|
25
|
+
return z[z.files[0]] > 0
|
|
26
|
+
raise ValueError(f"unsupported file {path}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def cmd_profile(args) -> int:
|
|
30
|
+
from .metrics import object_size_profile
|
|
31
|
+
files = sorted(p for p in Path(args.labels_dir).iterdir()
|
|
32
|
+
if p.name.endswith((".nii.gz", ".nii", ".npy", ".npz")))
|
|
33
|
+
if not files:
|
|
34
|
+
print(f"no label files in {args.labels_dir}", file=sys.stderr)
|
|
35
|
+
return 1
|
|
36
|
+
prof = object_size_profile([_load_mask(p) for p in files], connectivity=args.connectivity)
|
|
37
|
+
if args.json:
|
|
38
|
+
print(json.dumps(prof, indent=2))
|
|
39
|
+
return 0
|
|
40
|
+
print(f"{int(prof['cases'])} cases, {int(prof['objects'])} objects, "
|
|
41
|
+
f"median size {prof['median_size_vox']:.0f} voxels")
|
|
42
|
+
for b in ("tiny", "small", "medium", "large"):
|
|
43
|
+
print(f" {b:<7}{int(prof[f'n_{b}']):>7} {100 * prof[f'frac_{b}']:5.1f}%")
|
|
44
|
+
small = prof["frac_tiny"] + prof["frac_small"]
|
|
45
|
+
print(f"objects <= 50 voxels: {100 * small:.1f}%"
|
|
46
|
+
+ (" -> many small objects; component-aware losses are designed for this case." if small >= 0.3 else ""))
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cmd_losses(_args) -> int:
|
|
51
|
+
from .losses import list_losses
|
|
52
|
+
print("\n".join(list_losses()))
|
|
53
|
+
return 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def cmd_bench(args) -> int:
|
|
57
|
+
import torch
|
|
58
|
+
from .losses import get_loss
|
|
59
|
+
torch.manual_seed(0)
|
|
60
|
+
b, c, *sp = args.shape
|
|
61
|
+
dev = torch.device(args.device)
|
|
62
|
+
logits = torch.randn(b, c, *sp, device=dev, requires_grad=True)
|
|
63
|
+
# random sparse "objects": blobs of a few voxels
|
|
64
|
+
tgt = (torch.rand(b, 1, *sp, device=dev) > 0.999).float()
|
|
65
|
+
tgt = torch.nn.functional.max_pool3d(tgt, 3, 1, 1) if len(sp) == 3 else torch.nn.functional.max_pool2d(tgt, 3, 1, 1)
|
|
66
|
+
names = args.losses or ["dice_ce", "tversky", "focal_tversky", "cc_dice_ce", "cat", "mil", "catmil"]
|
|
67
|
+
print(f"input {tuple(logits.shape)} on {dev}, {args.iters} iterations (forward + backward)")
|
|
68
|
+
for name in names:
|
|
69
|
+
kw = {"cat_warmup_epochs": 0} if name == "catmil" else {}
|
|
70
|
+
loss_fn = get_loss(name, **kw)
|
|
71
|
+
for i in range(args.warmup + args.iters):
|
|
72
|
+
if i == args.warmup:
|
|
73
|
+
if dev.type == "cuda":
|
|
74
|
+
torch.cuda.synchronize()
|
|
75
|
+
t0 = time.perf_counter()
|
|
76
|
+
logits.grad = None
|
|
77
|
+
loss_fn(logits, tgt).backward()
|
|
78
|
+
if dev.type == "cuda":
|
|
79
|
+
torch.cuda.synchronize()
|
|
80
|
+
print(f" {name:<16}{1000 * (time.perf_counter() - t0) / args.iters:9.1f} ms/iter")
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def cmd_nnunet(args) -> int:
|
|
85
|
+
from .integrations.nnunet import install as inst
|
|
86
|
+
return {"install": inst.install, "uninstall": inst.uninstall, "status": inst.status}[args.action]()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def main(argv=None) -> int:
|
|
90
|
+
ap = argparse.ArgumentParser(prog="comploss", description=__doc__)
|
|
91
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
92
|
+
p = sub.add_parser("profile", help="object-size distribution of a folder of GT masks")
|
|
93
|
+
p.add_argument("labels_dir")
|
|
94
|
+
p.add_argument("--connectivity", type=int, default=1)
|
|
95
|
+
p.add_argument("--json", action="store_true")
|
|
96
|
+
p.set_defaults(func=cmd_profile)
|
|
97
|
+
p = sub.add_parser("losses", help="list loss names for get_loss()")
|
|
98
|
+
p.set_defaults(func=cmd_losses)
|
|
99
|
+
p = sub.add_parser("bench", help="time forward + backward of each loss")
|
|
100
|
+
p.add_argument("--shape", type=int, nargs="+", default=[2, 2, 64, 64, 64], help="B C *spatial")
|
|
101
|
+
p.add_argument("--device", default="cuda" if __import__("torch").cuda.is_available() else "cpu")
|
|
102
|
+
p.add_argument("--iters", type=int, default=10)
|
|
103
|
+
p.add_argument("--warmup", type=int, default=2)
|
|
104
|
+
p.add_argument("--losses", nargs="*")
|
|
105
|
+
p.set_defaults(func=cmd_bench)
|
|
106
|
+
p = sub.add_parser("nnunet", help="make the nnU-Net trainers visible to nnUNetv2_train")
|
|
107
|
+
p.add_argument("action", choices=["install", "uninstall", "status"])
|
|
108
|
+
p.set_defaults(func=cmd_nnunet)
|
|
109
|
+
args = ap.parse_args(argv)
|
|
110
|
+
return args.func(args)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
if __name__ == "__main__":
|
|
114
|
+
sys.exit(main())
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""Connected-component utilities shared by the losses, transforms and metrics."""
|
|
2
|
+
from .labeling import label_batch, label_components, set_backend
|
|
3
|
+
from .voronoi import voronoi_components
|
|
4
|
+
|
|
5
|
+
__all__ = ["label_batch", "label_components", "set_backend", "voronoi_components"]
|