segresnet-mlx 0.3.4__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.4 → segresnet_mlx-0.3.6}/PKG-INFO +94 -69
  2. segresnet_mlx-0.3.6/README.md +179 -0
  3. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/pyproject.toml +2 -2
  4. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/__init__.py +1 -1
  5. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/medmlx.py +62 -28
  6. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/predictor.py +1 -1
  7. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/transforms.py +17 -0
  8. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/weights.py +10 -4
  9. segresnet_mlx-0.3.4/README.md +0 -154
  10. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/.gitignore +0 -0
  11. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/LICENSE +0 -0
  12. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/THIRD_PARTY_NOTICES.md +0 -0
  13. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_arrays.py +0 -0
  14. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_nifti.py +0 -0
  15. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_records.py +0 -0
  16. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_runtime.py +0 -0
  17. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/_types.py +0 -0
  18. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/inference.py +0 -0
  19. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/network.py +0 -0
  20. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/py.typed +0 -0
  21. {segresnet_mlx-0.3.4 → segresnet_mlx-0.3.6}/src/segresnet_mlx/telemetry.py +0 -0
  22. {segresnet_mlx-0.3.4 → 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.4
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.4/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
@@ -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.4/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.4/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,29 +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
- Weights: 19 MB download for `segresnet-brats`, 76 MB for `segresnet-renal-cect`. Peak MLX memory: 4.9 GB for a 240×240×155 four-sequence brain MRI (`segresnet-brats`) and 4.0 GB for a 478×277×161 three-phase CT (`segresnet-renal-cect`).
65
-
66
- ## Use with MedMLX
67
-
68
- The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this package. It installs this runtime, downloads its weights on first use, and lets an AI agent describe, check and run `segresnet-brats` and `segresnet-renal-cect` for you.
69
-
70
- ```sh
71
- uv tool install --python 3.13 "medmlx[segment,mcp]"
72
- MEDMLX="$(uv tool dir --bin --color never)/medmlx"
73
- mkdir -p "$HOME/medmlx-work"
74
- claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
75
- ```
76
-
77
- For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"`. Other MCP clients take the same command and arguments. The same install provides the `medmlx` CLI, for example `medmlx describe segresnet-brats`.
78
-
79
- > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
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 |
80
68
 
81
69
  ## Install
82
70
 
83
71
  ```bash
84
72
  uv venv --python 3.13
85
73
  source .venv/bin/activate
86
- uv pip install "segresnet-mlx>=0.3.4"
74
+ uv pip install "segresnet-mlx>=0.3.6"
87
75
  ```
88
76
 
89
77
  ## Run
@@ -98,23 +86,21 @@ result = brats(
98
86
  print(result["outputs"]["mask"])
99
87
  ```
100
88
 
101
- The registered models are `segresnet-brats` and `segresnet-renal-cect`; their `brats`
102
- and `renal_cect` runners select the matching bundle internally. The renal runner takes
103
- `arterial_path`, `venous_path` and `excretory_path`. Keep each model's input volumes
104
- on one voxel grid.
89
+ ### Models and weights
105
90
 
106
- Omitting `weights_path` downloads `MedMLX/segresnet-brats-mlx` or
107
- `MedMLX/segresnet-renal-cect-mlx` into the shared MedMLX cache on first use; interrupted
108
- downloads resume and later runs work offline. With MedMLX installed, `medmlx setup
109
- segresnet-brats` downloads it ahead of time. To use your own copy, pass a folder
110
- containing `segresnet-brats.safetensors` for BraTS or `segresnet-renal-cect.safetensors`
111
- for renal CECT as `weights_path`. `details.weights_revision` records the downloaded
112
- commit, or `null` for a folder without a MedMLX download record.
91
+ Each runner selects its bundle internally. Keep each model's input volumes on one voxel
92
+ grid.
113
93
 
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` |
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`.
114
101
  The standalone `run(bundle=..., weights_path=...)` interface remains available for
115
- explicit local checkpoints, including the whole-body CT variants. Published native
116
- weights are also available for [renal CECT](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
117
- and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
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).
118
104
 
119
105
  ### Inputs and outputs
120
106
 
@@ -128,35 +114,61 @@ and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
128
114
  | `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` (renal only) |
129
115
 
130
116
  Inputs are finite 3D volumes on one voxel grid, with spatial units in millimetres or
131
- unspecified. The mask is written on the input grid as the NIfTI reader corrects it. Renal labels are float32: 1 artery, 2 vein, 3 ureter,
132
- 4 neoplasm and 5 parenchyma. BraTS labels are uint8: 1 tumor core, 2 whole tumor
133
- outside the core and 4 enhancing tumor.
117
+ unspecified. The mask is written on the input grid as the NIfTI reader corrects it.
118
+
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 |
134
123
 
135
- `compensated-fp32` accumulates convolution and GroupNorm in paired Metal floats with
136
- float32 layer outputs. `compensated-fp48` carries the pairs through the hidden layers
137
- and stitches in float64 on the host; it needs the renal transposed-convolution decoder.
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) |
138
129
 
139
- `run` returns `{"outputs": {"mask": path}, "details": {...}}`, with labels, shapes,
140
- window settings, MLX device, peak memory and elapsed time. Invalid inputs raise
141
- `InvalidInputError`; missing or mismatched weights raise `AssetNotReadyError`;
142
- inference failures raise `ModelExecutionError`.
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`.
143
133
 
144
134
  ### Whole-body CT and streaming
145
135
 
146
- `run` takes `bundle` and a `.safetensors` file as `weights_path`: `brats_mri_segmentation`,
147
- `renalStructures_CECT_segmentation`, `wholeBody_ct_segmentation` (1.5 mm) or
148
- `wholeBody_ct_segmentation_lowres` (3 mm). The whole-body bundles take one CT as
149
- `image_path` and use `segresnet-wholebody-high.safetensors` or
150
- `segresnet-wholebody-low.safetensors`. They write float32 labels 0–104 from the
151
- bundle's `channel_def`: 1 spleen, 2 kidney_right, 3 kidney_left, 4 gallbladder,
152
- 5 liver, 6 stomach, 7 aorta, 8 inferior_vena_cava, 9 portal_vein_and_splenic_vein,
153
- 10 pancreas, 11–12 adrenal glands (right, left), 13–17 lung lobes (upper and lower
154
- left, upper, middle and lower right), 18–41 vertebrae L5–C1, 42 esophagus, 43 trachea,
155
- 44–49 heart chambers and pulmonary artery, 50 brain, 51–54 iliac arteries and veins,
156
- 55 small bowel, 56 duodenum, 57 colon, 58–69 left ribs 1–12, 70–81 right ribs 1–12,
157
- 82–83 humerus, 84–85 scapula, 86–87 clavicula, 88–89 femur, 90–91 hip, 92 sacrum,
158
- 93 face, 94–99 gluteus maximus, medius and minimus, 100–101 autochthon, 102–103
159
- iliopsoas and 104 urinary bladder.
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 |
160
172
 
161
173
  `run(..., streaming=True, scratch_dir="scratch")` keeps blending intermediates and
162
174
  logits in temporary mapped files instead of a full in-memory class volume. The files
@@ -179,16 +191,29 @@ config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
179
191
  volume_logits = predict_logits(patch, config, network=network) # stitched sliding windows
180
192
  ```
181
193
 
182
- `forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
183
- `predict_logits` takes preprocessed arrays of any size and stitches the bundle's
184
- sliding windows; neither normalizes intensities, applies activations or maps labels.
185
- `load_model` checks tensor names, shapes and finite float32 values against
186
- `required_shapes(spec)`, not checkpoint identity. `WindowTelemetry` and
187
- `BundlePredictor` record bounded progress and timing. Inference needs Apple Silicon
188
- with Metal and has no CPU fallback.
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.
189
201
 
190
- ## 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.
205
+
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
+ ```
191
212
 
192
- [Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
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
193
218
 
194
- 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.4"
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"
@@ -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.4/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"
@@ -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.4"
22
+ __version__ = "0.3.6"
23
23
 
24
24
  _EXPORTS = {
25
25
  "BUNDLE_CONFIGS": "segresnet_mlx.predictor",
@@ -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",
@@ -389,8 +389,13 @@ def run(
389
389
  "image_path": image_path,
390
390
  }
391
391
  config, mask_path = _check_arguments(
392
- bundle, values, output_dir, overwrite=overwrite,
393
- 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,
394
399
  )
395
400
  output_root = mask_path.parent
396
401
  weights = _weights_file(weights_path)
@@ -408,7 +413,7 @@ def run(
408
413
  if streaming:
409
414
  from medmlx_core.volume_workspace import VolumeWorkspace
410
415
 
411
- context = VolumeWorkspace(scratch_dir)
416
+ context = VolumeWorkspace(Path(scratch_dir).expanduser() if scratch_dir else None)
412
417
  else:
413
418
  context = nullcontext(None)
414
419
  with context as workspace:
@@ -475,6 +480,8 @@ def brats(
475
480
  weights_path: str | None = None,
476
481
  overwrite: bool = False,
477
482
  arithmetic_profile: ArithmeticProfile = "torch-order-fp32",
483
+ streaming: bool = False,
484
+ scratch_dir: str | None = None,
478
485
  ) -> RunResult:
479
486
  """Segment BraTS MRI; omit weights_path to download its cached model folder.
480
487
 
@@ -494,21 +501,34 @@ def brats(
494
501
  overwrite: Replace an existing output mask when true.
495
502
  arithmetic_profile: ``torch-order-fp32`` (default) or ``compensated-fp32``;
496
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.
497
506
  """
498
507
  _check_arguments(
499
508
  "brats_mri_segmentation",
500
509
  {"t1c_path": t1c_path, "t1_path": t1_path, "t2_path": t2_path, "flair_path": flair_path},
501
- output_dir, overwrite=overwrite, arithmetic_profile=arithmetic_profile,
510
+ output_dir,
511
+ overwrite=overwrite,
512
+ arithmetic_profile=arithmetic_profile,
513
+ streaming=streaming,
514
+ scratch_dir=scratch_dir,
502
515
  )
503
516
  folder = (
504
- weights_dir("segresnet-brats")
505
- 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()
506
518
  )
507
519
  checkpoint = folder / "segresnet-brats.safetensors" if folder.is_dir() else folder
508
520
  return run(
509
- bundle="brats_mri_segmentation", weights_path=str(checkpoint), output_dir=output_dir,
510
- t1c_path=t1c_path, t1_path=t1_path, t2_path=t2_path, flair_path=flair_path,
511
- 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,
512
532
  )
513
533
 
514
534
 
@@ -521,6 +541,8 @@ def renal_cect(
521
541
  weights_path: str | None = None,
522
542
  overwrite: bool = False,
523
543
  arithmetic_profile: ArithmeticProfile = "torch-order-fp32",
544
+ streaming: bool = False,
545
+ scratch_dir: str | None = None,
524
546
  ) -> RunResult:
525
547
  """Segment renal CECT; omit weights_path to download its cached model folder.
526
548
 
@@ -540,22 +562,39 @@ def renal_cect(
540
562
  overwrite: Replace an existing output mask when true.
541
563
  arithmetic_profile: ``torch-order-fp32`` (default), ``compensated-fp32``
542
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.
543
567
  """
544
568
  _check_arguments(
545
569
  "renalStructures_CECT_segmentation",
546
- {"arterial_path": arterial_path, "venous_path": venous_path,
547
- "excretory_path": excretory_path},
548
- output_dir, overwrite=overwrite, arithmetic_profile=arithmetic_profile,
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,
549
580
  )
550
581
  folder = (
551
582
  weights_dir("segresnet-renal-cect")
552
- if weights_path is None else Path(weights_path).expanduser()
583
+ if weights_path is None
584
+ else Path(weights_path).expanduser()
553
585
  )
554
586
  checkpoint = folder / "segresnet-renal-cect.safetensors" if folder.is_dir() else folder
555
587
  return run(
556
- bundle="renalStructures_CECT_segmentation", weights_path=str(checkpoint),
557
- output_dir=output_dir, arterial_path=arterial_path, venous_path=venous_path,
558
- 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,
559
598
  )
560
599
 
561
600
 
@@ -567,6 +606,7 @@ def _check_arguments(
567
606
  overwrite: bool,
568
607
  arithmetic_profile: ArithmeticProfile,
569
608
  streaming: bool = False,
609
+ scratch_dir: str | None = None,
570
610
  ) -> tuple[Bundle, Path]:
571
611
  """Check every ``run`` argument before weights, inputs or MLX are loaded.
572
612
 
@@ -598,6 +638,8 @@ def _check_arguments(
598
638
  for name, flag in (("overwrite", overwrite), ("streaming", streaming)):
599
639
  if not isinstance(cast(object, flag), bool):
600
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")
601
643
  output_root = Path(output_dir).expanduser().resolve()
602
644
  if output_root.exists() and not output_root.is_dir():
603
645
  raise InvalidInputError(f"output_dir is not a directory: {output_root}")
@@ -714,8 +756,7 @@ def postprocess_wholebody(logits: Float32Array, inverse: SpatialInverse) -> Floa
714
756
  """
715
757
  # Kept to mirror the bundle's Activationsd(softmax=True) step; in exact
716
758
  # arithmetic it does not change the argmax.
717
- probabilities = transforms.softmax_channel(logits)
718
- labels = transforms.argmax_channel(probabilities)
759
+ labels = transforms.softmax_argmax_channel(logits)
719
760
  values, affine = transforms.invert_spacing(
720
761
  labels, inverse.affine, inverse.resampling, "nearest"
721
762
  )
@@ -730,16 +771,9 @@ def postprocess_streaming(
730
771
  workspace: VolumeWorkspace,
731
772
  ) -> MaskArray:
732
773
  """Retain each bundle's activation/restoration/label order with bounded class storage."""
733
- from medmlx_core.volume_workspace import restored_argmax
734
-
735
774
  if bundle in _WHOLE_BODY_PIXDIM:
736
775
  assert inverse is not None
737
- probabilities = workspace.map_channels(logits, transforms.softmax_channel)
738
- labels = restored_argmax(probabilities, lambda channel: channel)[None]
739
- values, affine = transforms.invert_spacing(
740
- labels, inverse.affine, inverse.resampling, "nearest"
741
- )
742
- return transforms.invert_orientation(values, affine, inverse.orientation)[0][0]
776
+ return postprocess_wholebody(logits, inverse)
743
777
  if bundle == "renalStructures_CECT_segmentation":
744
778
  assert inverse is not None
745
779
  labels: Float32Array | None = None
@@ -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"``.
@@ -278,6 +278,23 @@ def argmax_channel(data: Float32Array) -> Float32Array:
278
278
  return np.argmax(data, axis=0)[None].astype(np.float32, copy=False)
279
279
 
280
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
+
281
298
  def sigmoid(data: Float32Array) -> Float32Array:
282
299
  """Float32 sigmoid with a stable negative tail and source threshold rounding."""
283
300
  one = np.float32(1.0)
@@ -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,154 +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.4/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.4/docs/example.png" alt="Brain tumor segmentation in axial, coronal and sagittal MRI" width="100%">
17
-
18
- </div>
19
-
20
- | Input | Output |
21
- | :--- | :--- |
22
- | MRI sequences or CT volumes | Segmentation on the input grid |
23
-
24
- Weights: 19 MB download for `segresnet-brats`, 76 MB for `segresnet-renal-cect`. Peak MLX memory: 4.9 GB for a 240×240×155 four-sequence brain MRI (`segresnet-brats`) and 4.0 GB for a 478×277×161 three-phase CT (`segresnet-renal-cect`).
25
-
26
- ## Use with MedMLX
27
-
28
- The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this package. It installs this runtime, downloads its weights on first use, and lets an AI agent describe, check and run `segresnet-brats` and `segresnet-renal-cect` for you.
29
-
30
- ```sh
31
- uv tool install --python 3.13 "medmlx[segment,mcp]"
32
- MEDMLX="$(uv tool dir --bin --color never)/medmlx"
33
- mkdir -p "$HOME/medmlx-work"
34
- claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
35
- ```
36
-
37
- For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"`. Other MCP clients take the same command and arguments. The same install provides the `medmlx` CLI, for example `medmlx describe segresnet-brats`.
38
-
39
- > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
40
-
41
- ## Install
42
-
43
- ```bash
44
- uv venv --python 3.13
45
- source .venv/bin/activate
46
- uv pip install "segresnet-mlx>=0.3.4"
47
- ```
48
-
49
- ## Run
50
-
51
- ```python
52
- from segresnet_mlx.medmlx import brats
53
-
54
- result = brats(
55
- t1c_path="t1c.nii.gz", t1_path="t1.nii.gz", t2_path="t2.nii.gz",
56
- flair_path="flair.nii.gz", output_dir="out",
57
- )
58
- print(result["outputs"]["mask"])
59
- ```
60
-
61
- The registered models are `segresnet-brats` and `segresnet-renal-cect`; their `brats`
62
- and `renal_cect` runners select the matching bundle internally. The renal runner takes
63
- `arterial_path`, `venous_path` and `excretory_path`. Keep each model's input volumes
64
- on one voxel grid.
65
-
66
- Omitting `weights_path` downloads `MedMLX/segresnet-brats-mlx` or
67
- `MedMLX/segresnet-renal-cect-mlx` into the shared MedMLX cache on first use; interrupted
68
- downloads resume and later runs work offline. With MedMLX installed, `medmlx setup
69
- segresnet-brats` downloads it ahead of time. To use your own copy, pass a folder
70
- containing `segresnet-brats.safetensors` for BraTS or `segresnet-renal-cect.safetensors`
71
- for renal CECT as `weights_path`. `details.weights_revision` records the downloaded
72
- commit, or `null` for a folder without a MedMLX download record.
73
-
74
- The standalone `run(bundle=..., weights_path=...)` interface remains available for
75
- explicit local checkpoints, including the whole-body CT variants. Published native
76
- weights are also available for [renal CECT](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
77
- and [whole-body CT](https://huggingface.co/MedMLX/segresnet-wholebody-mlx).
78
-
79
- ### Inputs and outputs
80
-
81
- | Argument | Meaning |
82
- | --- | --- |
83
- | `t1c_path`, `t1_path`, `t2_path`, `flair_path` | `brats`: contrast T1, T1, T2 and FLAIR MRI in NIfTI |
84
- | `arterial_path`, `venous_path`, `excretory_path` | `renal_cect`: arterial, venous and excretory CT in NIfTI |
85
- | `output_dir` | Directory for `<bundle>_mask.nii.gz`; created if missing |
86
- | `weights_path` | Optional `.safetensors` file or a folder containing it |
87
- | `overwrite` | `False` by default; an existing mask is replaced only when `True` |
88
- | `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` (renal only) |
89
-
90
- Inputs are finite 3D volumes on one voxel grid, with spatial units in millimetres or
91
- unspecified. The mask is written on the input grid as the NIfTI reader corrects it. Renal labels are float32: 1 artery, 2 vein, 3 ureter,
92
- 4 neoplasm and 5 parenchyma. BraTS labels are uint8: 1 tumor core, 2 whole tumor
93
- outside the core and 4 enhancing tumor.
94
-
95
- `compensated-fp32` accumulates convolution and GroupNorm in paired Metal floats with
96
- float32 layer outputs. `compensated-fp48` carries the pairs through the hidden layers
97
- and stitches in float64 on the host; it needs the renal transposed-convolution decoder.
98
-
99
- `run` returns `{"outputs": {"mask": path}, "details": {...}}`, with labels, shapes,
100
- window settings, MLX device, peak memory and elapsed time. Invalid inputs raise
101
- `InvalidInputError`; missing or mismatched weights raise `AssetNotReadyError`;
102
- inference failures raise `ModelExecutionError`.
103
-
104
- ### Whole-body CT and streaming
105
-
106
- `run` takes `bundle` and a `.safetensors` file as `weights_path`: `brats_mri_segmentation`,
107
- `renalStructures_CECT_segmentation`, `wholeBody_ct_segmentation` (1.5 mm) or
108
- `wholeBody_ct_segmentation_lowres` (3 mm). The whole-body bundles take one CT as
109
- `image_path` and use `segresnet-wholebody-high.safetensors` or
110
- `segresnet-wholebody-low.safetensors`. They write float32 labels 0–104 from the
111
- bundle's `channel_def`: 1 spleen, 2 kidney_right, 3 kidney_left, 4 gallbladder,
112
- 5 liver, 6 stomach, 7 aorta, 8 inferior_vena_cava, 9 portal_vein_and_splenic_vein,
113
- 10 pancreas, 11–12 adrenal glands (right, left), 13–17 lung lobes (upper and lower
114
- left, upper, middle and lower right), 18–41 vertebrae L5–C1, 42 esophagus, 43 trachea,
115
- 44–49 heart chambers and pulmonary artery, 50 brain, 51–54 iliac arteries and veins,
116
- 55 small bowel, 56 duodenum, 57 colon, 58–69 left ribs 1–12, 70–81 right ribs 1–12,
117
- 82–83 humerus, 84–85 scapula, 86–87 clavicula, 88–89 femur, 90–91 hip, 92 sacrum,
118
- 93 face, 94–99 gluteus maximus, medius and minimus, 100–101 autochthon, 102–103
119
- iliopsoas and 104 urinary bladder.
120
-
121
- `run(..., streaming=True, scratch_dir="scratch")` keeps blending intermediates and
122
- logits in temporary mapped files instead of a full in-memory class volume. The files
123
- are removed on success and failure; `scratch_dir` defaults to the system temporary
124
- directory. The final label volume stays in memory.
125
-
126
- ### Python API
127
-
128
- ```python
129
- from pathlib import Path
130
-
131
- import numpy as np
132
- from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_model, predict_logits
133
-
134
- spec = SegResNetSpec(3, 6, 32, upsample_mode="deconv") # renal CECT network
135
- network = load_model(Path("segresnet-renal-cect.safetensors"), spec=spec)
136
- patch = np.zeros((1, 3, 32, 32, 32), dtype=np.float32)
137
- logits = forward_patch(network, patch) # float32 NCDHW -> float32 NumPy logits
138
- config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
139
- volume_logits = predict_logits(patch, config, network=network) # stitched sliding windows
140
- ```
141
-
142
- `forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
143
- `predict_logits` takes preprocessed arrays of any size and stitches the bundle's
144
- sliding windows; neither normalizes intensities, applies activations or maps labels.
145
- `load_model` checks tensor names, shapes and finite float32 values against
146
- `required_shapes(spec)`, not checkpoint identity. `WindowTelemetry` and
147
- `BundlePredictor` record bounded progress and timing. Inference needs Apple Silicon
148
- with Metal and has no CPU fallback.
149
-
150
- ## License
151
-
152
- [Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.3.4/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
153
-
154
- For research and education. Outputs require human review.
File without changes
File without changes