segresnet-mlx 0.3.3__tar.gz → 0.3.6__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.
Files changed (22) hide show
  1. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/PKG-INFO +95 -68
  2. segresnet_mlx-0.3.6/README.md +179 -0
  3. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/pyproject.toml +5 -8
  4. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/__init__.py +1 -1
  5. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_types.py +1 -18
  6. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/medmlx.py +66 -28
  7. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/network.py +0 -14
  8. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/predictor.py +1 -1
  9. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/transforms.py +17 -19
  10. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/weights.py +10 -4
  11. segresnet_mlx-0.3.3/README.md +0 -152
  12. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/.gitignore +0 -0
  13. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/LICENSE +0 -0
  14. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/THIRD_PARTY_NOTICES.md +0 -0
  15. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_arrays.py +0 -0
  16. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_nifti.py +0 -0
  17. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_records.py +0 -0
  18. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_runtime.py +0 -0
  19. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/inference.py +0 -0
  20. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/py.typed +0 -0
  21. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/telemetry.py +0 -0
  22. {segresnet_mlx-0.3.3 → segresnet_mlx-0.3.6}/src/segresnet_mlx/topology.py +0 -0
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: segresnet-mlx
3
- Version: 0.3.3
3
+ Version: 0.3.6
4
4
  Summary: Segment brain tumors, renal structures and whole-body CT anatomy with MONAI SegResNet models in native MLX
5
5
  Project-URL: Homepage, https://medmlx.org
6
- Project-URL: Documentation, https://github.com/MedMLX/segresnet-mlx/blob/v0.3.3/README.md
6
+ Project-URL: Documentation, https://github.com/MedMLX/segresnet-mlx/blob/v0.3.6/README.md
7
7
  Project-URL: Repository, https://github.com/MedMLX/segresnet-mlx
8
8
  Project-URL: Issues, https://github.com/MedMLX/segresnet-mlx/issues
9
9
  Project-URL: Weights, https://huggingface.co/models?author=MedMLX&search=segresnet
@@ -24,7 +24,7 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
24
  Classifier: Topic :: Scientific/Engineering :: Image Processing
25
25
  Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
26
26
  Requires-Python: <3.14,>=3.13
27
- Requires-Dist: medmlx-core==0.2.6
27
+ Requires-Dist: medmlx-core<0.3,>=0.2.6
28
28
  Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
29
29
  Requires-Dist: nibabel<6,>=5.3
30
30
  Requires-Dist: numpy<3,>=2.0
@@ -46,14 +46,14 @@ Segment brain tumors, renal structures and whole-body CT anatomy with MONAI SegR
46
46
 
47
47
  [![PyPI](https://img.shields.io/pypi/v/segresnet-mlx)](https://pypi.org/project/segresnet-mlx/)
48
48
  [![Python](https://img.shields.io/pypi/pyversions/segresnet-mlx)](https://pypi.org/project/segresnet-mlx/)
49
- [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.3/LICENSE)
49
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.6/LICENSE)
50
50
  [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
51
51
  [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/segresnet-brats-mlx)
52
52
  [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
53
53
 
54
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
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%">
56
+ <img src="https://raw.githubusercontent.com/MedMLX/segresnet-mlx/main/docs/example.png" alt="Brain tumor segmentation in axial, coronal and sagittal MRI" width="100%">
57
57
 
58
58
  </div>
59
59
 
@@ -61,27 +61,17 @@ Segment brain tumors, renal structures and whole-body CT anatomy with MONAI SegR
61
61
  | :--- | :--- |
62
62
  | MRI sequences or CT volumes | Segmentation on the input grid |
63
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.
64
+ | Model | Weights download | Peak MLX memory | Measured on |
65
+ | :--- | ---: | ---: | :--- |
66
+ | `segresnet-brats` | 19 MB | 4.9 GB | 240×240×155 four-sequence brain MRI |
67
+ | `segresnet-renal-cect` | 76 MB | 4.0 GB | 478×277×161 three-phase CT |
78
68
 
79
69
  ## Install
80
70
 
81
71
  ```bash
82
72
  uv venv --python 3.13
83
73
  source .venv/bin/activate
84
- uv pip install "segresnet-mlx>=0.3.3"
74
+ uv pip install "segresnet-mlx>=0.3.6"
85
75
  ```
86
76
 
87
77
  ## Run
@@ -96,23 +86,21 @@ result = brats(
96
86
  print(result["outputs"]["mask"])
97
87
  ```
98
88
 
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.
89
+ ### Models and weights
90
+
91
+ Each runner selects its bundle internally. Keep each model's input volumes on one voxel
92
+ grid.
103
93
 
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.
94
+ | Model | Runner | Inputs | Weights | Local file |
95
+ | :--- | :--- | :--- | :--- | :--- |
96
+ | `segresnet-brats` | `brats` | `t1c_path`, `t1_path`, `t2_path`, `flair_path` | `MedMLX/segresnet-brats-mlx` | `segresnet-brats.safetensors` |
97
+ | `segresnet-renal-cect` | `renal_cect` | `arterial_path`, `venous_path`, `excretory_path` | [`MedMLX/segresnet-renal-cect-mlx`](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx) | `segresnet-renal-cect.safetensors` |
111
98
 
99
+ Weights download on first use; `medmlx setup segresnet-brats` downloads ahead of time.
100
+ For local weights, pass a folder containing the model's local file as `weights_path`.
112
101
  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).
102
+ explicit local checkpoints, including the whole-body CT variants, whose native weights
103
+ are published as [`MedMLX/segresnet-wholebody-mlx`](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
116
104
 
117
105
  ### Inputs and outputs
118
106
 
@@ -126,35 +114,61 @@ and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
126
114
  | `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` (renal only) |
127
115
 
128
116
  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.
117
+ unspecified. The mask is written on the input grid as the NIfTI reader corrects it.
132
118
 
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.
119
+ | Model | Mask dtype | Labels |
120
+ | :--- | :--- | :--- |
121
+ | `segresnet-brats` | uint8 | 1 necrotic/non-enhancing tumor core, 2 peritumoral edema, 4 enhancing tumor |
122
+ | `segresnet-renal-cect` | float32 | 1 artery, 2 vein, 3 ureter, 4 neoplasm, 5 parenchyma |
136
123
 
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`.
124
+ | `arithmetic_profile` | Arithmetic |
125
+ | :--- | :--- |
126
+ | `torch-order-fp32` (default) | The default float32 profile |
127
+ | `compensated-fp32` | Convolution and GroupNorm accumulate in paired Metal floats, with float32 layer outputs |
128
+ | `compensated-fp48` | The pairs carry through the hidden layers and stitching runs in float64 on the host; needs the renal transposed-convolution decoder (renal only) |
129
+
130
+ `run` returns `{"outputs": {"mask": path}, "details": {...}}`, with run metadata in `details`.
131
+ Invalid inputs raise `InvalidInputError`; missing or mismatched weights raise
132
+ `AssetNotReadyError`; inference failures raise `ModelExecutionError`.
141
133
 
142
134
  ### Whole-body CT and streaming
143
135
 
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.
136
+ `run` takes `bundle` and a `.safetensors` file as `weights_path`:
137
+
138
+ | `bundle` | Weights file | Input |
139
+ | :--- | :--- | :--- |
140
+ | `brats_mri_segmentation` | `segresnet-brats.safetensors` | Four MRI sequences |
141
+ | `renalStructures_CECT_segmentation` | `segresnet-renal-cect.safetensors` | Three CT phases |
142
+ | `wholeBody_ct_segmentation` (1.5 mm) | `segresnet-wholebody-high.safetensors` | One CT as `image_path` |
143
+ | `wholeBody_ct_segmentation_lowres` (3 mm) | `segresnet-wholebody-low.safetensors` | One CT as `image_path` |
144
+
145
+ The whole-body bundles write float32 labels 0–104 from the bundle's `channel_def`:
146
+
147
+ | Labels | Structures |
148
+ | :--- | :--- |
149
+ | 1–10 | spleen, kidney_right, kidney_left, gallbladder, liver, stomach, aorta, inferior_vena_cava, portal_vein_and_splenic_vein, pancreas |
150
+ | 11–12 | adrenal glands (right, left) |
151
+ | 13–17 | lung lobes (upper and lower left, upper, middle and lower right) |
152
+ | 18–41 | vertebrae L5–C1 |
153
+ | 42–43 | esophagus, trachea |
154
+ | 44–49 | heart chambers and pulmonary artery |
155
+ | 50 | brain |
156
+ | 51–54 | iliac arteries and veins |
157
+ | 55 | small bowel |
158
+ | 56 | duodenum |
159
+ | 57 | colon |
160
+ | 58–69 | left ribs 1–12 |
161
+ | 70–81 | right ribs 1–12 |
162
+ | 82–83 | humerus |
163
+ | 84–85 | scapula |
164
+ | 86–87 | clavicula |
165
+ | 88–89 | femur |
166
+ | 90–91 | hip |
167
+ | 92–93 | sacrum, face |
168
+ | 94–99 | gluteus maximus, medius and minimus |
169
+ | 100–101 | autochthon |
170
+ | 102–103 | iliopsoas |
171
+ | 104 | urinary bladder |
158
172
 
159
173
  `run(..., streaming=True, scratch_dir="scratch")` keeps blending intermediates and
160
174
  logits in temporary mapped files instead of a full in-memory class volume. The files
@@ -177,16 +191,29 @@ config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
177
191
  volume_logits = predict_logits(patch, config, network=network) # stitched sliding windows
178
192
  ```
179
193
 
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.
194
+ - `forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
195
+ - `predict_logits` takes preprocessed arrays of any size and stitches the bundle's
196
+ sliding windows. Neither normalizes intensities, applies activations or maps labels.
197
+ - `load_model` checks tensor names, shapes and finite float32 values against
198
+ `required_shapes(spec)`.
199
+ - `WindowTelemetry` and `BundlePredictor` record bounded progress and timing.
200
+ - Inference requires Apple Silicon with Metal.
187
201
 
188
- ## License
202
+ ## Use with MedMLX
203
+
204
+ Use the [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) to run `segresnet-brats` and `segresnet-renal-cect` from an MCP client. Weights download on first use.
189
205
 
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.
206
+ ```sh
207
+ uv tool install --python 3.13 "medmlx[segment,mcp]"
208
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
209
+ mkdir -p "$HOME/medmlx-work"
210
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
211
+ ```
212
+
213
+ 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`.
214
+
215
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
216
+
217
+ ## License
191
218
 
192
- For research and education. Outputs require human review.
219
+ [Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.6/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.6/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -0,0 +1,179 @@
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
+ [![PyPI](https://img.shields.io/pypi/v/segresnet-mlx)](https://pypi.org/project/segresnet-mlx/)
8
+ [![Python](https://img.shields.io/pypi/pyversions/segresnet-mlx)](https://pypi.org/project/segresnet-mlx/)
9
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.6/LICENSE)
10
+ [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
11
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/segresnet-brats-mlx)
12
+ [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](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/main/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
+ | Model | Weights download | Peak MLX memory | Measured on |
25
+ | :--- | ---: | ---: | :--- |
26
+ | `segresnet-brats` | 19 MB | 4.9 GB | 240×240×155 four-sequence brain MRI |
27
+ | `segresnet-renal-cect` | 76 MB | 4.0 GB | 478×277×161 three-phase CT |
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ uv venv --python 3.13
33
+ source .venv/bin/activate
34
+ uv pip install "segresnet-mlx>=0.3.6"
35
+ ```
36
+
37
+ ## Run
38
+
39
+ ```python
40
+ from segresnet_mlx.medmlx import brats
41
+
42
+ result = brats(
43
+ t1c_path="t1c.nii.gz", t1_path="t1.nii.gz", t2_path="t2.nii.gz",
44
+ flair_path="flair.nii.gz", output_dir="out",
45
+ )
46
+ print(result["outputs"]["mask"])
47
+ ```
48
+
49
+ ### Models and weights
50
+
51
+ Each runner selects its bundle internally. Keep each model's input volumes on one voxel
52
+ grid.
53
+
54
+ | Model | Runner | Inputs | Weights | Local file |
55
+ | :--- | :--- | :--- | :--- | :--- |
56
+ | `segresnet-brats` | `brats` | `t1c_path`, `t1_path`, `t2_path`, `flair_path` | `MedMLX/segresnet-brats-mlx` | `segresnet-brats.safetensors` |
57
+ | `segresnet-renal-cect` | `renal_cect` | `arterial_path`, `venous_path`, `excretory_path` | [`MedMLX/segresnet-renal-cect-mlx`](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx) | `segresnet-renal-cect.safetensors` |
58
+
59
+ Weights download on first use; `medmlx setup segresnet-brats` downloads ahead of time.
60
+ For local weights, pass a folder containing the model's local file as `weights_path`.
61
+ The standalone `run(bundle=..., weights_path=...)` interface remains available for
62
+ explicit local checkpoints, including the whole-body CT variants, whose native weights
63
+ are published as [`MedMLX/segresnet-wholebody-mlx`](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
64
+
65
+ ### Inputs and outputs
66
+
67
+ | Argument | Meaning |
68
+ | --- | --- |
69
+ | `t1c_path`, `t1_path`, `t2_path`, `flair_path` | `brats`: contrast T1, T1, T2 and FLAIR MRI in NIfTI |
70
+ | `arterial_path`, `venous_path`, `excretory_path` | `renal_cect`: arterial, venous and excretory CT in NIfTI |
71
+ | `output_dir` | Directory for `<bundle>_mask.nii.gz`; created if missing |
72
+ | `weights_path` | Optional `.safetensors` file or a folder containing it |
73
+ | `overwrite` | `False` by default; an existing mask is replaced only when `True` |
74
+ | `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` (renal only) |
75
+
76
+ Inputs are finite 3D volumes on one voxel grid, with spatial units in millimetres or
77
+ unspecified. The mask is written on the input grid as the NIfTI reader corrects it.
78
+
79
+ | Model | Mask dtype | Labels |
80
+ | :--- | :--- | :--- |
81
+ | `segresnet-brats` | uint8 | 1 necrotic/non-enhancing tumor core, 2 peritumoral edema, 4 enhancing tumor |
82
+ | `segresnet-renal-cect` | float32 | 1 artery, 2 vein, 3 ureter, 4 neoplasm, 5 parenchyma |
83
+
84
+ | `arithmetic_profile` | Arithmetic |
85
+ | :--- | :--- |
86
+ | `torch-order-fp32` (default) | The default float32 profile |
87
+ | `compensated-fp32` | Convolution and GroupNorm accumulate in paired Metal floats, with float32 layer outputs |
88
+ | `compensated-fp48` | The pairs carry through the hidden layers and stitching runs in float64 on the host; needs the renal transposed-convolution decoder (renal only) |
89
+
90
+ `run` returns `{"outputs": {"mask": path}, "details": {...}}`, with run metadata in `details`.
91
+ Invalid inputs raise `InvalidInputError`; missing or mismatched weights raise
92
+ `AssetNotReadyError`; inference failures raise `ModelExecutionError`.
93
+
94
+ ### Whole-body CT and streaming
95
+
96
+ `run` takes `bundle` and a `.safetensors` file as `weights_path`:
97
+
98
+ | `bundle` | Weights file | Input |
99
+ | :--- | :--- | :--- |
100
+ | `brats_mri_segmentation` | `segresnet-brats.safetensors` | Four MRI sequences |
101
+ | `renalStructures_CECT_segmentation` | `segresnet-renal-cect.safetensors` | Three CT phases |
102
+ | `wholeBody_ct_segmentation` (1.5 mm) | `segresnet-wholebody-high.safetensors` | One CT as `image_path` |
103
+ | `wholeBody_ct_segmentation_lowres` (3 mm) | `segresnet-wholebody-low.safetensors` | One CT as `image_path` |
104
+
105
+ The whole-body bundles write float32 labels 0–104 from the bundle's `channel_def`:
106
+
107
+ | Labels | Structures |
108
+ | :--- | :--- |
109
+ | 1–10 | spleen, kidney_right, kidney_left, gallbladder, liver, stomach, aorta, inferior_vena_cava, portal_vein_and_splenic_vein, pancreas |
110
+ | 11–12 | adrenal glands (right, left) |
111
+ | 13–17 | lung lobes (upper and lower left, upper, middle and lower right) |
112
+ | 18–41 | vertebrae L5–C1 |
113
+ | 42–43 | esophagus, trachea |
114
+ | 44–49 | heart chambers and pulmonary artery |
115
+ | 50 | brain |
116
+ | 51–54 | iliac arteries and veins |
117
+ | 55 | small bowel |
118
+ | 56 | duodenum |
119
+ | 57 | colon |
120
+ | 58–69 | left ribs 1–12 |
121
+ | 70–81 | right ribs 1–12 |
122
+ | 82–83 | humerus |
123
+ | 84–85 | scapula |
124
+ | 86–87 | clavicula |
125
+ | 88–89 | femur |
126
+ | 90–91 | hip |
127
+ | 92–93 | sacrum, face |
128
+ | 94–99 | gluteus maximus, medius and minimus |
129
+ | 100–101 | autochthon |
130
+ | 102–103 | iliopsoas |
131
+ | 104 | urinary bladder |
132
+
133
+ `run(..., streaming=True, scratch_dir="scratch")` keeps blending intermediates and
134
+ logits in temporary mapped files instead of a full in-memory class volume. The files
135
+ are removed on success and failure; `scratch_dir` defaults to the system temporary
136
+ directory. The final label volume stays in memory.
137
+
138
+ ### Python API
139
+
140
+ ```python
141
+ from pathlib import Path
142
+
143
+ import numpy as np
144
+ from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_model, predict_logits
145
+
146
+ spec = SegResNetSpec(3, 6, 32, upsample_mode="deconv") # renal CECT network
147
+ network = load_model(Path("segresnet-renal-cect.safetensors"), spec=spec)
148
+ patch = np.zeros((1, 3, 32, 32, 32), dtype=np.float32)
149
+ logits = forward_patch(network, patch) # float32 NCDHW -> float32 NumPy logits
150
+ config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
151
+ volume_logits = predict_logits(patch, config, network=network) # stitched sliding windows
152
+ ```
153
+
154
+ - `forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
155
+ - `predict_logits` takes preprocessed arrays of any size and stitches the bundle's
156
+ sliding windows. Neither normalizes intensities, applies activations or maps labels.
157
+ - `load_model` checks tensor names, shapes and finite float32 values against
158
+ `required_shapes(spec)`.
159
+ - `WindowTelemetry` and `BundlePredictor` record bounded progress and timing.
160
+ - Inference requires Apple Silicon with Metal.
161
+
162
+ ## Use with MedMLX
163
+
164
+ Use the [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) to run `segresnet-brats` and `segresnet-renal-cect` from an MCP client. Weights download on first use.
165
+
166
+ ```sh
167
+ uv tool install --python 3.13 "medmlx[segment,mcp]"
168
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
169
+ mkdir -p "$HOME/medmlx-work"
170
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
171
+ ```
172
+
173
+ 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`.
174
+
175
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
176
+
177
+ ## License
178
+
179
+ [Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.6/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.6/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "segresnet-mlx"
7
- version = "0.3.3"
7
+ version = "0.3.6"
8
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
10
  requires-python = ">=3.13,<3.14"
@@ -39,7 +39,7 @@ authors = [
39
39
  { name = "Alfredo Sandoval Jr." },
40
40
  ]
41
41
  dependencies = [
42
- "medmlx-core==0.2.6",
42
+ "medmlx-core>=0.2.6,<0.3",
43
43
  "mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'",
44
44
  "nibabel>=5.3,<6",
45
45
  "numpy>=2.0,<3",
@@ -51,7 +51,7 @@ segresnet-renal-cect = "segresnet_mlx.medmlx:RENAL_CECT_MODEL"
51
51
 
52
52
  [project.urls]
53
53
  Homepage = "https://medmlx.org"
54
- Documentation = "https://github.com/MedMLX/segresnet-mlx/blob/v0.3.3/README.md"
54
+ Documentation = "https://github.com/MedMLX/segresnet-mlx/blob/v0.3.6/README.md"
55
55
  Repository = "https://github.com/MedMLX/segresnet-mlx"
56
56
  Issues = "https://github.com/MedMLX/segresnet-mlx/issues"
57
57
  Weights = "https://huggingface.co/models?author=MedMLX&search=segresnet"
@@ -68,9 +68,6 @@ dev = [
68
68
  "torch>=2.6,<3",
69
69
  ]
70
70
 
71
- [tool.hatch.metadata]
72
- allow-direct-references = true
73
-
74
71
  [tool.hatch.build.targets.wheel]
75
72
  packages = ["src/segresnet_mlx"]
76
73
 
@@ -93,8 +90,8 @@ extend-select = ["TID251", "TID252", "ANN401"]
93
90
  select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
94
91
 
95
92
  [tool.pyright]
96
- include = ["scripts","src","tests"]
97
- extraPaths = ["src", "scripts", "tests"]
93
+ include = ["src", "tests"]
94
+ extraPaths = ["src", "tests"]
98
95
  pythonVersion = "3.13"
99
96
  typeCheckingMode = "strict"
100
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.3"
22
+ __version__ = "0.3.6"
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, HostArray
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
- ...
@@ -190,8 +190,8 @@ BUNDLES: dict[str, Bundle] = {
190
190
  roles=("t1c_path", "t1_path", "t2_path", "flair_path"),
191
191
  labels={
192
192
  0: "background",
193
- 1: "tumor core, not enhancing",
194
- 2: "whole tumor outside the core",
193
+ 1: "necrotic/non-enhancing tumor core",
194
+ 2: "peritumoral edema",
195
195
  4: "enhancing tumor",
196
196
  },
197
197
  output_dtype="uint8",
@@ -225,6 +225,8 @@ BRATS_MODEL = {
225
225
  "label": "SegResNet BraTS MRI",
226
226
  "task": "segmentation",
227
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,
228
230
  "summary": "BraTS brain tumor segmentation from co-registered MRI sequences.",
229
231
  "labels": {
230
232
  str(value): name
@@ -236,6 +238,8 @@ RENAL_CECT_MODEL = {
236
238
  "label": "SegResNet renal CECT",
237
239
  "task": "segmentation",
238
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,
239
243
  "summary": "Renal structures from arterial, venous and excretory phase CT.",
240
244
  "labels": {
241
245
  str(value): name
@@ -385,8 +389,13 @@ def run(
385
389
  "image_path": image_path,
386
390
  }
387
391
  config, mask_path = _check_arguments(
388
- bundle, values, output_dir, overwrite=overwrite,
389
- arithmetic_profile=arithmetic_profile, streaming=streaming,
392
+ bundle,
393
+ values,
394
+ output_dir,
395
+ overwrite=overwrite,
396
+ arithmetic_profile=arithmetic_profile,
397
+ streaming=streaming,
398
+ scratch_dir=scratch_dir,
390
399
  )
391
400
  output_root = mask_path.parent
392
401
  weights = _weights_file(weights_path)
@@ -404,7 +413,7 @@ def run(
404
413
  if streaming:
405
414
  from medmlx_core.volume_workspace import VolumeWorkspace
406
415
 
407
- context = VolumeWorkspace(scratch_dir)
416
+ context = VolumeWorkspace(Path(scratch_dir).expanduser() if scratch_dir else None)
408
417
  else:
409
418
  context = nullcontext(None)
410
419
  with context as workspace:
@@ -471,6 +480,8 @@ def brats(
471
480
  weights_path: str | None = None,
472
481
  overwrite: bool = False,
473
482
  arithmetic_profile: ArithmeticProfile = "torch-order-fp32",
483
+ streaming: bool = False,
484
+ scratch_dir: str | None = None,
474
485
  ) -> RunResult:
475
486
  """Segment BraTS MRI; omit weights_path to download its cached model folder.
476
487
 
@@ -490,21 +501,34 @@ def brats(
490
501
  overwrite: Replace an existing output mask when true.
491
502
  arithmetic_profile: ``torch-order-fp32`` (default) or ``compensated-fp32``;
492
503
  ``compensated-fp48`` requires the renal bundle.
504
+ streaming: Use bounded blending and mapped logits, as in ``run``.
505
+ scratch_dir: Existing parent directory for temporary streaming maps.
493
506
  """
494
507
  _check_arguments(
495
508
  "brats_mri_segmentation",
496
509
  {"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,
510
+ output_dir,
511
+ overwrite=overwrite,
512
+ arithmetic_profile=arithmetic_profile,
513
+ streaming=streaming,
514
+ scratch_dir=scratch_dir,
498
515
  )
499
516
  folder = (
500
- weights_dir("segresnet-brats")
501
- if weights_path is None else Path(weights_path).expanduser()
517
+ weights_dir("segresnet-brats") if weights_path is None else Path(weights_path).expanduser()
502
518
  )
503
519
  checkpoint = folder / "segresnet-brats.safetensors" if folder.is_dir() else folder
504
520
  return run(
505
- bundle="brats_mri_segmentation", weights_path=str(checkpoint), output_dir=output_dir,
506
- t1c_path=t1c_path, t1_path=t1_path, t2_path=t2_path, flair_path=flair_path,
507
- overwrite=overwrite, arithmetic_profile=arithmetic_profile,
521
+ bundle="brats_mri_segmentation",
522
+ weights_path=str(checkpoint),
523
+ output_dir=output_dir,
524
+ t1c_path=t1c_path,
525
+ t1_path=t1_path,
526
+ t2_path=t2_path,
527
+ flair_path=flair_path,
528
+ overwrite=overwrite,
529
+ arithmetic_profile=arithmetic_profile,
530
+ streaming=streaming,
531
+ scratch_dir=scratch_dir,
508
532
  )
509
533
 
510
534
 
@@ -517,6 +541,8 @@ def renal_cect(
517
541
  weights_path: str | None = None,
518
542
  overwrite: bool = False,
519
543
  arithmetic_profile: ArithmeticProfile = "torch-order-fp32",
544
+ streaming: bool = False,
545
+ scratch_dir: str | None = None,
520
546
  ) -> RunResult:
521
547
  """Segment renal CECT; omit weights_path to download its cached model folder.
522
548
 
@@ -536,22 +562,39 @@ def renal_cect(
536
562
  overwrite: Replace an existing output mask when true.
537
563
  arithmetic_profile: ``torch-order-fp32`` (default), ``compensated-fp32``
538
564
  or ``compensated-fp48``; see ``run`` for their arithmetic contracts.
565
+ streaming: Use bounded blending and mapped logits, as in ``run``.
566
+ scratch_dir: Existing parent directory for temporary streaming maps.
539
567
  """
540
568
  _check_arguments(
541
569
  "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,
570
+ {
571
+ "arterial_path": arterial_path,
572
+ "venous_path": venous_path,
573
+ "excretory_path": excretory_path,
574
+ },
575
+ output_dir,
576
+ overwrite=overwrite,
577
+ arithmetic_profile=arithmetic_profile,
578
+ streaming=streaming,
579
+ scratch_dir=scratch_dir,
545
580
  )
546
581
  folder = (
547
582
  weights_dir("segresnet-renal-cect")
548
- if weights_path is None else Path(weights_path).expanduser()
583
+ if weights_path is None
584
+ else Path(weights_path).expanduser()
549
585
  )
550
586
  checkpoint = folder / "segresnet-renal-cect.safetensors" if folder.is_dir() else folder
551
587
  return run(
552
- bundle="renalStructures_CECT_segmentation", weights_path=str(checkpoint),
553
- output_dir=output_dir, arterial_path=arterial_path, venous_path=venous_path,
554
- excretory_path=excretory_path, overwrite=overwrite, arithmetic_profile=arithmetic_profile,
588
+ bundle="renalStructures_CECT_segmentation",
589
+ weights_path=str(checkpoint),
590
+ output_dir=output_dir,
591
+ arterial_path=arterial_path,
592
+ venous_path=venous_path,
593
+ excretory_path=excretory_path,
594
+ overwrite=overwrite,
595
+ arithmetic_profile=arithmetic_profile,
596
+ streaming=streaming,
597
+ scratch_dir=scratch_dir,
555
598
  )
556
599
 
557
600
 
@@ -563,6 +606,7 @@ def _check_arguments(
563
606
  overwrite: bool,
564
607
  arithmetic_profile: ArithmeticProfile,
565
608
  streaming: bool = False,
609
+ scratch_dir: str | None = None,
566
610
  ) -> tuple[Bundle, Path]:
567
611
  """Check every ``run`` argument before weights, inputs or MLX are loaded.
568
612
 
@@ -594,6 +638,8 @@ def _check_arguments(
594
638
  for name, flag in (("overwrite", overwrite), ("streaming", streaming)):
595
639
  if not isinstance(cast(object, flag), bool):
596
640
  raise InvalidInputError(f"{name} must be true or false")
641
+ if streaming and scratch_dir is not None and not Path(scratch_dir).expanduser().is_dir():
642
+ raise InvalidInputError("scratch_dir must name an existing directory")
597
643
  output_root = Path(output_dir).expanduser().resolve()
598
644
  if output_root.exists() and not output_root.is_dir():
599
645
  raise InvalidInputError(f"output_dir is not a directory: {output_root}")
@@ -710,8 +756,7 @@ def postprocess_wholebody(logits: Float32Array, inverse: SpatialInverse) -> Floa
710
756
  """
711
757
  # Kept to mirror the bundle's Activationsd(softmax=True) step; in exact
712
758
  # arithmetic it does not change the argmax.
713
- probabilities = transforms.softmax_channel(logits)
714
- labels = transforms.argmax_channel(probabilities)
759
+ labels = transforms.softmax_argmax_channel(logits)
715
760
  values, affine = transforms.invert_spacing(
716
761
  labels, inverse.affine, inverse.resampling, "nearest"
717
762
  )
@@ -726,16 +771,9 @@ def postprocess_streaming(
726
771
  workspace: VolumeWorkspace,
727
772
  ) -> MaskArray:
728
773
  """Retain each bundle's activation/restoration/label order with bounded class storage."""
729
- from medmlx_core.volume_workspace import restored_argmax
730
-
731
774
  if bundle in _WHOLE_BODY_PIXDIM:
732
775
  assert inverse is not None
733
- probabilities = workspace.map_channels(logits, transforms.softmax_channel)
734
- labels = restored_argmax(probabilities, lambda channel: channel)[None]
735
- values, affine = transforms.invert_spacing(
736
- labels, inverse.affine, inverse.resampling, "nearest"
737
- )
738
- return transforms.invert_orientation(values, affine, inverse.orientation)[0][0]
776
+ return postprocess_wholebody(logits, inverse)
739
777
  if bundle == "renalStructures_CECT_segmentation":
740
778
  assert inverse is not None
741
779
  labels: Float32Array | None = None
@@ -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
 
@@ -35,7 +35,7 @@ class SlidingWindowConfig:
35
35
  Attributes:
36
36
  roi_size: Window size in voxels, ``(D, H, W)`` of the preprocessed volume.
37
37
  sw_batch_size: Windows sent to the network per call.
38
- overlap: Fraction of each window shared with its neighbour, in ``[0, 1)``.
38
+ overlap: Fraction of each window shared with its neighbor, in ``[0, 1)``.
39
39
  mode: Window blending, ``"constant"`` or ``"gaussian"`` (sigma scale 0.125).
40
40
  padding_mode: How a volume smaller than ``roi_size`` is padded: ``"constant"``
41
41
  (zeros), ``"reflect"``, ``"replicate"`` or ``"circular"``.
@@ -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,
@@ -289,6 +278,23 @@ def argmax_channel(data: Float32Array) -> Float32Array:
289
278
  return np.argmax(data, axis=0)[None].astype(np.float32, copy=False)
290
279
 
291
280
 
281
+ def softmax_argmax_channel(data: Float32Array) -> Float32Array:
282
+ """Select labels after the existing FP32 softmax in bounded spatial blocks.
283
+
284
+ Keep softmax's rounding and lowest-index ties. Gathering coordinates avoids
285
+ a full logits copy for noncontiguous callers; no probability volume is retained.
286
+ """
287
+ shape = data.shape[1:]
288
+ output = np.empty((1, *shape), dtype=np.float32)
289
+ labels = output.reshape(-1)
290
+ for start in range(0, labels.size, 8192):
291
+ stop = min(start + 8192, labels.size)
292
+ positions = np.unravel_index(np.arange(start, stop), shape)
293
+ block = data[(slice(None), *positions)]
294
+ labels[start:stop] = argmax_channel(softmax_channel(block))[0]
295
+ return output
296
+
297
+
292
298
  def sigmoid(data: Float32Array) -> Float32Array:
293
299
  """Float32 sigmoid with a stable negative tail and source threshold rounding."""
294
300
  one = np.float32(1.0)
@@ -347,10 +353,6 @@ def write_nifti(path: Path, data: HostArray, affine: Float64Array, dtype: npt.DT
347
353
  nib.save(image, str(path))
348
354
 
349
355
 
350
-
351
-
352
-
353
-
354
356
  def _normalize_transform(shape: Sequence[int]) -> Float64Array:
355
357
  """``monai.networks.utils.normalize_transform`` (``align_corners=False``)."""
356
358
  size = np.asarray(shape, dtype=np.float64)
@@ -362,10 +364,6 @@ def _normalize_transform(shape: Sequence[int]) -> Float64Array:
362
364
  return result
363
365
 
364
366
 
365
-
366
-
367
-
368
-
369
367
  def _theta(
370
368
  xform: Float64Array,
371
369
  in_size: Sequence[int],
@@ -73,8 +73,9 @@ def load_model(
73
73
  """Load converted float32 safetensors into a ``SegResNet`` for ``spec``.
74
74
 
75
75
  Raises:
76
- InvalidInputError: If the loaded value is not a mapping, its keys or shapes differ
77
- from ``required_shapes(spec)``, or a parameter is not finite float32.
76
+ InvalidInputError: If ``weights_path`` does not end in ``.safetensors``, the
77
+ loaded value is not a mapping, its keys or shapes differ from
78
+ ``required_shapes(spec)``, or a parameter is not finite float32.
78
79
  RuntimeError: If MLX cannot open or decode the weights file.
79
80
  """
80
81
  if Path(weights_path).suffix != ".safetensors":
@@ -101,9 +102,14 @@ def load_model(
101
102
  f"SegResNet MLX parameter {key!r} has shape {shape}; expected {expected_shape}"
102
103
  )
103
104
  for key, value in weights.items():
104
- if value.dtype != mx.float32 or not bool(mx.all(mx.isfinite(value)).item()):
105
+ if value.dtype != mx.float32:
106
+ raise InvalidInputError(f"SegResNet MLX parameter {key!r} must be finite float32")
107
+ finite = {key: mx.all(mx.isfinite(value)) for key, value in weights.items()}
108
+ # Evaluate every admitted tensor and its check together before reading scalars.
109
+ mx.eval(weights, finite)
110
+ for key, valid in finite.items():
111
+ if not bool(valid.item()):
105
112
  raise InvalidInputError(f"SegResNet MLX parameter {key!r} must be finite float32")
106
- mx.eval(weights)
107
113
  return SegResNet(spec, weights, mx=mx, arithmetic_profile=arithmetic_profile)
108
114
 
109
115
 
@@ -1,152 +0,0 @@
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
- [![PyPI](https://img.shields.io/pypi/v/segresnet-mlx)](https://pypi.org/project/segresnet-mlx/)
8
- [![Python](https://img.shields.io/pypi/pyversions/segresnet-mlx)](https://pypi.org/project/segresnet-mlx/)
9
- [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.3/LICENSE)
10
- [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
11
- [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/segresnet-brats-mlx)
12
- [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](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.
File without changes
File without changes