nnunet-lite 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mirshahi Lab
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.
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.4
2
+ Name: nnunet-lite
3
+ Version: 0.1.0
4
+ Summary: Convert nnU-Net models to a standalone safetensors bundle and run nnU-Net-quality inference without nnU-Net
5
+ Author: idinsmore1
6
+ Author-email: idinsmore1 <irdinsmore1@geisinger.edu>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: connected-components-3d>=4.1.1
10
+ Requires-Dist: fastmorph>=1.10.0
11
+ Requires-Dist: fastremap>=1.21.0
12
+ Requires-Dist: nibabel>=5.4.2
13
+ Requires-Dist: numpy>=2.4.6
14
+ Requires-Dist: safetensors>=0.8.0
15
+ Requires-Dist: scipy>=1.17.1
16
+ Requires-Dist: torch>=2.9
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+
20
+ # nnunet-lite
21
+
22
+ Run [nnU-Net](https://github.com/MIC-DKFZ/nnUNet) models without nnU-Net.
23
+
24
+ `nnunet-lite` converts a trained nnU-Net model into a small, self-contained **bundle** (`bundle.json` + `weights.safetensors`) and provides an inference API that reproduces nnU-Net's preprocessing, sliding-window prediction and resampling. Segmentations match nnU-Net within a small tolerance, with no `nnunetv2` dependency at inference time.
25
+
26
+ It is a library for conversion and inference, not a serving platform: it makes no attempt at cloud deployment, queuing or orchestration.
27
+
28
+ ## Why
29
+
30
+ - **Independent of nnU-Net.** A bundle needs only PyTorch, NumPy, SciPy, nibabel and safetensors.
31
+ - **Tensor in, tensor out.** The network is a plain `torch.nn.Module`. Predictions accept paths, bytes, file objects, NIfTI images or raw arrays, so nothing has to touch the disk.
32
+ - **Safe to load.** Weights are stored as safetensors and checked against a SHA-256 recorded in `bundle.json`. Conversion reads nnU-Net checkpoints with `weights_only=True` and refuses anything else in the pickle.
33
+ - **Fast preprocessing.** An optional GPU path is roughly 12–40x faster than nnU-Net's CPU preprocessing, with an exact CPU path when you need bit-equality.
34
+
35
+ ## Installation
36
+
37
+ The project uses [`uv`](https://docs.astral.sh/uv/). Python 3.11+ is required.
38
+
39
+ ```bash
40
+ git clone <repo-url> && cd nnunet_lite
41
+ uv sync
42
+ ```
43
+
44
+ ## Quick start
45
+
46
+ ```python
47
+ import nnunet_lite as nl
48
+
49
+ # 1. Convert once. Point at the nnU-Net trainer__plans__configuration folder.
50
+ nl.convert(
51
+ "nnUNet_results/Dataset485_x/nnUNetTrainer__nnUNetPlans__3d_fullres",
52
+ output_dir="bundles/dataset485",
53
+ )
54
+
55
+ # 2. Predict anywhere, with no nnU-Net files or dependencies.
56
+ predictor = nl.Predictor("bundles/dataset485") # CUDA if available
57
+ result = predictor.predict("ct.nii.gz", qc=True)
58
+
59
+ result.segmentation # CPU uint8 tensor on the input's grid
60
+ result.qc["muscle"].estimated_dice # optional per-label quality control
61
+ result.save("seg.nii.gz")
62
+ ```
63
+
64
+ ## Capabilities
65
+
66
+ ### Conversion
67
+
68
+ ```python
69
+ bundle = nl.convert(model_dir) # convert in memory
70
+ bundle = nl.convert(model_dir, output_dir="bundles/x") # convert and save
71
+ bundle.save("bundles/x") # or save later
72
+ bundle = nl.load_bundle("bundles/x", device="cuda") # load, verifying weights
73
+ config = nl.load_config("bundles/x") # bundle.json only, no weights
74
+ ```
75
+
76
+ `convert` takes `fold`, `checkpoint`, `overwrite`, `device`, and an `inference` override for the sliding-window settings (default: nnU-Net's own).
77
+
78
+ ### Preprocessing
79
+
80
+ `nl.preprocess(volume, spacing, config.preprocessing)` runs nnU-Net's pipeline: transpose, crop to nonzero, normalize, resample. It needs only the config, not the weights.
81
+
82
+ | | CPU (`device="cpu"`) | GPU (default when CUDA is available) |
83
+ |---|---|---|
84
+ | Match to nnU-Net | Byte-equal to `DefaultPreprocessor.run_case_npy` | Within float32 rounding |
85
+ | Max difference from CPU path | — | ~5e-7 on normalized data |
86
+ | Voxels bit-identical to CPU | 100% | ~93% |
87
+ | Crop box and shapes | nnU-Net's | Identical to CPU |
88
+
89
+ The GPU path applies spline resampling as one float64 matrix product per axis, using matrices from the same scipy call the CPU path makes. If it fails for any reason (out of memory, CUDA error, non-finite input) it emits a `RuntimeWarning` and falls back to the exact CPU path.
90
+
91
+ Measured on an RTX 2080 Ti, resampling to 1.5 mm:
92
+
93
+ | Input | CPU | GPU | Speedup | Peak GPU memory |
94
+ |---|---|---|---|---|
95
+ | 300×512×512 at 0.8 mm | 8.76 s | 0.30 s | 29x | 1.3 GB |
96
+ | 80×512×512, 5 mm slices | 2.32 s | 0.11 s | 22x | 0.6 GB |
97
+ | 600×512×512 at 1×0.7 mm | 17.68 s | 0.45 s | 39x | 3.6 GB |
98
+ | 2-channel MRI 150×240×240, masked z-score | 2.82 s | 0.24 s | 12x | 0.3 GB |
99
+
100
+ Use the default for throughput; use `device="cpu"` when you need exactly what nnU-Net would produce, for example when validating a conversion. The effect of GPU rounding on final segmentations has not been measured yet.
101
+
102
+ ### Prediction
103
+
104
+ ```python
105
+ predictor.predict("ct.nii.gz") # path
106
+ predictor.predict(s3_body_bytes) # bytes or binary file object, nothing written to disk
107
+ predictor.predict(volume, spacing) # raw (C, X, Y, Z) array or tensor plus spacing
108
+ predictor.predict(source, qc=["muscle"], mirror=True)
109
+ ```
110
+
111
+ - Preprocessing always runs inside `predict` using the bundle's own configuration. There is no entry point for pre-preprocessed tensors.
112
+ - **Sliding window** is a port of `nnUNetPredictor`: tile positions, Gaussian weighting, zero padding, float16 accumulation and CUDA autocast. On CUDA out-of-memory it warns and moves accumulation to the CPU. 2D bundles run slice by slice.
113
+ - **Restoring** resamples logits to the cropped input shape, argmaxes, un-crops and transposes back, one class at a time so full-resolution logits for all classes are never held at once.
114
+ - **Mirroring** (test-time augmentation) is **off** by default, unlike nnU-Net. Pass `mirror=True` to enable it.
115
+ - **Output**: `result.save(path)` and `result.to_bytes()` write NIfTI on the input file's own grid and orientation, using the smallest unsigned integer type that holds the model's highest label. These need a file input, since array inputs carry no affine.
116
+ - **Inputs**: `.nii` and `.nii.gz` are both accepted, including from memory, via nnU-Net's `NibabelIO` and `NibabelIOWithReorient` readers. Other readers work for arrays only.
117
+
118
+ ### Quality control
119
+
120
+ `qc=True` (every foreground label) or a list of label names or ids adds per-label statistics. QC never changes the segmentation and costs nothing unless requested.
121
+
122
+ - **Segmentation stats** (26-connected components): `voxel_count`, `component_count`, `largest_component_fraction`, `small_component_voxel_counts`, `touches_boundary`.
123
+ - **Confidence stats** (softmax at network resolution): `estimated_dice`, `mean_margin`, `low_margin_fraction`, `mean_entropy`, `network_voxel_count`.
124
+
125
+ `estimated_dice` is **uncalibrated**: it is the raw confidence-based estimate at temperature 1. Per-model temperatures and calibration against true Dice are not implemented yet, so treat it as a relative signal, not a Dice value.
126
+
127
+ ### Multiple models on one input
128
+
129
+ ```python
130
+ multi = nl.MultiPredictor({"299": "bundles/dataset299", "485": "bundles/dataset485"})
131
+ results = multi.predict("ct.nii.gz", qc=True) # dict[str, PredictionResult]
132
+ ```
133
+
134
+ The input is parsed once and preprocessed once per distinct preprocessing config. All networks stay on the device; models run one after another.
135
+
136
+ ## Constraints
137
+
138
+ **Models**
139
+ - Architectures: `PlainConvUNet` and `ResidualEncoderUNet`, 2D and 3D, with InstanceNorm, LeakyReLU or ReLU, and no dropout. Legacy and `architecture`-style plans, including `inherits_from`, are supported.
140
+ - One fold per bundle. No ensembling across folds.
141
+ - Not supported (raises `NotImplementedError`): cascade configurations, region-based labels, the ignore label.
142
+
143
+ **Preprocessing**
144
+ - Normalization: `CTNormalization`, `ZScoreNormalization` (with and without mask), `RescaleTo01Normalization`, `RGBTo01Normalization`, `NoNormalization`.
145
+ - Resampling: only nnU-Net's default, `resample_data_or_seg_to_shape`. Others raise `NotImplementedError`.
146
+ - Array inputs must use the axis and spacing order nnU-Net's reader produced for the model, recorded as `config.preprocessing.image_reader`. For example, the nibabel readers give `(z, y, x)` with reversed spacing. 2D images need a singleton first spatial axis, as in nnU-Net.
147
+ - Masked z-score still computes its hole-filled mask on the CPU, even on the GPU path.
148
+
149
+ **Scope**
150
+ - The target is nnU-Net-quality output within a low tolerance, not bitwise-identical segmentations. Network logits are tested bitwise-equal to nnU-Net's own network on CPU FP32 and CUDA autocast.
151
+ - Bundles record the sliding-window defaults (`tile_step_size=0.5`, Gaussian weighting) because nnU-Net keeps them outside its plans. Override them at conversion time if you need different values.
152
+ - Schema 1 bundles still load; saving always writes schema 2.
153
+
154
+ ## Development
155
+
156
+ ```bash
157
+ uv run pytest # synthetic nnU-Net folders, no nnunetv2 needed
158
+ uv run ruff check . && uv run ruff format .
159
+ uv run mypy
160
+ ```
161
+
162
+ Equivalence tests compare against nnU-Net itself and need `nnunetv2`, so they run in the leadup environment:
163
+
164
+ ```bash
165
+ PYTHONPATH=src packages/nnunet_model_conversion/.venv/bin/python -m pytest tests
166
+ ```
167
+
168
+ - `tests/test_nnunet_equivalence.py`: bitwise-equal logits (needs real model folders).
169
+ - `tests/test_nnunet_preprocessing_equivalence.py`: byte-equal preprocessing against `DefaultPreprocessor`.
170
+ - `tests/test_nnunet_prediction_equivalence.py`: whole-CT segmentations against `nnUNetPredictor` (needs CUDA and a test CT via `NNUNET_LITE_TEST_IMAGE`).
171
+
172
+ The earlier speed, accuracy and precision work behind this library lives in `packages/nnunet_model_conversion`.
@@ -0,0 +1,153 @@
1
+ # nnunet-lite
2
+
3
+ Run [nnU-Net](https://github.com/MIC-DKFZ/nnUNet) models without nnU-Net.
4
+
5
+ `nnunet-lite` converts a trained nnU-Net model into a small, self-contained **bundle** (`bundle.json` + `weights.safetensors`) and provides an inference API that reproduces nnU-Net's preprocessing, sliding-window prediction and resampling. Segmentations match nnU-Net within a small tolerance, with no `nnunetv2` dependency at inference time.
6
+
7
+ It is a library for conversion and inference, not a serving platform: it makes no attempt at cloud deployment, queuing or orchestration.
8
+
9
+ ## Why
10
+
11
+ - **Independent of nnU-Net.** A bundle needs only PyTorch, NumPy, SciPy, nibabel and safetensors.
12
+ - **Tensor in, tensor out.** The network is a plain `torch.nn.Module`. Predictions accept paths, bytes, file objects, NIfTI images or raw arrays, so nothing has to touch the disk.
13
+ - **Safe to load.** Weights are stored as safetensors and checked against a SHA-256 recorded in `bundle.json`. Conversion reads nnU-Net checkpoints with `weights_only=True` and refuses anything else in the pickle.
14
+ - **Fast preprocessing.** An optional GPU path is roughly 12–40x faster than nnU-Net's CPU preprocessing, with an exact CPU path when you need bit-equality.
15
+
16
+ ## Installation
17
+
18
+ The project uses [`uv`](https://docs.astral.sh/uv/). Python 3.11+ is required.
19
+
20
+ ```bash
21
+ git clone <repo-url> && cd nnunet_lite
22
+ uv sync
23
+ ```
24
+
25
+ ## Quick start
26
+
27
+ ```python
28
+ import nnunet_lite as nl
29
+
30
+ # 1. Convert once. Point at the nnU-Net trainer__plans__configuration folder.
31
+ nl.convert(
32
+ "nnUNet_results/Dataset485_x/nnUNetTrainer__nnUNetPlans__3d_fullres",
33
+ output_dir="bundles/dataset485",
34
+ )
35
+
36
+ # 2. Predict anywhere, with no nnU-Net files or dependencies.
37
+ predictor = nl.Predictor("bundles/dataset485") # CUDA if available
38
+ result = predictor.predict("ct.nii.gz", qc=True)
39
+
40
+ result.segmentation # CPU uint8 tensor on the input's grid
41
+ result.qc["muscle"].estimated_dice # optional per-label quality control
42
+ result.save("seg.nii.gz")
43
+ ```
44
+
45
+ ## Capabilities
46
+
47
+ ### Conversion
48
+
49
+ ```python
50
+ bundle = nl.convert(model_dir) # convert in memory
51
+ bundle = nl.convert(model_dir, output_dir="bundles/x") # convert and save
52
+ bundle.save("bundles/x") # or save later
53
+ bundle = nl.load_bundle("bundles/x", device="cuda") # load, verifying weights
54
+ config = nl.load_config("bundles/x") # bundle.json only, no weights
55
+ ```
56
+
57
+ `convert` takes `fold`, `checkpoint`, `overwrite`, `device`, and an `inference` override for the sliding-window settings (default: nnU-Net's own).
58
+
59
+ ### Preprocessing
60
+
61
+ `nl.preprocess(volume, spacing, config.preprocessing)` runs nnU-Net's pipeline: transpose, crop to nonzero, normalize, resample. It needs only the config, not the weights.
62
+
63
+ | | CPU (`device="cpu"`) | GPU (default when CUDA is available) |
64
+ |---|---|---|
65
+ | Match to nnU-Net | Byte-equal to `DefaultPreprocessor.run_case_npy` | Within float32 rounding |
66
+ | Max difference from CPU path | — | ~5e-7 on normalized data |
67
+ | Voxels bit-identical to CPU | 100% | ~93% |
68
+ | Crop box and shapes | nnU-Net's | Identical to CPU |
69
+
70
+ The GPU path applies spline resampling as one float64 matrix product per axis, using matrices from the same scipy call the CPU path makes. If it fails for any reason (out of memory, CUDA error, non-finite input) it emits a `RuntimeWarning` and falls back to the exact CPU path.
71
+
72
+ Measured on an RTX 2080 Ti, resampling to 1.5 mm:
73
+
74
+ | Input | CPU | GPU | Speedup | Peak GPU memory |
75
+ |---|---|---|---|---|
76
+ | 300×512×512 at 0.8 mm | 8.76 s | 0.30 s | 29x | 1.3 GB |
77
+ | 80×512×512, 5 mm slices | 2.32 s | 0.11 s | 22x | 0.6 GB |
78
+ | 600×512×512 at 1×0.7 mm | 17.68 s | 0.45 s | 39x | 3.6 GB |
79
+ | 2-channel MRI 150×240×240, masked z-score | 2.82 s | 0.24 s | 12x | 0.3 GB |
80
+
81
+ Use the default for throughput; use `device="cpu"` when you need exactly what nnU-Net would produce, for example when validating a conversion. The effect of GPU rounding on final segmentations has not been measured yet.
82
+
83
+ ### Prediction
84
+
85
+ ```python
86
+ predictor.predict("ct.nii.gz") # path
87
+ predictor.predict(s3_body_bytes) # bytes or binary file object, nothing written to disk
88
+ predictor.predict(volume, spacing) # raw (C, X, Y, Z) array or tensor plus spacing
89
+ predictor.predict(source, qc=["muscle"], mirror=True)
90
+ ```
91
+
92
+ - Preprocessing always runs inside `predict` using the bundle's own configuration. There is no entry point for pre-preprocessed tensors.
93
+ - **Sliding window** is a port of `nnUNetPredictor`: tile positions, Gaussian weighting, zero padding, float16 accumulation and CUDA autocast. On CUDA out-of-memory it warns and moves accumulation to the CPU. 2D bundles run slice by slice.
94
+ - **Restoring** resamples logits to the cropped input shape, argmaxes, un-crops and transposes back, one class at a time so full-resolution logits for all classes are never held at once.
95
+ - **Mirroring** (test-time augmentation) is **off** by default, unlike nnU-Net. Pass `mirror=True` to enable it.
96
+ - **Output**: `result.save(path)` and `result.to_bytes()` write NIfTI on the input file's own grid and orientation, using the smallest unsigned integer type that holds the model's highest label. These need a file input, since array inputs carry no affine.
97
+ - **Inputs**: `.nii` and `.nii.gz` are both accepted, including from memory, via nnU-Net's `NibabelIO` and `NibabelIOWithReorient` readers. Other readers work for arrays only.
98
+
99
+ ### Quality control
100
+
101
+ `qc=True` (every foreground label) or a list of label names or ids adds per-label statistics. QC never changes the segmentation and costs nothing unless requested.
102
+
103
+ - **Segmentation stats** (26-connected components): `voxel_count`, `component_count`, `largest_component_fraction`, `small_component_voxel_counts`, `touches_boundary`.
104
+ - **Confidence stats** (softmax at network resolution): `estimated_dice`, `mean_margin`, `low_margin_fraction`, `mean_entropy`, `network_voxel_count`.
105
+
106
+ `estimated_dice` is **uncalibrated**: it is the raw confidence-based estimate at temperature 1. Per-model temperatures and calibration against true Dice are not implemented yet, so treat it as a relative signal, not a Dice value.
107
+
108
+ ### Multiple models on one input
109
+
110
+ ```python
111
+ multi = nl.MultiPredictor({"299": "bundles/dataset299", "485": "bundles/dataset485"})
112
+ results = multi.predict("ct.nii.gz", qc=True) # dict[str, PredictionResult]
113
+ ```
114
+
115
+ The input is parsed once and preprocessed once per distinct preprocessing config. All networks stay on the device; models run one after another.
116
+
117
+ ## Constraints
118
+
119
+ **Models**
120
+ - Architectures: `PlainConvUNet` and `ResidualEncoderUNet`, 2D and 3D, with InstanceNorm, LeakyReLU or ReLU, and no dropout. Legacy and `architecture`-style plans, including `inherits_from`, are supported.
121
+ - One fold per bundle. No ensembling across folds.
122
+ - Not supported (raises `NotImplementedError`): cascade configurations, region-based labels, the ignore label.
123
+
124
+ **Preprocessing**
125
+ - Normalization: `CTNormalization`, `ZScoreNormalization` (with and without mask), `RescaleTo01Normalization`, `RGBTo01Normalization`, `NoNormalization`.
126
+ - Resampling: only nnU-Net's default, `resample_data_or_seg_to_shape`. Others raise `NotImplementedError`.
127
+ - Array inputs must use the axis and spacing order nnU-Net's reader produced for the model, recorded as `config.preprocessing.image_reader`. For example, the nibabel readers give `(z, y, x)` with reversed spacing. 2D images need a singleton first spatial axis, as in nnU-Net.
128
+ - Masked z-score still computes its hole-filled mask on the CPU, even on the GPU path.
129
+
130
+ **Scope**
131
+ - The target is nnU-Net-quality output within a low tolerance, not bitwise-identical segmentations. Network logits are tested bitwise-equal to nnU-Net's own network on CPU FP32 and CUDA autocast.
132
+ - Bundles record the sliding-window defaults (`tile_step_size=0.5`, Gaussian weighting) because nnU-Net keeps them outside its plans. Override them at conversion time if you need different values.
133
+ - Schema 1 bundles still load; saving always writes schema 2.
134
+
135
+ ## Development
136
+
137
+ ```bash
138
+ uv run pytest # synthetic nnU-Net folders, no nnunetv2 needed
139
+ uv run ruff check . && uv run ruff format .
140
+ uv run mypy
141
+ ```
142
+
143
+ Equivalence tests compare against nnU-Net itself and need `nnunetv2`, so they run in the leadup environment:
144
+
145
+ ```bash
146
+ PYTHONPATH=src packages/nnunet_model_conversion/.venv/bin/python -m pytest tests
147
+ ```
148
+
149
+ - `tests/test_nnunet_equivalence.py`: bitwise-equal logits (needs real model folders).
150
+ - `tests/test_nnunet_preprocessing_equivalence.py`: byte-equal preprocessing against `DefaultPreprocessor`.
151
+ - `tests/test_nnunet_prediction_equivalence.py`: whole-CT segmentations against `nnUNetPredictor` (needs CUDA and a test CT via `NNUNET_LITE_TEST_IMAGE`).
152
+
153
+ The earlier speed, accuracy and precision work behind this library lives in `packages/nnunet_model_conversion`.
@@ -0,0 +1,89 @@
1
+ [project]
2
+ name = "nnunet-lite"
3
+ version = "0.1.0"
4
+ description = "Convert nnU-Net models to a standalone safetensors bundle and run nnU-Net-quality inference without nnU-Net"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = [
10
+ "connected-components-3d>=4.1.1",
11
+ "fastmorph>=1.10.0",
12
+ "fastremap>=1.21.0",
13
+ "nibabel>=5.4.2",
14
+ "numpy>=2.4.6",
15
+ "safetensors>=0.8.0",
16
+ "scipy>=1.17.1",
17
+ "torch>=2.9",
18
+ ]
19
+
20
+ [[project.authors]]
21
+ name = "idinsmore1"
22
+ email = "irdinsmore1@geisinger.edu"
23
+
24
+ [build-system]
25
+ requires = ["uv_build>=0.9.27,<0.14.0"]
26
+ build-backend = "uv_build"
27
+
28
+ [dependency-groups]
29
+ dev = [
30
+ "ipykernel>=7.4.0",
31
+ "matplotlib>=3.11.2",
32
+ "mypy>=2.4.1",
33
+ "pre-commit>=4.7.0",
34
+ "pytest>=9.2.0",
35
+ "ruff>=0.17.3",
36
+ ]
37
+
38
+ [[tool.uv.sources.torch]]
39
+ index = "pytorch-cu130"
40
+ marker = "sys_platform == 'linux' or sys_platform == 'win32'"
41
+
42
+ [[tool.uv.index]]
43
+ name = "pytorch-cu130"
44
+ url = "https://download.pytorch.org/whl/cu130"
45
+ explicit = true
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
49
+
50
+ [tool.ruff]
51
+ line-length = 105
52
+ target-version = "py311"
53
+ src = ["src"]
54
+ extend-exclude = ["packages"]
55
+
56
+ [tool.ruff.lint]
57
+ select = [
58
+ "E",
59
+ "W",
60
+ "F",
61
+ "I",
62
+ "B",
63
+ "UP",
64
+ "SIM",
65
+ "C4",
66
+ "RUF",
67
+ ]
68
+
69
+ [tool.ruff.format]
70
+ docstring-code-format = true
71
+
72
+ [tool.mypy]
73
+ python_version = "3.11"
74
+ files = ["src"]
75
+ exclude = ["^packages/"]
76
+ strict = true
77
+ warn_unreachable = true
78
+ pretty = true
79
+
80
+ [[tool.mypy.overrides]]
81
+ module = [
82
+ "scipy.*",
83
+ "fastmorph.*",
84
+ ]
85
+ ignore_missing_imports = true
86
+
87
+ [[tool.mypy.overrides]]
88
+ module = ["nnunet_lite.io"]
89
+ disallow_untyped_calls = false
@@ -0,0 +1,85 @@
1
+ [project]
2
+ name = "nnunet-lite"
3
+ version = "0.1.0"
4
+ description = "Convert nnU-Net models to a standalone safetensors bundle and run nnU-Net-quality inference without nnU-Net"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "idinsmore1", email = "irdinsmore1@geisinger.edu" }
10
+ ]
11
+ requires-python = ">=3.11"
12
+ dependencies = [
13
+ "connected-components-3d>=4.1.1",
14
+ "fastmorph>=1.10.0",
15
+ "fastremap>=1.21.0",
16
+ "nibabel>=5.4.2",
17
+ "numpy>=2.4.6",
18
+ "safetensors>=0.8.0",
19
+ "scipy>=1.17.1",
20
+ "torch>=2.9",
21
+ ]
22
+
23
+ [build-system]
24
+ requires = ["uv_build>=0.9.27,<0.14.0"]
25
+ build-backend = "uv_build"
26
+
27
+ [dependency-groups]
28
+ dev = [
29
+ "ipykernel>=7.4.0",
30
+ "matplotlib>=3.11.2",
31
+ "mypy>=2.4.1",
32
+ "pre-commit>=4.7.0",
33
+ "pytest>=9.2.0",
34
+ "ruff>=0.17.3",
35
+ ]
36
+
37
+ [tool.uv.sources]
38
+ torch = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux' or sys_platform == 'win32'" }]
39
+
40
+ [[tool.uv.index]]
41
+ name = "pytorch-cu130"
42
+ url = "https://download.pytorch.org/whl/cu130"
43
+ explicit = true
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
47
+
48
+ [tool.ruff]
49
+ line-length = 105
50
+ target-version = "py311"
51
+ src = ["src"]
52
+ extend-exclude = ["packages"]
53
+
54
+ [tool.ruff.lint]
55
+ select = [
56
+ "E", # pycodestyle errors
57
+ "W", # pycodestyle warnings
58
+ "F", # pyflakes
59
+ "I", # isort
60
+ "B", # flake8-bugbear
61
+ "UP", # pyupgrade
62
+ "SIM", # flake8-simplify
63
+ "C4", # flake8-comprehensions
64
+ "RUF", # ruff-specific
65
+ ]
66
+
67
+ [tool.ruff.format]
68
+ docstring-code-format = true
69
+
70
+ [tool.mypy]
71
+ python_version = "3.11"
72
+ files = ["src"]
73
+ exclude = ["^packages/"]
74
+ strict = true
75
+ warn_unreachable = true
76
+ pretty = true
77
+
78
+ [[tool.mypy.overrides]]
79
+ module = ["scipy.*", "fastmorph.*"]
80
+ ignore_missing_imports = true
81
+
82
+ [[tool.mypy.overrides]]
83
+ # nibabel's orientation and image-construction helpers are not annotated.
84
+ module = ["nnunet_lite.io"]
85
+ disallow_untyped_calls = false
@@ -0,0 +1,32 @@
1
+ from .bundle import Bundle, load_bundle, load_config
2
+ from .config import (
3
+ BundleConfig,
4
+ ChannelConfig,
5
+ InferenceConfig,
6
+ NetworkConfig,
7
+ PreprocessingConfig,
8
+ ResamplingConfig,
9
+ )
10
+ from .convert import convert
11
+ from .predict import MultiPredictor, PredictionResult, Predictor
12
+ from .preprocessing import PreprocessingProperties, preprocess
13
+ from .qc import LabelQC
14
+
15
+ __all__ = [
16
+ "Bundle",
17
+ "BundleConfig",
18
+ "ChannelConfig",
19
+ "InferenceConfig",
20
+ "LabelQC",
21
+ "MultiPredictor",
22
+ "NetworkConfig",
23
+ "PredictionResult",
24
+ "Predictor",
25
+ "PreprocessingConfig",
26
+ "PreprocessingProperties",
27
+ "ResamplingConfig",
28
+ "convert",
29
+ "load_bundle",
30
+ "load_config",
31
+ "preprocess",
32
+ ]
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+
3
+ import warnings
4
+
5
+ import torch
6
+
7
+
8
+ def resolve_device(device: str | torch.device | None) -> torch.device:
9
+ if device is None:
10
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+ return torch.device(device)
12
+
13
+
14
+ def warn_cpu_fallback(what: str, device: torch.device, error: BaseException) -> None:
15
+ # Called from the function that falls back, so the warning points at its caller.
16
+ reason = (str(error).strip() or type(error).__name__).splitlines()[0]
17
+ warnings.warn(
18
+ f"{what} on {device} failed ({reason}); falling back to CPU", RuntimeWarning, stacklevel=3
19
+ )
20
+ if device.type == "cuda":
21
+ torch.cuda.empty_cache()