segresnet-mlx 0.3.2__tar.gz → 0.3.4__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.
- segresnet_mlx-0.3.4/.gitignore +38 -0
- segresnet_mlx-0.3.4/PKG-INFO +194 -0
- segresnet_mlx-0.3.4/README.md +154 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/THIRD_PARTY_NOTICES.md +1 -1
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/pyproject.toml +40 -12
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/__init__.py +1 -1
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/_types.py +1 -18
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/medmlx.py +106 -67
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/network.py +1 -15
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/topology.py +1 -1
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/transforms.py +0 -19
- segresnet_mlx-0.3.2/.gitignore +0 -26
- segresnet_mlx-0.3.2/PKG-INFO +0 -79
- segresnet_mlx-0.3.2/README.md +0 -53
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/LICENSE +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/_arrays.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/_nifti.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/_records.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/_runtime.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/inference.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/predictor.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/py.typed +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/telemetry.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.4}/src/segresnet_mlx/weights.py +0 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# MedMLX standard
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
.venv
|
|
6
|
+
build/
|
|
7
|
+
dist/
|
|
8
|
+
.pytest_cache/
|
|
9
|
+
.ruff_cache/
|
|
10
|
+
.mypy_cache/
|
|
11
|
+
.hypothesis/
|
|
12
|
+
.coverage
|
|
13
|
+
htmlcov/
|
|
14
|
+
.DS_Store
|
|
15
|
+
# Never commit secrets (Hugging Face tokens)
|
|
16
|
+
.env
|
|
17
|
+
# Never commit data or weights
|
|
18
|
+
/data/
|
|
19
|
+
/work/
|
|
20
|
+
/weights/
|
|
21
|
+
/models/
|
|
22
|
+
/checkpoints/
|
|
23
|
+
/outputs/
|
|
24
|
+
*.nii
|
|
25
|
+
*.nii.gz
|
|
26
|
+
*.dcm
|
|
27
|
+
*.nrrd
|
|
28
|
+
*.mha
|
|
29
|
+
*.mhd
|
|
30
|
+
*.safetensors
|
|
31
|
+
*.pt
|
|
32
|
+
*.pth
|
|
33
|
+
*.ckpt
|
|
34
|
+
*.bin
|
|
35
|
+
*.h5
|
|
36
|
+
*.npy
|
|
37
|
+
*.npz
|
|
38
|
+
!tests/fixtures/**/*.npz
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: segresnet-mlx
|
|
3
|
+
Version: 0.3.4
|
|
4
|
+
Summary: Segment brain tumors, renal structures and whole-body CT anatomy with MONAI SegResNet models in native MLX
|
|
5
|
+
Project-URL: Homepage, https://medmlx.org
|
|
6
|
+
Project-URL: Documentation, https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/README.md
|
|
7
|
+
Project-URL: Repository, https://github.com/MedMLX/segresnet-mlx
|
|
8
|
+
Project-URL: Issues, https://github.com/MedMLX/segresnet-mlx/issues
|
|
9
|
+
Project-URL: Weights, https://huggingface.co/models?author=MedMLX&search=segresnet
|
|
10
|
+
Project-URL: MedMLX, https://github.com/MedMLX/medmlx
|
|
11
|
+
Author: Joseph Sandoval, Alfredo Sandoval Jr.
|
|
12
|
+
License-Expression: Apache-2.0
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
License-File: THIRD_PARTY_NOTICES.md
|
|
15
|
+
Keywords: apple-silicon,brats,ct,medical-imaging,metal,mlx,monai,mri,segmentation,segresnet
|
|
16
|
+
Classifier: Development Status :: 4 - Beta
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Intended Audience :: Science/Research
|
|
19
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
24
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
25
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
26
|
+
Requires-Python: <3.14,>=3.13
|
|
27
|
+
Requires-Dist: medmlx-core<0.3,>=0.2.6
|
|
28
|
+
Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
|
|
29
|
+
Requires-Dist: nibabel<6,>=5.3
|
|
30
|
+
Requires-Dist: numpy<3,>=2.0
|
|
31
|
+
Provides-Extra: dev
|
|
32
|
+
Requires-Dist: hypothesis<7,>=6; extra == 'dev'
|
|
33
|
+
Requires-Dist: monai==1.6.1; extra == 'dev'
|
|
34
|
+
Requires-Dist: pyright==1.1.414; extra == 'dev'
|
|
35
|
+
Requires-Dist: pytest<10,>=8.4; extra == 'dev'
|
|
36
|
+
Requires-Dist: pytorch-ignite<0.6,>=0.4.11; extra == 'dev'
|
|
37
|
+
Requires-Dist: ruff<1,>=0.13; extra == 'dev'
|
|
38
|
+
Requires-Dist: torch<3,>=2.6; extra == 'dev'
|
|
39
|
+
Description-Content-Type: text/markdown
|
|
40
|
+
|
|
41
|
+
<div align="center">
|
|
42
|
+
|
|
43
|
+
# segresnet-mlx
|
|
44
|
+
|
|
45
|
+
Segment brain tumors, renal structures and whole-body CT anatomy with MONAI SegResNet models in native MLX.
|
|
46
|
+
|
|
47
|
+
[](https://pypi.org/project/segresnet-mlx/)
|
|
48
|
+
[](https://pypi.org/project/segresnet-mlx/)
|
|
49
|
+
[](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/LICENSE)
|
|
50
|
+
[](https://github.com/ml-explore/mlx)
|
|
51
|
+
[](https://huggingface.co/MedMLX/segresnet-brats-mlx)
|
|
52
|
+
[](https://github.com/MedMLX/medmlx)
|
|
53
|
+
|
|
54
|
+
[BraTS weights](https://huggingface.co/MedMLX/segresnet-brats-mlx) · [Renal weights](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
|
|
55
|
+
|
|
56
|
+
<img src="https://raw.githubusercontent.com/MedMLX/segresnet-mlx/v0.3.4/docs/example.png" alt="Brain tumor segmentation in axial, coronal and sagittal MRI" width="100%">
|
|
57
|
+
|
|
58
|
+
</div>
|
|
59
|
+
|
|
60
|
+
| Input | Output |
|
|
61
|
+
| :--- | :--- |
|
|
62
|
+
| MRI sequences or CT volumes | Segmentation on the input grid |
|
|
63
|
+
|
|
64
|
+
Weights: 19 MB download for `segresnet-brats`, 76 MB for `segresnet-renal-cect`. Peak MLX memory: 4.9 GB for a 240×240×155 four-sequence brain MRI (`segresnet-brats`) and 4.0 GB for a 478×277×161 three-phase CT (`segresnet-renal-cect`).
|
|
65
|
+
|
|
66
|
+
## Use with MedMLX
|
|
67
|
+
|
|
68
|
+
The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this package. It installs this runtime, downloads its weights on first use, and lets an AI agent describe, check and run `segresnet-brats` and `segresnet-renal-cect` for you.
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
uv tool install --python 3.13 "medmlx[segment,mcp]"
|
|
72
|
+
MEDMLX="$(uv tool dir --bin --color never)/medmlx"
|
|
73
|
+
mkdir -p "$HOME/medmlx-work"
|
|
74
|
+
claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"`. Other MCP clients take the same command and arguments. The same install provides the `medmlx` CLI, for example `medmlx describe segresnet-brats`.
|
|
78
|
+
|
|
79
|
+
> **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
|
|
80
|
+
|
|
81
|
+
## Install
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
uv venv --python 3.13
|
|
85
|
+
source .venv/bin/activate
|
|
86
|
+
uv pip install "segresnet-mlx>=0.3.4"
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Run
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from segresnet_mlx.medmlx import brats
|
|
93
|
+
|
|
94
|
+
result = brats(
|
|
95
|
+
t1c_path="t1c.nii.gz", t1_path="t1.nii.gz", t2_path="t2.nii.gz",
|
|
96
|
+
flair_path="flair.nii.gz", output_dir="out",
|
|
97
|
+
)
|
|
98
|
+
print(result["outputs"]["mask"])
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
The registered models are `segresnet-brats` and `segresnet-renal-cect`; their `brats`
|
|
102
|
+
and `renal_cect` runners select the matching bundle internally. The renal runner takes
|
|
103
|
+
`arterial_path`, `venous_path` and `excretory_path`. Keep each model's input volumes
|
|
104
|
+
on one voxel grid.
|
|
105
|
+
|
|
106
|
+
Omitting `weights_path` downloads `MedMLX/segresnet-brats-mlx` or
|
|
107
|
+
`MedMLX/segresnet-renal-cect-mlx` into the shared MedMLX cache on first use; interrupted
|
|
108
|
+
downloads resume and later runs work offline. With MedMLX installed, `medmlx setup
|
|
109
|
+
segresnet-brats` downloads it ahead of time. To use your own copy, pass a folder
|
|
110
|
+
containing `segresnet-brats.safetensors` for BraTS or `segresnet-renal-cect.safetensors`
|
|
111
|
+
for renal CECT as `weights_path`. `details.weights_revision` records the downloaded
|
|
112
|
+
commit, or `null` for a folder without a MedMLX download record.
|
|
113
|
+
|
|
114
|
+
The standalone `run(bundle=..., weights_path=...)` interface remains available for
|
|
115
|
+
explicit local checkpoints, including the whole-body CT variants. Published native
|
|
116
|
+
weights are also available for [renal CECT](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
|
|
117
|
+
and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
|
|
118
|
+
|
|
119
|
+
### Inputs and outputs
|
|
120
|
+
|
|
121
|
+
| Argument | Meaning |
|
|
122
|
+
| --- | --- |
|
|
123
|
+
| `t1c_path`, `t1_path`, `t2_path`, `flair_path` | `brats`: contrast T1, T1, T2 and FLAIR MRI in NIfTI |
|
|
124
|
+
| `arterial_path`, `venous_path`, `excretory_path` | `renal_cect`: arterial, venous and excretory CT in NIfTI |
|
|
125
|
+
| `output_dir` | Directory for `<bundle>_mask.nii.gz`; created if missing |
|
|
126
|
+
| `weights_path` | Optional `.safetensors` file or a folder containing it |
|
|
127
|
+
| `overwrite` | `False` by default; an existing mask is replaced only when `True` |
|
|
128
|
+
| `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` (renal only) |
|
|
129
|
+
|
|
130
|
+
Inputs are finite 3D volumes on one voxel grid, with spatial units in millimetres or
|
|
131
|
+
unspecified. The mask is written on the input grid as the NIfTI reader corrects it. Renal labels are float32: 1 artery, 2 vein, 3 ureter,
|
|
132
|
+
4 neoplasm and 5 parenchyma. BraTS labels are uint8: 1 tumor core, 2 whole tumor
|
|
133
|
+
outside the core and 4 enhancing tumor.
|
|
134
|
+
|
|
135
|
+
`compensated-fp32` accumulates convolution and GroupNorm in paired Metal floats with
|
|
136
|
+
float32 layer outputs. `compensated-fp48` carries the pairs through the hidden layers
|
|
137
|
+
and stitches in float64 on the host; it needs the renal transposed-convolution decoder.
|
|
138
|
+
|
|
139
|
+
`run` returns `{"outputs": {"mask": path}, "details": {...}}`, with labels, shapes,
|
|
140
|
+
window settings, MLX device, peak memory and elapsed time. Invalid inputs raise
|
|
141
|
+
`InvalidInputError`; missing or mismatched weights raise `AssetNotReadyError`;
|
|
142
|
+
inference failures raise `ModelExecutionError`.
|
|
143
|
+
|
|
144
|
+
### Whole-body CT and streaming
|
|
145
|
+
|
|
146
|
+
`run` takes `bundle` and a `.safetensors` file as `weights_path`: `brats_mri_segmentation`,
|
|
147
|
+
`renalStructures_CECT_segmentation`, `wholeBody_ct_segmentation` (1.5 mm) or
|
|
148
|
+
`wholeBody_ct_segmentation_lowres` (3 mm). The whole-body bundles take one CT as
|
|
149
|
+
`image_path` and use `segresnet-wholebody-high.safetensors` or
|
|
150
|
+
`segresnet-wholebody-low.safetensors`. They write float32 labels 0–104 from the
|
|
151
|
+
bundle's `channel_def`: 1 spleen, 2 kidney_right, 3 kidney_left, 4 gallbladder,
|
|
152
|
+
5 liver, 6 stomach, 7 aorta, 8 inferior_vena_cava, 9 portal_vein_and_splenic_vein,
|
|
153
|
+
10 pancreas, 11–12 adrenal glands (right, left), 13–17 lung lobes (upper and lower
|
|
154
|
+
left, upper, middle and lower right), 18–41 vertebrae L5–C1, 42 esophagus, 43 trachea,
|
|
155
|
+
44–49 heart chambers and pulmonary artery, 50 brain, 51–54 iliac arteries and veins,
|
|
156
|
+
55 small bowel, 56 duodenum, 57 colon, 58–69 left ribs 1–12, 70–81 right ribs 1–12,
|
|
157
|
+
82–83 humerus, 84–85 scapula, 86–87 clavicula, 88–89 femur, 90–91 hip, 92 sacrum,
|
|
158
|
+
93 face, 94–99 gluteus maximus, medius and minimus, 100–101 autochthon, 102–103
|
|
159
|
+
iliopsoas and 104 urinary bladder.
|
|
160
|
+
|
|
161
|
+
`run(..., streaming=True, scratch_dir="scratch")` keeps blending intermediates and
|
|
162
|
+
logits in temporary mapped files instead of a full in-memory class volume. The files
|
|
163
|
+
are removed on success and failure; `scratch_dir` defaults to the system temporary
|
|
164
|
+
directory. The final label volume stays in memory.
|
|
165
|
+
|
|
166
|
+
### Python API
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
from pathlib import Path
|
|
170
|
+
|
|
171
|
+
import numpy as np
|
|
172
|
+
from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_model, predict_logits
|
|
173
|
+
|
|
174
|
+
spec = SegResNetSpec(3, 6, 32, upsample_mode="deconv") # renal CECT network
|
|
175
|
+
network = load_model(Path("segresnet-renal-cect.safetensors"), spec=spec)
|
|
176
|
+
patch = np.zeros((1, 3, 32, 32, 32), dtype=np.float32)
|
|
177
|
+
logits = forward_patch(network, patch) # float32 NCDHW -> float32 NumPy logits
|
|
178
|
+
config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
|
|
179
|
+
volume_logits = predict_logits(patch, config, network=network) # stitched sliding windows
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
`forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
|
|
183
|
+
`predict_logits` takes preprocessed arrays of any size and stitches the bundle's
|
|
184
|
+
sliding windows; neither normalizes intensities, applies activations or maps labels.
|
|
185
|
+
`load_model` checks tensor names, shapes and finite float32 values against
|
|
186
|
+
`required_shapes(spec)`, not checkpoint identity. `WindowTelemetry` and
|
|
187
|
+
`BundlePredictor` record bounded progress and timing. Inference needs Apple Silicon
|
|
188
|
+
with Metal and has no CPU fallback.
|
|
189
|
+
|
|
190
|
+
## License
|
|
191
|
+
|
|
192
|
+
[Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
|
|
193
|
+
|
|
194
|
+
For research and education. Outputs require human review.
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
# segresnet-mlx
|
|
4
|
+
|
|
5
|
+
Segment brain tumors, renal structures and whole-body CT anatomy with MONAI SegResNet models in native MLX.
|
|
6
|
+
|
|
7
|
+
[](https://pypi.org/project/segresnet-mlx/)
|
|
8
|
+
[](https://pypi.org/project/segresnet-mlx/)
|
|
9
|
+
[](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/LICENSE)
|
|
10
|
+
[](https://github.com/ml-explore/mlx)
|
|
11
|
+
[](https://huggingface.co/MedMLX/segresnet-brats-mlx)
|
|
12
|
+
[](https://github.com/MedMLX/medmlx)
|
|
13
|
+
|
|
14
|
+
[BraTS weights](https://huggingface.co/MedMLX/segresnet-brats-mlx) · [Renal weights](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
|
|
15
|
+
|
|
16
|
+
<img src="https://raw.githubusercontent.com/MedMLX/segresnet-mlx/v0.3.4/docs/example.png" alt="Brain tumor segmentation in axial, coronal and sagittal MRI" width="100%">
|
|
17
|
+
|
|
18
|
+
</div>
|
|
19
|
+
|
|
20
|
+
| Input | Output |
|
|
21
|
+
| :--- | :--- |
|
|
22
|
+
| MRI sequences or CT volumes | Segmentation on the input grid |
|
|
23
|
+
|
|
24
|
+
Weights: 19 MB download for `segresnet-brats`, 76 MB for `segresnet-renal-cect`. Peak MLX memory: 4.9 GB for a 240×240×155 four-sequence brain MRI (`segresnet-brats`) and 4.0 GB for a 478×277×161 three-phase CT (`segresnet-renal-cect`).
|
|
25
|
+
|
|
26
|
+
## Use with MedMLX
|
|
27
|
+
|
|
28
|
+
The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this package. It installs this runtime, downloads its weights on first use, and lets an AI agent describe, check and run `segresnet-brats` and `segresnet-renal-cect` for you.
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
uv tool install --python 3.13 "medmlx[segment,mcp]"
|
|
32
|
+
MEDMLX="$(uv tool dir --bin --color never)/medmlx"
|
|
33
|
+
mkdir -p "$HOME/medmlx-work"
|
|
34
|
+
claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"`. Other MCP clients take the same command and arguments. The same install provides the `medmlx` CLI, for example `medmlx describe segresnet-brats`.
|
|
38
|
+
|
|
39
|
+
> **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
uv venv --python 3.13
|
|
45
|
+
source .venv/bin/activate
|
|
46
|
+
uv pip install "segresnet-mlx>=0.3.4"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Run
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from segresnet_mlx.medmlx import brats
|
|
53
|
+
|
|
54
|
+
result = brats(
|
|
55
|
+
t1c_path="t1c.nii.gz", t1_path="t1.nii.gz", t2_path="t2.nii.gz",
|
|
56
|
+
flair_path="flair.nii.gz", output_dir="out",
|
|
57
|
+
)
|
|
58
|
+
print(result["outputs"]["mask"])
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The registered models are `segresnet-brats` and `segresnet-renal-cect`; their `brats`
|
|
62
|
+
and `renal_cect` runners select the matching bundle internally. The renal runner takes
|
|
63
|
+
`arterial_path`, `venous_path` and `excretory_path`. Keep each model's input volumes
|
|
64
|
+
on one voxel grid.
|
|
65
|
+
|
|
66
|
+
Omitting `weights_path` downloads `MedMLX/segresnet-brats-mlx` or
|
|
67
|
+
`MedMLX/segresnet-renal-cect-mlx` into the shared MedMLX cache on first use; interrupted
|
|
68
|
+
downloads resume and later runs work offline. With MedMLX installed, `medmlx setup
|
|
69
|
+
segresnet-brats` downloads it ahead of time. To use your own copy, pass a folder
|
|
70
|
+
containing `segresnet-brats.safetensors` for BraTS or `segresnet-renal-cect.safetensors`
|
|
71
|
+
for renal CECT as `weights_path`. `details.weights_revision` records the downloaded
|
|
72
|
+
commit, or `null` for a folder without a MedMLX download record.
|
|
73
|
+
|
|
74
|
+
The standalone `run(bundle=..., weights_path=...)` interface remains available for
|
|
75
|
+
explicit local checkpoints, including the whole-body CT variants. Published native
|
|
76
|
+
weights are also available for [renal CECT](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
|
|
77
|
+
and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
|
|
78
|
+
|
|
79
|
+
### Inputs and outputs
|
|
80
|
+
|
|
81
|
+
| Argument | Meaning |
|
|
82
|
+
| --- | --- |
|
|
83
|
+
| `t1c_path`, `t1_path`, `t2_path`, `flair_path` | `brats`: contrast T1, T1, T2 and FLAIR MRI in NIfTI |
|
|
84
|
+
| `arterial_path`, `venous_path`, `excretory_path` | `renal_cect`: arterial, venous and excretory CT in NIfTI |
|
|
85
|
+
| `output_dir` | Directory for `<bundle>_mask.nii.gz`; created if missing |
|
|
86
|
+
| `weights_path` | Optional `.safetensors` file or a folder containing it |
|
|
87
|
+
| `overwrite` | `False` by default; an existing mask is replaced only when `True` |
|
|
88
|
+
| `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` (renal only) |
|
|
89
|
+
|
|
90
|
+
Inputs are finite 3D volumes on one voxel grid, with spatial units in millimetres or
|
|
91
|
+
unspecified. The mask is written on the input grid as the NIfTI reader corrects it. Renal labels are float32: 1 artery, 2 vein, 3 ureter,
|
|
92
|
+
4 neoplasm and 5 parenchyma. BraTS labels are uint8: 1 tumor core, 2 whole tumor
|
|
93
|
+
outside the core and 4 enhancing tumor.
|
|
94
|
+
|
|
95
|
+
`compensated-fp32` accumulates convolution and GroupNorm in paired Metal floats with
|
|
96
|
+
float32 layer outputs. `compensated-fp48` carries the pairs through the hidden layers
|
|
97
|
+
and stitches in float64 on the host; it needs the renal transposed-convolution decoder.
|
|
98
|
+
|
|
99
|
+
`run` returns `{"outputs": {"mask": path}, "details": {...}}`, with labels, shapes,
|
|
100
|
+
window settings, MLX device, peak memory and elapsed time. Invalid inputs raise
|
|
101
|
+
`InvalidInputError`; missing or mismatched weights raise `AssetNotReadyError`;
|
|
102
|
+
inference failures raise `ModelExecutionError`.
|
|
103
|
+
|
|
104
|
+
### Whole-body CT and streaming
|
|
105
|
+
|
|
106
|
+
`run` takes `bundle` and a `.safetensors` file as `weights_path`: `brats_mri_segmentation`,
|
|
107
|
+
`renalStructures_CECT_segmentation`, `wholeBody_ct_segmentation` (1.5 mm) or
|
|
108
|
+
`wholeBody_ct_segmentation_lowres` (3 mm). The whole-body bundles take one CT as
|
|
109
|
+
`image_path` and use `segresnet-wholebody-high.safetensors` or
|
|
110
|
+
`segresnet-wholebody-low.safetensors`. They write float32 labels 0–104 from the
|
|
111
|
+
bundle's `channel_def`: 1 spleen, 2 kidney_right, 3 kidney_left, 4 gallbladder,
|
|
112
|
+
5 liver, 6 stomach, 7 aorta, 8 inferior_vena_cava, 9 portal_vein_and_splenic_vein,
|
|
113
|
+
10 pancreas, 11–12 adrenal glands (right, left), 13–17 lung lobes (upper and lower
|
|
114
|
+
left, upper, middle and lower right), 18–41 vertebrae L5–C1, 42 esophagus, 43 trachea,
|
|
115
|
+
44–49 heart chambers and pulmonary artery, 50 brain, 51–54 iliac arteries and veins,
|
|
116
|
+
55 small bowel, 56 duodenum, 57 colon, 58–69 left ribs 1–12, 70–81 right ribs 1–12,
|
|
117
|
+
82–83 humerus, 84–85 scapula, 86–87 clavicula, 88–89 femur, 90–91 hip, 92 sacrum,
|
|
118
|
+
93 face, 94–99 gluteus maximus, medius and minimus, 100–101 autochthon, 102–103
|
|
119
|
+
iliopsoas and 104 urinary bladder.
|
|
120
|
+
|
|
121
|
+
`run(..., streaming=True, scratch_dir="scratch")` keeps blending intermediates and
|
|
122
|
+
logits in temporary mapped files instead of a full in-memory class volume. The files
|
|
123
|
+
are removed on success and failure; `scratch_dir` defaults to the system temporary
|
|
124
|
+
directory. The final label volume stays in memory.
|
|
125
|
+
|
|
126
|
+
### Python API
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
from pathlib import Path
|
|
130
|
+
|
|
131
|
+
import numpy as np
|
|
132
|
+
from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_model, predict_logits
|
|
133
|
+
|
|
134
|
+
spec = SegResNetSpec(3, 6, 32, upsample_mode="deconv") # renal CECT network
|
|
135
|
+
network = load_model(Path("segresnet-renal-cect.safetensors"), spec=spec)
|
|
136
|
+
patch = np.zeros((1, 3, 32, 32, 32), dtype=np.float32)
|
|
137
|
+
logits = forward_patch(network, patch) # float32 NCDHW -> float32 NumPy logits
|
|
138
|
+
config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
|
|
139
|
+
volume_logits = predict_logits(patch, config, network=network) # stitched sliding windows
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
|
|
143
|
+
`predict_logits` takes preprocessed arrays of any size and stitches the bundle's
|
|
144
|
+
sliding windows; neither normalizes intensities, applies activations or maps labels.
|
|
145
|
+
`load_model` checks tensor names, shapes and finite float32 values against
|
|
146
|
+
`required_shapes(spec)`, not checkpoint identity. `WindowTelemetry` and
|
|
147
|
+
`BundlePredictor` record bounded progress and timing. Inference needs Apple Silicon
|
|
148
|
+
with Metal and has no CPU fallback.
|
|
149
|
+
|
|
150
|
+
## License
|
|
151
|
+
|
|
152
|
+
[Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
|
|
153
|
+
|
|
154
|
+
For research and education. Outputs require human review.
|
|
@@ -13,7 +13,7 @@ the full license is included in [LICENSE](LICENSE).
|
|
|
13
13
|
Bundle definitions originate in the
|
|
14
14
|
[MONAI model zoo](https://github.com/Project-MONAI/model-zoo), revision
|
|
15
15
|
`db9eeeef7ba64ce2ced0230d9bd4c524f69b7f0c`. The source files and bundle versions
|
|
16
|
-
are identified in [
|
|
16
|
+
are identified in [tests/fixtures/upstream_reference.json](tests/fixtures/upstream_reference.json).
|
|
17
17
|
The port changes execution to native MLX and host NumPy image processing.
|
|
18
18
|
|
|
19
19
|
Pretrained checkpoints and input datasets retain their publisher terms.
|
|
@@ -4,16 +4,43 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "segresnet-mlx"
|
|
7
|
-
version = "0.3.
|
|
8
|
-
description = "
|
|
7
|
+
version = "0.3.4"
|
|
8
|
+
description = "Segment brain tumors, renal structures and whole-body CT anatomy with MONAI SegResNet models in native MLX"
|
|
9
9
|
readme = "README.md"
|
|
10
|
-
requires-python = ">=3.13,<3.
|
|
11
|
-
classifiers = [
|
|
10
|
+
requires-python = ">=3.13,<3.14"
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 4 - Beta",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Intended Audience :: Science/Research",
|
|
15
|
+
"Operating System :: MacOS :: MacOS X",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
18
|
+
"Programming Language :: Python :: 3.13",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
20
|
+
"Topic :: Scientific/Engineering :: Image Processing",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Medical Science Apps.",
|
|
22
|
+
]
|
|
23
|
+
keywords = [
|
|
24
|
+
"mlx",
|
|
25
|
+
"apple-silicon",
|
|
26
|
+
"metal",
|
|
27
|
+
"medical-imaging",
|
|
28
|
+
"segresnet",
|
|
29
|
+
"monai",
|
|
30
|
+
"segmentation",
|
|
31
|
+
"brats",
|
|
32
|
+
"ct",
|
|
33
|
+
"mri",
|
|
34
|
+
]
|
|
12
35
|
license = "Apache-2.0"
|
|
13
36
|
license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]
|
|
14
|
-
authors = [
|
|
37
|
+
authors = [
|
|
38
|
+
{ name = "Joseph Sandoval" },
|
|
39
|
+
{ name = "Alfredo Sandoval Jr." },
|
|
40
|
+
]
|
|
15
41
|
dependencies = [
|
|
16
|
-
"medmlx-core
|
|
42
|
+
"medmlx-core>=0.2.6,<0.3",
|
|
43
|
+
"mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'",
|
|
17
44
|
"nibabel>=5.3,<6",
|
|
18
45
|
"numpy>=2.0,<3",
|
|
19
46
|
]
|
|
@@ -24,8 +51,11 @@ segresnet-renal-cect = "segresnet_mlx.medmlx:RENAL_CECT_MODEL"
|
|
|
24
51
|
|
|
25
52
|
[project.urls]
|
|
26
53
|
Homepage = "https://medmlx.org"
|
|
54
|
+
Documentation = "https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/README.md"
|
|
27
55
|
Repository = "https://github.com/MedMLX/segresnet-mlx"
|
|
28
|
-
|
|
56
|
+
Issues = "https://github.com/MedMLX/segresnet-mlx/issues"
|
|
57
|
+
Weights = "https://huggingface.co/models?author=MedMLX&search=segresnet"
|
|
58
|
+
MedMLX = "https://github.com/MedMLX/medmlx"
|
|
29
59
|
|
|
30
60
|
[project.optional-dependencies]
|
|
31
61
|
dev = [
|
|
@@ -38,9 +68,6 @@ dev = [
|
|
|
38
68
|
"torch>=2.6,<3",
|
|
39
69
|
]
|
|
40
70
|
|
|
41
|
-
[tool.hatch.metadata]
|
|
42
|
-
allow-direct-references = true
|
|
43
|
-
|
|
44
71
|
[tool.hatch.build.targets.wheel]
|
|
45
72
|
packages = ["src/segresnet_mlx"]
|
|
46
73
|
|
|
@@ -52,6 +79,7 @@ markers = ["mlx: native MLX execution requiring Apple Silicon Metal"]
|
|
|
52
79
|
[tool.uv]
|
|
53
80
|
constraint-dependencies = ["setuptools>=84.1.0", "filelock>=4.2.1", ]
|
|
54
81
|
environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
|
|
82
|
+
required-environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
|
|
55
83
|
|
|
56
84
|
[tool.ruff]
|
|
57
85
|
line-length = 100
|
|
@@ -62,8 +90,8 @@ extend-select = ["TID251", "TID252", "ANN401"]
|
|
|
62
90
|
select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
|
|
63
91
|
|
|
64
92
|
[tool.pyright]
|
|
65
|
-
include = ["
|
|
66
|
-
extraPaths = ["src", "
|
|
93
|
+
include = ["src", "tests"]
|
|
94
|
+
extraPaths = ["src", "tests"]
|
|
67
95
|
pythonVersion = "3.13"
|
|
68
96
|
typeCheckingMode = "strict"
|
|
69
97
|
enableTypeIgnoreComments = false
|
|
@@ -19,7 +19,7 @@ if TYPE_CHECKING:
|
|
|
19
19
|
from segresnet_mlx.weights import load_model as load_model
|
|
20
20
|
from segresnet_mlx.weights import required_shapes as required_shapes
|
|
21
21
|
|
|
22
|
-
__version__ = "0.3.
|
|
22
|
+
__version__ = "0.3.4"
|
|
23
23
|
|
|
24
24
|
_EXPORTS = {
|
|
25
25
|
"BUNDLE_CONFIGS": "segresnet_mlx.predictor",
|
|
@@ -12,28 +12,16 @@ if TYPE_CHECKING:
|
|
|
12
12
|
from medmlx_core.typing import MlxRuntime
|
|
13
13
|
from medmlx_core.volume_workspace import VolumeWorkspace
|
|
14
14
|
|
|
15
|
-
from segresnet_mlx._arrays import Float32Array
|
|
15
|
+
from segresnet_mlx._arrays import Float32Array
|
|
16
16
|
|
|
17
17
|
type Array = mx.array
|
|
18
18
|
|
|
19
19
|
class WorkspaceOptions(TypedDict, total=False):
|
|
20
20
|
workspace: VolumeWorkspace
|
|
21
21
|
|
|
22
|
-
type ArrayValue = bool | int | float | complex | list[ArrayValue] | tuple[ArrayValue, ...]
|
|
23
|
-
|
|
24
|
-
class ArrayConstructor(Protocol):
|
|
25
|
-
def __call__(
|
|
26
|
-
self, value: HostArray | Array | ArrayValue, dtype: mx.Dtype | None = None
|
|
27
|
-
) -> Array:
|
|
28
|
-
"""Construct an MLX array with an optional dtype."""
|
|
29
|
-
...
|
|
30
|
-
|
|
31
22
|
class MLX(MlxRuntime, Protocol):
|
|
32
23
|
all = staticmethod(mx.all)
|
|
33
24
|
isfinite = staticmethod(mx.isfinite)
|
|
34
|
-
full = staticmethod(mx.full)
|
|
35
|
-
sum = staticmethod(mx.sum)
|
|
36
|
-
ones = staticmethod(mx.ones)
|
|
37
25
|
synchronize = staticmethod(mx.synchronize)
|
|
38
26
|
clear_cache = staticmethod(mx.clear_cache)
|
|
39
27
|
load = staticmethod(mx.load)
|
|
@@ -63,8 +51,3 @@ if TYPE_CHECKING:
|
|
|
63
51
|
|
|
64
52
|
class CoreSlidingWindow(Protocol):
|
|
65
53
|
sliding_window_inference: SlidingWindowInference
|
|
66
|
-
|
|
67
|
-
class Metal(Protocol):
|
|
68
|
-
def is_available(self) -> bool:
|
|
69
|
-
"""Report whether the Metal backend is available."""
|
|
70
|
-
...
|
|
@@ -9,7 +9,7 @@ from collections.abc import Mapping
|
|
|
9
9
|
from contextlib import nullcontext
|
|
10
10
|
from dataclasses import dataclass
|
|
11
11
|
from pathlib import Path
|
|
12
|
-
from typing import TYPE_CHECKING
|
|
12
|
+
from typing import TYPE_CHECKING, cast
|
|
13
13
|
|
|
14
14
|
from segresnet_mlx._arrays import Float32Array, Float64Array, MaskArray
|
|
15
15
|
from segresnet_mlx._records import RunResult, Runtime
|
|
@@ -30,34 +30,6 @@ from medmlx_core.weights import weights_dir, weights_revision
|
|
|
30
30
|
from segresnet_mlx import transforms
|
|
31
31
|
from segresnet_mlx.topology import ArithmeticProfile, SegResNetSpec
|
|
32
32
|
|
|
33
|
-
MODEL = {
|
|
34
|
-
"id": "segresnet",
|
|
35
|
-
"label": "SegResNet",
|
|
36
|
-
"task": "segmentation",
|
|
37
|
-
"run": "segresnet_mlx.medmlx:run",
|
|
38
|
-
"summary": (
|
|
39
|
-
"MONAI SegResNet bundles: renal structures in three-phase contrast CT "
|
|
40
|
-
"(renalStructures_CECT_segmentation), brain tumor in BraTS MRI "
|
|
41
|
-
"(brats_mri_segmentation), and 104 whole-body structures in CT at 1.5 mm or "
|
|
42
|
-
"3 mm (wholeBody_ct_segmentation, wholeBody_ct_segmentation_lowres)."
|
|
43
|
-
),
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
BRATS_MODEL = {
|
|
47
|
-
"id": "segresnet-brats",
|
|
48
|
-
"label": "SegResNet BraTS MRI",
|
|
49
|
-
"task": "segmentation",
|
|
50
|
-
"run": "segresnet_mlx.medmlx:brats",
|
|
51
|
-
"summary": "BraTS brain tumor segmentation from co-registered MRI sequences.",
|
|
52
|
-
}
|
|
53
|
-
RENAL_CECT_MODEL = {
|
|
54
|
-
"id": "segresnet-renal-cect",
|
|
55
|
-
"label": "SegResNet renal CECT",
|
|
56
|
-
"task": "segmentation",
|
|
57
|
-
"run": "segresnet_mlx.medmlx:renal_cect",
|
|
58
|
-
"summary": "Renal structures from arterial, venous and excretory phase CT.",
|
|
59
|
-
}
|
|
60
|
-
|
|
61
33
|
# Label values of the 104 TotalSegmentator structures plus background, as listed in the
|
|
62
34
|
# whole-body bundle's metadata.json ``channel_def``.
|
|
63
35
|
_WHOLE_BODY_LABELS: Mapping[int, str] = {
|
|
@@ -248,6 +220,33 @@ BUNDLES: dict[str, Bundle] = {
|
|
|
248
220
|
),
|
|
249
221
|
}
|
|
250
222
|
|
|
223
|
+
BRATS_MODEL = {
|
|
224
|
+
"id": "segresnet-brats",
|
|
225
|
+
"label": "SegResNet BraTS MRI",
|
|
226
|
+
"task": "segmentation",
|
|
227
|
+
"run": "segresnet_mlx.medmlx:brats",
|
|
228
|
+
# Measured MLX peak for a 240x240x155 four-sequence MRI; larger inputs need more.
|
|
229
|
+
"peak_memory_gb": 5.0,
|
|
230
|
+
"summary": "BraTS brain tumor segmentation from co-registered MRI sequences.",
|
|
231
|
+
"labels": {
|
|
232
|
+
str(value): name
|
|
233
|
+
for value, name in BUNDLES["brats_mri_segmentation"].labels.items()
|
|
234
|
+
},
|
|
235
|
+
}
|
|
236
|
+
RENAL_CECT_MODEL = {
|
|
237
|
+
"id": "segresnet-renal-cect",
|
|
238
|
+
"label": "SegResNet renal CECT",
|
|
239
|
+
"task": "segmentation",
|
|
240
|
+
"run": "segresnet_mlx.medmlx:renal_cect",
|
|
241
|
+
# Measured MLX peak for a 478x277x161 three-phase CT; larger inputs need more.
|
|
242
|
+
"peak_memory_gb": 4.1,
|
|
243
|
+
"summary": "Renal structures from arterial, venous and excretory phase CT.",
|
|
244
|
+
"labels": {
|
|
245
|
+
str(value): name
|
|
246
|
+
for value, name in BUNDLES["renalStructures_CECT_segmentation"].labels.items()
|
|
247
|
+
},
|
|
248
|
+
}
|
|
249
|
+
|
|
251
250
|
_ROLES = tuple(dict.fromkeys(role for bundle in BUNDLES.values() for role in bundle.roles))
|
|
252
251
|
# The renal bundle's Spacingd pixdim, in mm.
|
|
253
252
|
_RENAL_SPACING = (0.8, 0.8, 0.8)
|
|
@@ -325,9 +324,10 @@ def run(
|
|
|
325
324
|
and whole-body labels 0-104 as float32, BraTS labels 0, 1, 2, 4 as uint8, as the
|
|
326
325
|
bundles' ``SaveImaged`` wrote them. An existing mask is replaced only when
|
|
327
326
|
``overwrite`` is true; output aliases of input images are refused by a
|
|
328
|
-
preflight check.
|
|
329
|
-
NIfTI spatial-unit field
|
|
330
|
-
|
|
327
|
+
preflight check. Every argument is checked before weights or inputs are loaded.
|
|
328
|
+
The NIfTI spatial-unit field must be mm or unspecified (then assumed mm); other
|
|
329
|
+
units are refused, not converted. Paths are not locked against concurrent
|
|
330
|
+
replacement after the alias check.
|
|
331
331
|
|
|
332
332
|
``arithmetic_profile="compensated-fp32"`` uses Metal float pairs for
|
|
333
333
|
convolution and GroupNorm accumulation, with float32 layer boundaries.
|
|
@@ -369,16 +369,15 @@ def run(
|
|
|
369
369
|
``requires_human_review`` set to true.
|
|
370
370
|
|
|
371
371
|
Raises:
|
|
372
|
-
InvalidInputError: Unknown bundle or profile, missing or inapplicable
|
|
373
|
-
paths,
|
|
374
|
-
|
|
372
|
+
InvalidInputError: Unknown bundle or profile, missing, absent or inapplicable
|
|
373
|
+
input paths, ``overwrite`` or ``streaming`` not a bool, ``output_dir`` not a
|
|
374
|
+
directory, an existing output without ``overwrite``, or an unreadable,
|
|
375
|
+
non-3D, non-finite, non-mm or mismatched-grid NIfTI input.
|
|
375
376
|
AssetNotReadyError: The weights file is missing, not ``.safetensors``, or
|
|
376
377
|
does not match the bundle's network.
|
|
377
378
|
ModelExecutionError: Inference failed or produced a mask off the source grid
|
|
378
379
|
or with labels outside the bundle's set.
|
|
379
380
|
"""
|
|
380
|
-
if type(streaming) is not bool:
|
|
381
|
-
raise InvalidInputError("streaming must be boolean")
|
|
382
381
|
values = {
|
|
383
382
|
"arterial_path": arterial_path,
|
|
384
383
|
"venous_path": venous_path,
|
|
@@ -389,35 +388,11 @@ def run(
|
|
|
389
388
|
"flair_path": flair_path,
|
|
390
389
|
"image_path": image_path,
|
|
391
390
|
}
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
raise InvalidInputError(f"Unknown SegResNet arithmetic profile {arithmetic_profile!r}")
|
|
398
|
-
config = BUNDLES[bundle]
|
|
399
|
-
if arithmetic_profile == "compensated-fp48" and config.spec.upsample_mode != "deconv":
|
|
400
|
-
raise InvalidInputError("Paired precision requires transpose-convolution upsampling")
|
|
401
|
-
missing = [role for role in config.roles if values[role] is None]
|
|
402
|
-
extra = [role for role in _ROLES if role not in config.roles and values[role] is not None]
|
|
403
|
-
if missing or extra:
|
|
404
|
-
raise InvalidInputError(
|
|
405
|
-
f"{bundle} requires {', '.join(config.roles)}"
|
|
406
|
-
+ (f"; missing {', '.join(missing)}" if missing else "")
|
|
407
|
-
+ (f"; not applicable: {', '.join(extra)}" if extra else "")
|
|
408
|
-
)
|
|
409
|
-
output_root = Path(output_dir).expanduser().resolve()
|
|
410
|
-
mask_path = output_root / f"{bundle}_mask.nii.gz"
|
|
411
|
-
for role in config.roles:
|
|
412
|
-
value = values[role]
|
|
413
|
-
assert value is not None
|
|
414
|
-
source = Path(value).expanduser().resolve()
|
|
415
|
-
if mask_path.resolve() == source or (
|
|
416
|
-
mask_path.exists() and source.exists() and mask_path.samefile(source)
|
|
417
|
-
):
|
|
418
|
-
raise InvalidInputError("SegResNet output must differ from every input image")
|
|
419
|
-
if mask_path.exists() and not overwrite:
|
|
420
|
-
raise InvalidInputError(f"Output exists: {mask_path}; pass overwrite=true to replace it")
|
|
391
|
+
config, mask_path = _check_arguments(
|
|
392
|
+
bundle, values, output_dir, overwrite=overwrite,
|
|
393
|
+
arithmetic_profile=arithmetic_profile, streaming=streaming,
|
|
394
|
+
)
|
|
395
|
+
output_root = mask_path.parent
|
|
421
396
|
weights = _weights_file(weights_path)
|
|
422
397
|
started = time.perf_counter()
|
|
423
398
|
volumes = load_inputs([(role, values[role]) for role in config.roles])
|
|
@@ -520,6 +495,11 @@ def brats(
|
|
|
520
495
|
arithmetic_profile: ``torch-order-fp32`` (default) or ``compensated-fp32``;
|
|
521
496
|
``compensated-fp48`` requires the renal bundle.
|
|
522
497
|
"""
|
|
498
|
+
_check_arguments(
|
|
499
|
+
"brats_mri_segmentation",
|
|
500
|
+
{"t1c_path": t1c_path, "t1_path": t1_path, "t2_path": t2_path, "flair_path": flair_path},
|
|
501
|
+
output_dir, overwrite=overwrite, arithmetic_profile=arithmetic_profile,
|
|
502
|
+
)
|
|
523
503
|
folder = (
|
|
524
504
|
weights_dir("segresnet-brats")
|
|
525
505
|
if weights_path is None else Path(weights_path).expanduser()
|
|
@@ -561,6 +541,12 @@ def renal_cect(
|
|
|
561
541
|
arithmetic_profile: ``torch-order-fp32`` (default), ``compensated-fp32``
|
|
562
542
|
or ``compensated-fp48``; see ``run`` for their arithmetic contracts.
|
|
563
543
|
"""
|
|
544
|
+
_check_arguments(
|
|
545
|
+
"renalStructures_CECT_segmentation",
|
|
546
|
+
{"arterial_path": arterial_path, "venous_path": venous_path,
|
|
547
|
+
"excretory_path": excretory_path},
|
|
548
|
+
output_dir, overwrite=overwrite, arithmetic_profile=arithmetic_profile,
|
|
549
|
+
)
|
|
564
550
|
folder = (
|
|
565
551
|
weights_dir("segresnet-renal-cect")
|
|
566
552
|
if weights_path is None else Path(weights_path).expanduser()
|
|
@@ -573,6 +559,59 @@ def renal_cect(
|
|
|
573
559
|
)
|
|
574
560
|
|
|
575
561
|
|
|
562
|
+
def _check_arguments(
|
|
563
|
+
bundle: str,
|
|
564
|
+
values: Mapping[str, str | None],
|
|
565
|
+
output_dir: str,
|
|
566
|
+
*,
|
|
567
|
+
overwrite: bool,
|
|
568
|
+
arithmetic_profile: ArithmeticProfile,
|
|
569
|
+
streaming: bool = False,
|
|
570
|
+
) -> tuple[Bundle, Path]:
|
|
571
|
+
"""Check every ``run`` argument before weights, inputs or MLX are loaded.
|
|
572
|
+
|
|
573
|
+
Returns the bundle settings and the absolute mask path.
|
|
574
|
+
"""
|
|
575
|
+
if bundle not in BUNDLES:
|
|
576
|
+
raise InvalidInputError(
|
|
577
|
+
f"Unknown SegResNet bundle {bundle!r}; expected one of: {', '.join(BUNDLES)}"
|
|
578
|
+
)
|
|
579
|
+
if arithmetic_profile not in {"torch-order-fp32", "compensated-fp32", "compensated-fp48"}:
|
|
580
|
+
raise InvalidInputError(f"Unknown SegResNet arithmetic profile {arithmetic_profile!r}")
|
|
581
|
+
config = BUNDLES[bundle]
|
|
582
|
+
if arithmetic_profile == "compensated-fp48" and config.spec.upsample_mode != "deconv":
|
|
583
|
+
raise InvalidInputError("Paired precision requires transpose-convolution upsampling")
|
|
584
|
+
missing = [role for role in config.roles if values.get(role) is None]
|
|
585
|
+
extra = [
|
|
586
|
+
role for role in _ROLES if role not in config.roles and values.get(role) is not None
|
|
587
|
+
]
|
|
588
|
+
if missing or extra:
|
|
589
|
+
raise InvalidInputError(
|
|
590
|
+
f"{bundle} requires {', '.join(config.roles)}"
|
|
591
|
+
+ (f"; missing {', '.join(missing)}" if missing else "")
|
|
592
|
+
+ (f"; not applicable: {', '.join(extra)}" if extra else "")
|
|
593
|
+
)
|
|
594
|
+
sources = [Path(str(values[role])).expanduser() for role in config.roles]
|
|
595
|
+
for role, source in zip(config.roles, sources, strict=True):
|
|
596
|
+
if not source.is_file():
|
|
597
|
+
raise InvalidInputError(f"{role} not found: {source}")
|
|
598
|
+
for name, flag in (("overwrite", overwrite), ("streaming", streaming)):
|
|
599
|
+
if not isinstance(cast(object, flag), bool):
|
|
600
|
+
raise InvalidInputError(f"{name} must be true or false")
|
|
601
|
+
output_root = Path(output_dir).expanduser().resolve()
|
|
602
|
+
if output_root.exists() and not output_root.is_dir():
|
|
603
|
+
raise InvalidInputError(f"output_dir is not a directory: {output_root}")
|
|
604
|
+
mask_path = output_root / f"{bundle}_mask.nii.gz"
|
|
605
|
+
for source in sources:
|
|
606
|
+
if mask_path.resolve() == source.resolve() or (
|
|
607
|
+
mask_path.exists() and mask_path.samefile(source)
|
|
608
|
+
):
|
|
609
|
+
raise InvalidInputError("SegResNet output must differ from every input image")
|
|
610
|
+
if mask_path.exists() and not overwrite:
|
|
611
|
+
raise InvalidInputError(f"Output exists: {mask_path}; pass overwrite=true to replace it")
|
|
612
|
+
return config, mask_path
|
|
613
|
+
|
|
614
|
+
|
|
576
615
|
def preprocess_renal(volumes: list[Volume]) -> tuple[Float32Array, SpatialInverse]:
|
|
577
616
|
"""The renal bundle's ``preprocessing`` from ``EnsureChannelFirstd`` onward.
|
|
578
617
|
|
|
@@ -880,4 +919,4 @@ def write_atomic(path: Path, mask: MaskArray, affine: Float64Array, dtype: str)
|
|
|
880
919
|
Path(name).unlink(missing_ok=True)
|
|
881
920
|
|
|
882
921
|
|
|
883
|
-
__all__ = ["BRATS_MODEL", "BUNDLES", "
|
|
922
|
+
__all__ = ["BRATS_MODEL", "BUNDLES", "RENAL_CECT_MODEL", "brats", "renal_cect", "run"]
|
|
@@ -17,20 +17,6 @@ from medmlx_core.precision import Float32Operators
|
|
|
17
17
|
from segresnet_mlx.topology import ArithmeticProfile, SegResNetSpec
|
|
18
18
|
|
|
19
19
|
|
|
20
|
-
def group_mean(values: Array, mx: MLX) -> Array:
|
|
21
|
-
"""Mean over the last axis of ``(N, G, S)`` values, summed in 256-element tiles.
|
|
22
|
-
|
|
23
|
-
Tiling bounds the float32 accumulation depth of a group that spans a whole
|
|
24
|
-
volume. The last dimension must be nonempty. Returns ``(N, G, 1)``. ``SegResNet``
|
|
25
|
-
does not call this (its GroupNorm comes from the ``medmlx_core`` operators); it is
|
|
26
|
-
exercised by ``tests/test_equivalence.py``.
|
|
27
|
-
"""
|
|
28
|
-
size = int(values.shape[-1])
|
|
29
|
-
padded = mx.pad(values, [(0, 0), (0, 0), (0, (-size) % 256)])
|
|
30
|
-
tiles = mx.reshape(padded, (*values.shape[:2], -1, 256))
|
|
31
|
-
return mx.sum(mx.sum(tiles, axis=-1), axis=-1, keepdims=True) / size
|
|
32
|
-
|
|
33
|
-
|
|
34
20
|
class SegResNet:
|
|
35
21
|
"""Raw-logit forward pass for MONAI's 3-D, group-normalized SegResNet.
|
|
36
22
|
|
|
@@ -43,7 +29,7 @@ class SegResNet:
|
|
|
43
29
|
``segresnet_mlx.weights`` lists them. Inference only: dropout is omitted and
|
|
44
30
|
no activation is applied to the output.
|
|
45
31
|
|
|
46
|
-
``arithmetic_profile`` selects the accumulation scheme (see
|
|
32
|
+
``arithmetic_profile`` selects the accumulation scheme (see the README):
|
|
47
33
|
``"torch-order-fp32"`` (default), ``"compensated-fp32"``, or
|
|
48
34
|
``"compensated-fp48"``, which needs ``upsample_mode="deconv"`` and raises
|
|
49
35
|
``ValueError`` otherwise. The first two profiles use float32 layer boundaries;
|
|
@@ -6,7 +6,7 @@ import math
|
|
|
6
6
|
from dataclasses import dataclass
|
|
7
7
|
from typing import Literal
|
|
8
8
|
|
|
9
|
-
# Accumulation scheme for convolution and GroupNorm;
|
|
9
|
+
# Accumulation scheme for convolution and GroupNorm; the README describes the three
|
|
10
10
|
# profiles. ``compensated-fp48`` additionally requires transpose-convolution upsampling.
|
|
11
11
|
type ArithmeticProfile = Literal["torch-order-fp32", "compensated-fp32", "compensated-fp48"]
|
|
12
12
|
|
|
@@ -26,9 +26,6 @@ import numpy.typing as npt
|
|
|
26
26
|
from medmlx_core.geometry import (
|
|
27
27
|
_bmm as _bmm,
|
|
28
28
|
)
|
|
29
|
-
from medmlx_core.geometry import (
|
|
30
|
-
_fma as _fma,
|
|
31
|
-
)
|
|
32
29
|
from medmlx_core.geometry import (
|
|
33
30
|
_linspace_from_neg_one as _linspace_from_neg_one,
|
|
34
31
|
)
|
|
@@ -106,14 +103,6 @@ def correct_nifti_header(image: NiftiImage) -> None:
|
|
|
106
103
|
image.header.set_zooms(affine_to_spacing(image.affine, 3))
|
|
107
104
|
|
|
108
105
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
106
|
def orient(
|
|
118
107
|
data: Float32Array,
|
|
119
108
|
affine: Float64Array,
|
|
@@ -347,10 +336,6 @@ def write_nifti(path: Path, data: HostArray, affine: Float64Array, dtype: npt.DT
|
|
|
347
336
|
nib.save(image, str(path))
|
|
348
337
|
|
|
349
338
|
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
339
|
def _normalize_transform(shape: Sequence[int]) -> Float64Array:
|
|
355
340
|
"""``monai.networks.utils.normalize_transform`` (``align_corners=False``)."""
|
|
356
341
|
size = np.asarray(shape, dtype=np.float64)
|
|
@@ -362,10 +347,6 @@ def _normalize_transform(shape: Sequence[int]) -> Float64Array:
|
|
|
362
347
|
return result
|
|
363
348
|
|
|
364
349
|
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
350
|
def _theta(
|
|
370
351
|
xform: Float64Array,
|
|
371
352
|
in_size: Sequence[int],
|
segresnet_mlx-0.3.2/.gitignore
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
__pycache__/
|
|
2
|
-
*.py[cod]
|
|
3
|
-
.venv/
|
|
4
|
-
*.egg-info/
|
|
5
|
-
dist/
|
|
6
|
-
build/
|
|
7
|
-
.pytest_cache/
|
|
8
|
-
.ruff_cache/
|
|
9
|
-
|
|
10
|
-
# Checkpoints and converted weights are never committed.
|
|
11
|
-
checkpoints/
|
|
12
|
-
weights/
|
|
13
|
-
*.safetensors
|
|
14
|
-
*.npz
|
|
15
|
-
!tests/fixtures/*.npz
|
|
16
|
-
!tests/fixtures/*/*.npz
|
|
17
|
-
*.pt
|
|
18
|
-
*.pth
|
|
19
|
-
*.ckpt
|
|
20
|
-
|
|
21
|
-
# Imaging data is never committed.
|
|
22
|
-
data/
|
|
23
|
-
*.nii
|
|
24
|
-
*.nii.gz
|
|
25
|
-
*.dcm
|
|
26
|
-
.DS_Store
|
segresnet_mlx-0.3.2/PKG-INFO
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.5
|
|
2
|
-
Name: segresnet-mlx
|
|
3
|
-
Version: 0.3.2
|
|
4
|
-
Summary: Native MLX SegResNet with NumPy sliding-window logit inference
|
|
5
|
-
Project-URL: Homepage, https://medmlx.org
|
|
6
|
-
Project-URL: Repository, https://github.com/MedMLX/segresnet-mlx
|
|
7
|
-
Project-URL: Weights, https://huggingface.co/MedMLX/segresnet-renal-cect-mlx
|
|
8
|
-
Author: Joseph Sandoval, Alfredo Sandoval Jr.
|
|
9
|
-
License-Expression: Apache-2.0
|
|
10
|
-
License-File: LICENSE
|
|
11
|
-
License-File: THIRD_PARTY_NOTICES.md
|
|
12
|
-
Classifier: Operating System :: MacOS :: MacOS X
|
|
13
|
-
Requires-Python: <3.15,>=3.13
|
|
14
|
-
Requires-Dist: medmlx-core==0.2.5
|
|
15
|
-
Requires-Dist: nibabel<6,>=5.3
|
|
16
|
-
Requires-Dist: numpy<3,>=2.0
|
|
17
|
-
Provides-Extra: dev
|
|
18
|
-
Requires-Dist: hypothesis<7,>=6; extra == 'dev'
|
|
19
|
-
Requires-Dist: monai==1.6.1; extra == 'dev'
|
|
20
|
-
Requires-Dist: pyright==1.1.414; extra == 'dev'
|
|
21
|
-
Requires-Dist: pytest<10,>=8.4; extra == 'dev'
|
|
22
|
-
Requires-Dist: pytorch-ignite<0.6,>=0.4.11; extra == 'dev'
|
|
23
|
-
Requires-Dist: ruff<1,>=0.13; extra == 'dev'
|
|
24
|
-
Requires-Dist: torch<3,>=2.6; extra == 'dev'
|
|
25
|
-
Description-Content-Type: text/markdown
|
|
26
|
-
|
|
27
|
-
# segresnet-mlx
|
|
28
|
-
|
|
29
|
-
Segment brain tumors, renal structures and whole-body CT anatomy with MONAI SegResNet models in native MLX.
|
|
30
|
-
|
|
31
|
-
[Docs](https://github.com/MedMLX/segresnet-mlx/blob/main/docs/technical.md) · [BraTS weights](https://huggingface.co/MedMLX/segresnet-brats-mlx) · [Renal weights](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx) · [MedMLX](https://github.com/MedMLX)
|
|
32
|
-
|
|
33
|
-
| Input | Output |
|
|
34
|
-
| :--- | :--- |
|
|
35
|
-
| MRI sequences or CT volumes | Segmentation on the input grid |
|
|
36
|
-
|
|
37
|
-
**Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
|
|
38
|
-
|
|
39
|
-
## Install
|
|
40
|
-
|
|
41
|
-
```bash
|
|
42
|
-
uv venv --python 3.13
|
|
43
|
-
source .venv/bin/activate
|
|
44
|
-
uv pip install "segresnet-mlx>=0.3.2"
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
## Run
|
|
48
|
-
|
|
49
|
-
```python
|
|
50
|
-
from segresnet_mlx.medmlx import brats
|
|
51
|
-
|
|
52
|
-
result = brats(
|
|
53
|
-
t1c_path="t1c.nii.gz", t1_path="t1.nii.gz", t2_path="t2.nii.gz",
|
|
54
|
-
flair_path="flair.nii.gz", output_dir="out",
|
|
55
|
-
)
|
|
56
|
-
print(result["outputs"]["mask"])
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
The registered models are `segresnet-brats` and `segresnet-renal-cect`. Their `brats`
|
|
60
|
-
and `renal_cect` runners select the matching bundle internally and download
|
|
61
|
-
`MedMLX/segresnet-brats-mlx` or `MedMLX/segresnet-renal-cect-mlx` when `weights_path`
|
|
62
|
-
is omitted. An explicit folder contains `segresnet-brats.safetensors` for BraTS or
|
|
63
|
-
`segresnet-renal-cect.safetensors` for renal CECT. The renal runner takes
|
|
64
|
-
`arterial_path`, `venous_path` and `excretory_path`. Keep each model's input volumes
|
|
65
|
-
on one voxel grid.
|
|
66
|
-
|
|
67
|
-
The standalone `run(bundle=..., weights_path=...)` interface remains available for
|
|
68
|
-
explicit local checkpoints, including the whole-body CT variants. Published native
|
|
69
|
-
weights are also available for [renal CECT](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
|
|
70
|
-
and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
|
|
71
|
-
|
|
72
|
-
Downloaded commits are returned in `details.weights_revision`; explicit local
|
|
73
|
-
weights report `null` unless the folder carries a MedMLX download revision.
|
|
74
|
-
|
|
75
|
-
## License
|
|
76
|
-
|
|
77
|
-
[Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/main/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/main/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
|
|
78
|
-
|
|
79
|
-
For research and education. Outputs require human review.
|
segresnet_mlx-0.3.2/README.md
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
# segresnet-mlx
|
|
2
|
-
|
|
3
|
-
Segment brain tumors, renal structures and whole-body CT anatomy with MONAI SegResNet models in native MLX.
|
|
4
|
-
|
|
5
|
-
[Docs](https://github.com/MedMLX/segresnet-mlx/blob/main/docs/technical.md) · [BraTS weights](https://huggingface.co/MedMLX/segresnet-brats-mlx) · [Renal weights](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx) · [MedMLX](https://github.com/MedMLX)
|
|
6
|
-
|
|
7
|
-
| Input | Output |
|
|
8
|
-
| :--- | :--- |
|
|
9
|
-
| MRI sequences or CT volumes | Segmentation on the input grid |
|
|
10
|
-
|
|
11
|
-
**Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
|
|
12
|
-
|
|
13
|
-
## Install
|
|
14
|
-
|
|
15
|
-
```bash
|
|
16
|
-
uv venv --python 3.13
|
|
17
|
-
source .venv/bin/activate
|
|
18
|
-
uv pip install "segresnet-mlx>=0.3.2"
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
## Run
|
|
22
|
-
|
|
23
|
-
```python
|
|
24
|
-
from segresnet_mlx.medmlx import brats
|
|
25
|
-
|
|
26
|
-
result = brats(
|
|
27
|
-
t1c_path="t1c.nii.gz", t1_path="t1.nii.gz", t2_path="t2.nii.gz",
|
|
28
|
-
flair_path="flair.nii.gz", output_dir="out",
|
|
29
|
-
)
|
|
30
|
-
print(result["outputs"]["mask"])
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
The registered models are `segresnet-brats` and `segresnet-renal-cect`. Their `brats`
|
|
34
|
-
and `renal_cect` runners select the matching bundle internally and download
|
|
35
|
-
`MedMLX/segresnet-brats-mlx` or `MedMLX/segresnet-renal-cect-mlx` when `weights_path`
|
|
36
|
-
is omitted. An explicit folder contains `segresnet-brats.safetensors` for BraTS or
|
|
37
|
-
`segresnet-renal-cect.safetensors` for renal CECT. The renal runner takes
|
|
38
|
-
`arterial_path`, `venous_path` and `excretory_path`. Keep each model's input volumes
|
|
39
|
-
on one voxel grid.
|
|
40
|
-
|
|
41
|
-
The standalone `run(bundle=..., weights_path=...)` interface remains available for
|
|
42
|
-
explicit local checkpoints, including the whole-body CT variants. Published native
|
|
43
|
-
weights are also available for [renal CECT](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
|
|
44
|
-
and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
|
|
45
|
-
|
|
46
|
-
Downloaded commits are returned in `details.weights_revision`; explicit local
|
|
47
|
-
weights report `null` unless the folder carries a MedMLX download revision.
|
|
48
|
-
|
|
49
|
-
## License
|
|
50
|
-
|
|
51
|
-
[Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/main/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/main/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
|
|
52
|
-
|
|
53
|
-
For research and education. Outputs require human review.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|