segresnet-mlx 0.3.2__tar.gz → 0.3.3__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.3/.gitignore +38 -0
- segresnet_mlx-0.3.3/PKG-INFO +192 -0
- segresnet_mlx-0.3.3/README.md +152 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/THIRD_PARTY_NOTICES.md +1 -1
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/pyproject.toml +38 -7
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/__init__.py +1 -1
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/medmlx.py +102 -67
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/network.py +1 -1
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/topology.py +1 -1
- 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.3}/LICENSE +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/_arrays.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/_nifti.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/_records.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/_runtime.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/_types.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/inference.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/predictor.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/py.typed +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/telemetry.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/src/segresnet_mlx/transforms.py +0 -0
- {segresnet_mlx-0.3.2 → segresnet_mlx-0.3.3}/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,192 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: segresnet-mlx
|
|
3
|
+
Version: 0.3.3
|
|
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.3/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.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.3/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.3/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
|
+
## Use with MedMLX
|
|
65
|
+
|
|
66
|
+
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.
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
uv tool install --python 3.13 "medmlx[segment,mcp]"
|
|
70
|
+
MEDMLX="$(uv tool dir --bin --color never)/medmlx"
|
|
71
|
+
mkdir -p "$HOME/medmlx-work"
|
|
72
|
+
claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
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`.
|
|
76
|
+
|
|
77
|
+
> **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
|
|
78
|
+
|
|
79
|
+
## Install
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
uv venv --python 3.13
|
|
83
|
+
source .venv/bin/activate
|
|
84
|
+
uv pip install "segresnet-mlx>=0.3.3"
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Run
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from segresnet_mlx.medmlx import brats
|
|
91
|
+
|
|
92
|
+
result = brats(
|
|
93
|
+
t1c_path="t1c.nii.gz", t1_path="t1.nii.gz", t2_path="t2.nii.gz",
|
|
94
|
+
flair_path="flair.nii.gz", output_dir="out",
|
|
95
|
+
)
|
|
96
|
+
print(result["outputs"]["mask"])
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
The registered models are `segresnet-brats` and `segresnet-renal-cect`; their `brats`
|
|
100
|
+
and `renal_cect` runners select the matching bundle internally. The renal runner takes
|
|
101
|
+
`arterial_path`, `venous_path` and `excretory_path`. Keep each model's input volumes
|
|
102
|
+
on one voxel grid.
|
|
103
|
+
|
|
104
|
+
Omitting `weights_path` downloads `MedMLX/segresnet-brats-mlx` or
|
|
105
|
+
`MedMLX/segresnet-renal-cect-mlx` into the shared MedMLX cache on first use; interrupted
|
|
106
|
+
downloads resume and later runs work offline. With MedMLX installed, `medmlx setup
|
|
107
|
+
segresnet-brats` downloads it ahead of time. To use your own copy, pass a folder
|
|
108
|
+
containing `segresnet-brats.safetensors` for BraTS or `segresnet-renal-cect.safetensors`
|
|
109
|
+
for renal CECT as `weights_path`. `details.weights_revision` records the downloaded
|
|
110
|
+
commit, or `null` for a folder without a MedMLX download record.
|
|
111
|
+
|
|
112
|
+
The standalone `run(bundle=..., weights_path=...)` interface remains available for
|
|
113
|
+
explicit local checkpoints, including the whole-body CT variants. Published native
|
|
114
|
+
weights are also available for [renal CECT](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
|
|
115
|
+
and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
|
|
116
|
+
|
|
117
|
+
### Inputs and outputs
|
|
118
|
+
|
|
119
|
+
| Argument | Meaning |
|
|
120
|
+
| --- | --- |
|
|
121
|
+
| `t1c_path`, `t1_path`, `t2_path`, `flair_path` | `brats`: contrast T1, T1, T2 and FLAIR MRI in NIfTI |
|
|
122
|
+
| `arterial_path`, `venous_path`, `excretory_path` | `renal_cect`: arterial, venous and excretory CT in NIfTI |
|
|
123
|
+
| `output_dir` | Directory for `<bundle>_mask.nii.gz`; created if missing |
|
|
124
|
+
| `weights_path` | Optional `.safetensors` file or a folder containing it |
|
|
125
|
+
| `overwrite` | `False` by default; an existing mask is replaced only when `True` |
|
|
126
|
+
| `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` (renal only) |
|
|
127
|
+
|
|
128
|
+
Inputs are finite 3D volumes on one voxel grid, with spatial units in millimetres or
|
|
129
|
+
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,
|
|
130
|
+
4 neoplasm and 5 parenchyma. BraTS labels are uint8: 1 tumor core, 2 whole tumor
|
|
131
|
+
outside the core and 4 enhancing tumor.
|
|
132
|
+
|
|
133
|
+
`compensated-fp32` accumulates convolution and GroupNorm in paired Metal floats with
|
|
134
|
+
float32 layer outputs. `compensated-fp48` carries the pairs through the hidden layers
|
|
135
|
+
and stitches in float64 on the host; it needs the renal transposed-convolution decoder.
|
|
136
|
+
|
|
137
|
+
`run` returns `{"outputs": {"mask": path}, "details": {...}}`, with labels, shapes,
|
|
138
|
+
window settings, MLX device, peak memory and elapsed time. Invalid inputs raise
|
|
139
|
+
`InvalidInputError`; missing or mismatched weights raise `AssetNotReadyError`;
|
|
140
|
+
inference failures raise `ModelExecutionError`.
|
|
141
|
+
|
|
142
|
+
### Whole-body CT and streaming
|
|
143
|
+
|
|
144
|
+
`run` takes `bundle` and a `.safetensors` file as `weights_path`: `brats_mri_segmentation`,
|
|
145
|
+
`renalStructures_CECT_segmentation`, `wholeBody_ct_segmentation` (1.5 mm) or
|
|
146
|
+
`wholeBody_ct_segmentation_lowres` (3 mm). The whole-body bundles take one CT as
|
|
147
|
+
`image_path` and use `segresnet-wholebody-high.safetensors` or
|
|
148
|
+
`segresnet-wholebody-low.safetensors`. They write float32 labels 0–104 from the
|
|
149
|
+
bundle's `channel_def`: 1 spleen, 2 kidney_right, 3 kidney_left, 4 gallbladder,
|
|
150
|
+
5 liver, 6 stomach, 7 aorta, 8 inferior_vena_cava, 9 portal_vein_and_splenic_vein,
|
|
151
|
+
10 pancreas, 11–12 adrenal glands (right, left), 13–17 lung lobes (upper and lower
|
|
152
|
+
left, upper, middle and lower right), 18–41 vertebrae L5–C1, 42 esophagus, 43 trachea,
|
|
153
|
+
44–49 heart chambers and pulmonary artery, 50 brain, 51–54 iliac arteries and veins,
|
|
154
|
+
55 small bowel, 56 duodenum, 57 colon, 58–69 left ribs 1–12, 70–81 right ribs 1–12,
|
|
155
|
+
82–83 humerus, 84–85 scapula, 86–87 clavicula, 88–89 femur, 90–91 hip, 92 sacrum,
|
|
156
|
+
93 face, 94–99 gluteus maximus, medius and minimus, 100–101 autochthon, 102–103
|
|
157
|
+
iliopsoas and 104 urinary bladder.
|
|
158
|
+
|
|
159
|
+
`run(..., streaming=True, scratch_dir="scratch")` keeps blending intermediates and
|
|
160
|
+
logits in temporary mapped files instead of a full in-memory class volume. The files
|
|
161
|
+
are removed on success and failure; `scratch_dir` defaults to the system temporary
|
|
162
|
+
directory. The final label volume stays in memory.
|
|
163
|
+
|
|
164
|
+
### Python API
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
from pathlib import Path
|
|
168
|
+
|
|
169
|
+
import numpy as np
|
|
170
|
+
from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_model, predict_logits
|
|
171
|
+
|
|
172
|
+
spec = SegResNetSpec(3, 6, 32, upsample_mode="deconv") # renal CECT network
|
|
173
|
+
network = load_model(Path("segresnet-renal-cect.safetensors"), spec=spec)
|
|
174
|
+
patch = np.zeros((1, 3, 32, 32, 32), dtype=np.float32)
|
|
175
|
+
logits = forward_patch(network, patch) # float32 NCDHW -> float32 NumPy logits
|
|
176
|
+
config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
|
|
177
|
+
volume_logits = predict_logits(patch, config, network=network) # stitched sliding windows
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
|
|
181
|
+
`predict_logits` takes preprocessed arrays of any size and stitches the bundle's
|
|
182
|
+
sliding windows; neither normalizes intensities, applies activations or maps labels.
|
|
183
|
+
`load_model` checks tensor names, shapes and finite float32 values against
|
|
184
|
+
`required_shapes(spec)`, not checkpoint identity. `WindowTelemetry` and
|
|
185
|
+
`BundlePredictor` record bounded progress and timing. Inference needs Apple Silicon
|
|
186
|
+
with Metal and has no CPU fallback.
|
|
187
|
+
|
|
188
|
+
## License
|
|
189
|
+
|
|
190
|
+
[Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.3/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.3/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
|
|
191
|
+
|
|
192
|
+
For research and education. Outputs require human review.
|
|
@@ -0,0 +1,152 @@
|
|
|
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.3/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.3/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
|
+
## Use with MedMLX
|
|
25
|
+
|
|
26
|
+
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.
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
uv tool install --python 3.13 "medmlx[segment,mcp]"
|
|
30
|
+
MEDMLX="$(uv tool dir --bin --color never)/medmlx"
|
|
31
|
+
mkdir -p "$HOME/medmlx-work"
|
|
32
|
+
claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
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`.
|
|
36
|
+
|
|
37
|
+
> **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
|
|
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.3"
|
|
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. The renal runner takes
|
|
61
|
+
`arterial_path`, `venous_path` and `excretory_path`. Keep each model's input volumes
|
|
62
|
+
on one voxel grid.
|
|
63
|
+
|
|
64
|
+
Omitting `weights_path` downloads `MedMLX/segresnet-brats-mlx` or
|
|
65
|
+
`MedMLX/segresnet-renal-cect-mlx` into the shared MedMLX cache on first use; interrupted
|
|
66
|
+
downloads resume and later runs work offline. With MedMLX installed, `medmlx setup
|
|
67
|
+
segresnet-brats` downloads it ahead of time. To use your own copy, pass a folder
|
|
68
|
+
containing `segresnet-brats.safetensors` for BraTS or `segresnet-renal-cect.safetensors`
|
|
69
|
+
for renal CECT as `weights_path`. `details.weights_revision` records the downloaded
|
|
70
|
+
commit, or `null` for a folder without a MedMLX download record.
|
|
71
|
+
|
|
72
|
+
The standalone `run(bundle=..., weights_path=...)` interface remains available for
|
|
73
|
+
explicit local checkpoints, including the whole-body CT variants. Published native
|
|
74
|
+
weights are also available for [renal CECT](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
|
|
75
|
+
and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
|
|
76
|
+
|
|
77
|
+
### Inputs and outputs
|
|
78
|
+
|
|
79
|
+
| Argument | Meaning |
|
|
80
|
+
| --- | --- |
|
|
81
|
+
| `t1c_path`, `t1_path`, `t2_path`, `flair_path` | `brats`: contrast T1, T1, T2 and FLAIR MRI in NIfTI |
|
|
82
|
+
| `arterial_path`, `venous_path`, `excretory_path` | `renal_cect`: arterial, venous and excretory CT in NIfTI |
|
|
83
|
+
| `output_dir` | Directory for `<bundle>_mask.nii.gz`; created if missing |
|
|
84
|
+
| `weights_path` | Optional `.safetensors` file or a folder containing it |
|
|
85
|
+
| `overwrite` | `False` by default; an existing mask is replaced only when `True` |
|
|
86
|
+
| `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` (renal only) |
|
|
87
|
+
|
|
88
|
+
Inputs are finite 3D volumes on one voxel grid, with spatial units in millimetres or
|
|
89
|
+
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,
|
|
90
|
+
4 neoplasm and 5 parenchyma. BraTS labels are uint8: 1 tumor core, 2 whole tumor
|
|
91
|
+
outside the core and 4 enhancing tumor.
|
|
92
|
+
|
|
93
|
+
`compensated-fp32` accumulates convolution and GroupNorm in paired Metal floats with
|
|
94
|
+
float32 layer outputs. `compensated-fp48` carries the pairs through the hidden layers
|
|
95
|
+
and stitches in float64 on the host; it needs the renal transposed-convolution decoder.
|
|
96
|
+
|
|
97
|
+
`run` returns `{"outputs": {"mask": path}, "details": {...}}`, with labels, shapes,
|
|
98
|
+
window settings, MLX device, peak memory and elapsed time. Invalid inputs raise
|
|
99
|
+
`InvalidInputError`; missing or mismatched weights raise `AssetNotReadyError`;
|
|
100
|
+
inference failures raise `ModelExecutionError`.
|
|
101
|
+
|
|
102
|
+
### Whole-body CT and streaming
|
|
103
|
+
|
|
104
|
+
`run` takes `bundle` and a `.safetensors` file as `weights_path`: `brats_mri_segmentation`,
|
|
105
|
+
`renalStructures_CECT_segmentation`, `wholeBody_ct_segmentation` (1.5 mm) or
|
|
106
|
+
`wholeBody_ct_segmentation_lowres` (3 mm). The whole-body bundles take one CT as
|
|
107
|
+
`image_path` and use `segresnet-wholebody-high.safetensors` or
|
|
108
|
+
`segresnet-wholebody-low.safetensors`. They write float32 labels 0–104 from the
|
|
109
|
+
bundle's `channel_def`: 1 spleen, 2 kidney_right, 3 kidney_left, 4 gallbladder,
|
|
110
|
+
5 liver, 6 stomach, 7 aorta, 8 inferior_vena_cava, 9 portal_vein_and_splenic_vein,
|
|
111
|
+
10 pancreas, 11–12 adrenal glands (right, left), 13–17 lung lobes (upper and lower
|
|
112
|
+
left, upper, middle and lower right), 18–41 vertebrae L5–C1, 42 esophagus, 43 trachea,
|
|
113
|
+
44–49 heart chambers and pulmonary artery, 50 brain, 51–54 iliac arteries and veins,
|
|
114
|
+
55 small bowel, 56 duodenum, 57 colon, 58–69 left ribs 1–12, 70–81 right ribs 1–12,
|
|
115
|
+
82–83 humerus, 84–85 scapula, 86–87 clavicula, 88–89 femur, 90–91 hip, 92 sacrum,
|
|
116
|
+
93 face, 94–99 gluteus maximus, medius and minimus, 100–101 autochthon, 102–103
|
|
117
|
+
iliopsoas and 104 urinary bladder.
|
|
118
|
+
|
|
119
|
+
`run(..., streaming=True, scratch_dir="scratch")` keeps blending intermediates and
|
|
120
|
+
logits in temporary mapped files instead of a full in-memory class volume. The files
|
|
121
|
+
are removed on success and failure; `scratch_dir` defaults to the system temporary
|
|
122
|
+
directory. The final label volume stays in memory.
|
|
123
|
+
|
|
124
|
+
### Python API
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from pathlib import Path
|
|
128
|
+
|
|
129
|
+
import numpy as np
|
|
130
|
+
from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_model, predict_logits
|
|
131
|
+
|
|
132
|
+
spec = SegResNetSpec(3, 6, 32, upsample_mode="deconv") # renal CECT network
|
|
133
|
+
network = load_model(Path("segresnet-renal-cect.safetensors"), spec=spec)
|
|
134
|
+
patch = np.zeros((1, 3, 32, 32, 32), dtype=np.float32)
|
|
135
|
+
logits = forward_patch(network, patch) # float32 NCDHW -> float32 NumPy logits
|
|
136
|
+
config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
|
|
137
|
+
volume_logits = predict_logits(patch, config, network=network) # stitched sliding windows
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
`forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
|
|
141
|
+
`predict_logits` takes preprocessed arrays of any size and stitches the bundle's
|
|
142
|
+
sliding windows; neither normalizes intensities, applies activations or maps labels.
|
|
143
|
+
`load_model` checks tensor names, shapes and finite float32 values against
|
|
144
|
+
`required_shapes(spec)`, not checkpoint identity. `WindowTelemetry` and
|
|
145
|
+
`BundlePredictor` record bounded progress and timing. Inference needs Apple Silicon
|
|
146
|
+
with Metal and has no CPU fallback.
|
|
147
|
+
|
|
148
|
+
## License
|
|
149
|
+
|
|
150
|
+
[Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.3/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.3/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
|
|
151
|
+
|
|
152
|
+
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.3"
|
|
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==0.2.
|
|
42
|
+
"medmlx-core==0.2.6",
|
|
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.3/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 = [
|
|
@@ -52,6 +82,7 @@ markers = ["mlx: native MLX execution requiring Apple Silicon Metal"]
|
|
|
52
82
|
[tool.uv]
|
|
53
83
|
constraint-dependencies = ["setuptools>=84.1.0", "filelock>=4.2.1", ]
|
|
54
84
|
environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
|
|
85
|
+
required-environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
|
|
55
86
|
|
|
56
87
|
[tool.ruff]
|
|
57
88
|
line-length = 100
|
|
@@ -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.3"
|
|
23
23
|
|
|
24
24
|
_EXPORTS = {
|
|
25
25
|
"BUNDLE_CONFIGS": "segresnet_mlx.predictor",
|
|
@@ -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,29 @@ 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
|
+
"summary": "BraTS brain tumor segmentation from co-registered MRI sequences.",
|
|
229
|
+
"labels": {
|
|
230
|
+
str(value): name
|
|
231
|
+
for value, name in BUNDLES["brats_mri_segmentation"].labels.items()
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
RENAL_CECT_MODEL = {
|
|
235
|
+
"id": "segresnet-renal-cect",
|
|
236
|
+
"label": "SegResNet renal CECT",
|
|
237
|
+
"task": "segmentation",
|
|
238
|
+
"run": "segresnet_mlx.medmlx:renal_cect",
|
|
239
|
+
"summary": "Renal structures from arterial, venous and excretory phase CT.",
|
|
240
|
+
"labels": {
|
|
241
|
+
str(value): name
|
|
242
|
+
for value, name in BUNDLES["renalStructures_CECT_segmentation"].labels.items()
|
|
243
|
+
},
|
|
244
|
+
}
|
|
245
|
+
|
|
251
246
|
_ROLES = tuple(dict.fromkeys(role for bundle in BUNDLES.values() for role in bundle.roles))
|
|
252
247
|
# The renal bundle's Spacingd pixdim, in mm.
|
|
253
248
|
_RENAL_SPACING = (0.8, 0.8, 0.8)
|
|
@@ -325,9 +320,10 @@ def run(
|
|
|
325
320
|
and whole-body labels 0-104 as float32, BraTS labels 0, 1, 2, 4 as uint8, as the
|
|
326
321
|
bundles' ``SaveImaged`` wrote them. An existing mask is replaced only when
|
|
327
322
|
``overwrite`` is true; output aliases of input images are refused by a
|
|
328
|
-
preflight check.
|
|
329
|
-
NIfTI spatial-unit field
|
|
330
|
-
|
|
323
|
+
preflight check. Every argument is checked before weights or inputs are loaded.
|
|
324
|
+
The NIfTI spatial-unit field must be mm or unspecified (then assumed mm); other
|
|
325
|
+
units are refused, not converted. Paths are not locked against concurrent
|
|
326
|
+
replacement after the alias check.
|
|
331
327
|
|
|
332
328
|
``arithmetic_profile="compensated-fp32"`` uses Metal float pairs for
|
|
333
329
|
convolution and GroupNorm accumulation, with float32 layer boundaries.
|
|
@@ -369,16 +365,15 @@ def run(
|
|
|
369
365
|
``requires_human_review`` set to true.
|
|
370
366
|
|
|
371
367
|
Raises:
|
|
372
|
-
InvalidInputError: Unknown bundle or profile, missing or inapplicable
|
|
373
|
-
paths,
|
|
374
|
-
|
|
368
|
+
InvalidInputError: Unknown bundle or profile, missing, absent or inapplicable
|
|
369
|
+
input paths, ``overwrite`` or ``streaming`` not a bool, ``output_dir`` not a
|
|
370
|
+
directory, an existing output without ``overwrite``, or an unreadable,
|
|
371
|
+
non-3D, non-finite, non-mm or mismatched-grid NIfTI input.
|
|
375
372
|
AssetNotReadyError: The weights file is missing, not ``.safetensors``, or
|
|
376
373
|
does not match the bundle's network.
|
|
377
374
|
ModelExecutionError: Inference failed or produced a mask off the source grid
|
|
378
375
|
or with labels outside the bundle's set.
|
|
379
376
|
"""
|
|
380
|
-
if type(streaming) is not bool:
|
|
381
|
-
raise InvalidInputError("streaming must be boolean")
|
|
382
377
|
values = {
|
|
383
378
|
"arterial_path": arterial_path,
|
|
384
379
|
"venous_path": venous_path,
|
|
@@ -389,35 +384,11 @@ def run(
|
|
|
389
384
|
"flair_path": flair_path,
|
|
390
385
|
"image_path": image_path,
|
|
391
386
|
}
|
|
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")
|
|
387
|
+
config, mask_path = _check_arguments(
|
|
388
|
+
bundle, values, output_dir, overwrite=overwrite,
|
|
389
|
+
arithmetic_profile=arithmetic_profile, streaming=streaming,
|
|
390
|
+
)
|
|
391
|
+
output_root = mask_path.parent
|
|
421
392
|
weights = _weights_file(weights_path)
|
|
422
393
|
started = time.perf_counter()
|
|
423
394
|
volumes = load_inputs([(role, values[role]) for role in config.roles])
|
|
@@ -520,6 +491,11 @@ def brats(
|
|
|
520
491
|
arithmetic_profile: ``torch-order-fp32`` (default) or ``compensated-fp32``;
|
|
521
492
|
``compensated-fp48`` requires the renal bundle.
|
|
522
493
|
"""
|
|
494
|
+
_check_arguments(
|
|
495
|
+
"brats_mri_segmentation",
|
|
496
|
+
{"t1c_path": t1c_path, "t1_path": t1_path, "t2_path": t2_path, "flair_path": flair_path},
|
|
497
|
+
output_dir, overwrite=overwrite, arithmetic_profile=arithmetic_profile,
|
|
498
|
+
)
|
|
523
499
|
folder = (
|
|
524
500
|
weights_dir("segresnet-brats")
|
|
525
501
|
if weights_path is None else Path(weights_path).expanduser()
|
|
@@ -561,6 +537,12 @@ def renal_cect(
|
|
|
561
537
|
arithmetic_profile: ``torch-order-fp32`` (default), ``compensated-fp32``
|
|
562
538
|
or ``compensated-fp48``; see ``run`` for their arithmetic contracts.
|
|
563
539
|
"""
|
|
540
|
+
_check_arguments(
|
|
541
|
+
"renalStructures_CECT_segmentation",
|
|
542
|
+
{"arterial_path": arterial_path, "venous_path": venous_path,
|
|
543
|
+
"excretory_path": excretory_path},
|
|
544
|
+
output_dir, overwrite=overwrite, arithmetic_profile=arithmetic_profile,
|
|
545
|
+
)
|
|
564
546
|
folder = (
|
|
565
547
|
weights_dir("segresnet-renal-cect")
|
|
566
548
|
if weights_path is None else Path(weights_path).expanduser()
|
|
@@ -573,6 +555,59 @@ def renal_cect(
|
|
|
573
555
|
)
|
|
574
556
|
|
|
575
557
|
|
|
558
|
+
def _check_arguments(
|
|
559
|
+
bundle: str,
|
|
560
|
+
values: Mapping[str, str | None],
|
|
561
|
+
output_dir: str,
|
|
562
|
+
*,
|
|
563
|
+
overwrite: bool,
|
|
564
|
+
arithmetic_profile: ArithmeticProfile,
|
|
565
|
+
streaming: bool = False,
|
|
566
|
+
) -> tuple[Bundle, Path]:
|
|
567
|
+
"""Check every ``run`` argument before weights, inputs or MLX are loaded.
|
|
568
|
+
|
|
569
|
+
Returns the bundle settings and the absolute mask path.
|
|
570
|
+
"""
|
|
571
|
+
if bundle not in BUNDLES:
|
|
572
|
+
raise InvalidInputError(
|
|
573
|
+
f"Unknown SegResNet bundle {bundle!r}; expected one of: {', '.join(BUNDLES)}"
|
|
574
|
+
)
|
|
575
|
+
if arithmetic_profile not in {"torch-order-fp32", "compensated-fp32", "compensated-fp48"}:
|
|
576
|
+
raise InvalidInputError(f"Unknown SegResNet arithmetic profile {arithmetic_profile!r}")
|
|
577
|
+
config = BUNDLES[bundle]
|
|
578
|
+
if arithmetic_profile == "compensated-fp48" and config.spec.upsample_mode != "deconv":
|
|
579
|
+
raise InvalidInputError("Paired precision requires transpose-convolution upsampling")
|
|
580
|
+
missing = [role for role in config.roles if values.get(role) is None]
|
|
581
|
+
extra = [
|
|
582
|
+
role for role in _ROLES if role not in config.roles and values.get(role) is not None
|
|
583
|
+
]
|
|
584
|
+
if missing or extra:
|
|
585
|
+
raise InvalidInputError(
|
|
586
|
+
f"{bundle} requires {', '.join(config.roles)}"
|
|
587
|
+
+ (f"; missing {', '.join(missing)}" if missing else "")
|
|
588
|
+
+ (f"; not applicable: {', '.join(extra)}" if extra else "")
|
|
589
|
+
)
|
|
590
|
+
sources = [Path(str(values[role])).expanduser() for role in config.roles]
|
|
591
|
+
for role, source in zip(config.roles, sources, strict=True):
|
|
592
|
+
if not source.is_file():
|
|
593
|
+
raise InvalidInputError(f"{role} not found: {source}")
|
|
594
|
+
for name, flag in (("overwrite", overwrite), ("streaming", streaming)):
|
|
595
|
+
if not isinstance(cast(object, flag), bool):
|
|
596
|
+
raise InvalidInputError(f"{name} must be true or false")
|
|
597
|
+
output_root = Path(output_dir).expanduser().resolve()
|
|
598
|
+
if output_root.exists() and not output_root.is_dir():
|
|
599
|
+
raise InvalidInputError(f"output_dir is not a directory: {output_root}")
|
|
600
|
+
mask_path = output_root / f"{bundle}_mask.nii.gz"
|
|
601
|
+
for source in sources:
|
|
602
|
+
if mask_path.resolve() == source.resolve() or (
|
|
603
|
+
mask_path.exists() and mask_path.samefile(source)
|
|
604
|
+
):
|
|
605
|
+
raise InvalidInputError("SegResNet output must differ from every input image")
|
|
606
|
+
if mask_path.exists() and not overwrite:
|
|
607
|
+
raise InvalidInputError(f"Output exists: {mask_path}; pass overwrite=true to replace it")
|
|
608
|
+
return config, mask_path
|
|
609
|
+
|
|
610
|
+
|
|
576
611
|
def preprocess_renal(volumes: list[Volume]) -> tuple[Float32Array, SpatialInverse]:
|
|
577
612
|
"""The renal bundle's ``preprocessing`` from ``EnsureChannelFirstd`` onward.
|
|
578
613
|
|
|
@@ -880,4 +915,4 @@ def write_atomic(path: Path, mask: MaskArray, affine: Float64Array, dtype: str)
|
|
|
880
915
|
Path(name).unlink(missing_ok=True)
|
|
881
916
|
|
|
882
917
|
|
|
883
|
-
__all__ = ["BRATS_MODEL", "BUNDLES", "
|
|
918
|
+
__all__ = ["BRATS_MODEL", "BUNDLES", "RENAL_CECT_MODEL", "brats", "renal_cect", "run"]
|
|
@@ -43,7 +43,7 @@ class SegResNet:
|
|
|
43
43
|
``segresnet_mlx.weights`` lists them. Inference only: dropout is omitted and
|
|
44
44
|
no activation is applied to the output.
|
|
45
45
|
|
|
46
|
-
``arithmetic_profile`` selects the accumulation scheme (see
|
|
46
|
+
``arithmetic_profile`` selects the accumulation scheme (see the README):
|
|
47
47
|
``"torch-order-fp32"`` (default), ``"compensated-fp32"``, or
|
|
48
48
|
``"compensated-fp48"``, which needs ``upsample_mode="deconv"`` and raises
|
|
49
49
|
``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
|
|
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
|
|
File without changes
|
|
File without changes
|