segresnet-mlx 0.4.0__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/PKG-INFO +33 -25
  2. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/README.md +30 -22
  3. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/pyproject.toml +3 -3
  4. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/__init__.py +7 -4
  5. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/_records.py +7 -6
  6. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/_types.py +6 -3
  7. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/medmlx.py +109 -205
  8. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/predictor.py +87 -33
  9. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/transforms.py +29 -8
  10. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/weights.py +1 -1
  11. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/.gitignore +0 -0
  12. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/LICENSE +0 -0
  13. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/THIRD_PARTY_NOTICES.md +0 -0
  14. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/_arrays.py +0 -0
  15. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/_nifti.py +0 -0
  16. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/_runtime.py +0 -0
  17. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/inference.py +0 -0
  18. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/network.py +0 -0
  19. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/py.typed +0 -0
  20. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/src/segresnet_mlx/telemetry.py +0 -0
  21. {segresnet_mlx-0.4.0 → segresnet_mlx-0.5.0}/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.4.0
3
+ Version: 0.5.0
4
4
  Summary: Segment renal arteries, veins, ureters, tumors and parenchyma in multiphase CT with MONAI SegResNet in native MLX
5
5
  Project-URL: Homepage, https://medmlx.org
6
- Project-URL: Documentation, https://github.com/MedMLX/segresnet-mlx/blob/v0.4.0/README.md
6
+ Project-URL: Documentation, https://github.com/MedMLX/segresnet-mlx/blob/v0.5.0/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.3,>=0.2.6
27
+ Requires-Dist: medmlx-core<0.4,>=0.3.1
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,13 +46,17 @@ Segment renal arteries, veins, ureters, tumors and parenchyma in multiphase CT w
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.4.0/LICENSE)
49
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/segresnet-mlx/blob/v0.5.0/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-renal-cect-mlx)
52
52
  [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
53
53
 
54
54
  [Weights](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx) · [Upstream bundle](https://github.com/Project-MONAI/model-zoo/tree/dev/models/renalStructures_CECT_segmentation) · [MedMLX](https://github.com/MedMLX/medmlx)
55
55
 
56
+ <img src="https://raw.githubusercontent.com/MedMLX/segresnet-mlx/main/docs/example.png" alt="Venous-phase CT of a left kidney with a renal tumor, the predicted renal labels on that slice, and a 3D view of the predicted kidney, tumor, vessels and collecting system" width="100%">
57
+
58
+ <sub>Three-phase CT from <a href="https://doi.org/10.7937/k9/tcia.2018.oblamn27">CPTAC-CCRCC</a> case C3N-00380 (The Cancer Imaging Archive, CC BY 4.0), segmented on a crop around each kidney. The 3D view smooths surfaces and hides fragments under 0.5 mL and labels more than 20 mm from the kidney.</sub>
59
+
56
60
  </div>
57
61
 
58
62
  | Input | Output |
@@ -68,18 +72,20 @@ Segment renal arteries, veins, ureters, tumors and parenchyma in multiphase CT w
68
72
  ```bash
69
73
  uv venv --python 3.13
70
74
  source .venv/bin/activate
71
- uv pip install "segresnet-mlx>=0.4.0"
75
+ uv pip install "segresnet-mlx>=0.5.0"
72
76
  ```
73
77
 
74
78
  ## Run
75
79
 
76
80
  ```python
77
- from segresnet_mlx.medmlx import renal_cect
78
-
79
- result = renal_cect(
80
- arterial_path="arterial.nii.gz",
81
- venous_path="venous.nii.gz",
82
- excretory_path="excretory.nii.gz",
81
+ from segresnet_mlx import run
82
+
83
+ result = run(
84
+ image_paths={
85
+ "arterial": "arterial.nii.gz",
86
+ "venous": "venous.nii.gz",
87
+ "excretory": "excretory.nii.gz",
88
+ },
83
89
  output_dir="out",
84
90
  )
85
91
  print(result["outputs"]["mask"])
@@ -87,40 +93,42 @@ print(result["outputs"]["mask"])
87
93
 
88
94
  Weights download from [`MedMLX/segresnet-renal-cect-mlx`](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
89
95
  on first use; `medmlx setup segresnet-renal-cect` downloads ahead of time. For local
90
- weights, pass `weights_path` as a folder containing `segresnet-renal-cect.safetensors`
91
- or as the file itself.
96
+ weights, pass `weights_path` as a folder containing `segresnet-renal-cect.safetensors`.
92
97
 
93
98
  ### Inputs and outputs
94
99
 
95
100
  | Argument | Meaning |
96
101
  | --- | --- |
97
- | `arterial_path`, `venous_path`, `excretory_path` | Arterial, venous and excretory CT in NIfTI, on one voxel grid |
98
- | `output_dir` | Directory for `renalStructures_CECT_segmentation_mask.nii.gz`; created if missing |
99
- | `weights_path` | Optional `.safetensors` file or a folder containing it |
102
+ | `image_paths` | `{"arterial": ..., "venous": ..., "excretory": ...}`: CT phases in NIfTI, on one voxel grid |
103
+ | `output_dir` | Directory for `mask.nii.gz`; created if missing |
104
+ | `weights_path` | Optional folder containing `segresnet-renal-cect.safetensors` |
100
105
  | `overwrite` | `False` by default; an existing mask is replaced only when `True` |
101
- | `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` |
106
+ | `precision` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` |
102
107
  | `streaming` | `False` by default; `True` keeps blending intermediates and logits in temporary mapped files |
103
108
  | `scratch_dir` | Parent directory for the streaming files; defaults to the system temporary directory |
104
109
 
105
110
  Inputs are finite 3D volumes on one voxel grid, with spatial units in millimetres or
106
111
  unspecified. The mask is written on the input grid as the NIfTI reader corrects it.
107
112
 
113
+ The model was trained on CT cropped to the kidney region. Crop around each kidney,
114
+ with a margin of about 15 mm, before running it: on a wider field of view it can label
115
+ vertebral bodies or liver as neoplasm.
116
+
108
117
  The mask is float32 with labels 1 artery, 2 vein, 3 ureter, 4 neoplasm and
109
118
  5 parenchyma; where classes overlap, the lower label wins.
110
119
 
111
- | `arithmetic_profile` | Arithmetic |
120
+ | `precision` | Arithmetic |
112
121
  | :--- | :--- |
113
122
  | `torch-order-fp32` (default) | The default float32 profile |
114
123
  | `compensated-fp32` | Convolution and GroupNorm accumulate in paired Metal floats, with float32 layer outputs |
115
124
  | `compensated-fp48` | The pairs carry through the hidden layers and stitching runs in float64 on the host |
116
125
 
117
- The runner returns `{"outputs": {"mask": path}, "details": {...}}`, with run metadata in `details`.
126
+ `run` returns `{"outputs": {"mask": path}, "artifacts": {"mask": ...}, "details": {...}}`: the `mask` artifact names the labels and the input grid it is on, and `details` holds run metadata.
118
127
  Invalid inputs raise `InvalidInputError`; missing or mismatched weights raise
119
128
  `AssetNotReadyError`; inference failures raise `ModelExecutionError`.
120
129
 
121
130
  Streaming files are removed on success and failure. The final label volume stays in
122
- memory. `run(bundle="renalStructures_CECT_segmentation", weights_path=...)` takes the
123
- same inputs with an explicit `.safetensors` file.
131
+ memory.
124
132
 
125
133
  ### Python API
126
134
 
@@ -128,10 +136,10 @@ same inputs with an explicit `.safetensors` file.
128
136
  from pathlib import Path
129
137
 
130
138
  import numpy as np
131
- from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_model, predict_logits
139
+ from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_network, predict_logits
132
140
 
133
141
  spec = SegResNetSpec(3, 6, 32, upsample_mode="deconv") # renal CECT network
134
- network = load_model(Path("segresnet-renal-cect.safetensors"), spec=spec)
142
+ network = load_network(Path("segresnet-renal-cect.safetensors"), spec=spec)
135
143
  patch = np.zeros((1, 3, 32, 32, 32), dtype=np.float32)
136
144
  logits = forward_patch(network, patch) # float32 NCDHW -> float32 NumPy logits
137
145
  config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
@@ -141,7 +149,7 @@ volume_logits = predict_logits(patch, config, network=network) # stitched slidi
141
149
  - `forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
142
150
  - `predict_logits` takes preprocessed arrays of any size and stitches the bundle's
143
151
  sliding windows. Neither normalizes intensities, applies activations or maps labels.
144
- - `load_model` checks tensor names, shapes and finite float32 values against
152
+ - `load_network` checks tensor names, shapes and finite float32 values against
145
153
  `required_shapes(spec)`.
146
154
  - `WindowTelemetry` and `BundlePredictor` record bounded progress and timing.
147
155
  - Inference requires Apple Silicon with Metal.
@@ -163,4 +171,4 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
163
171
 
164
172
  ## License
165
173
 
166
- [Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.4.0/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.4.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
174
+ [Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.5.0/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.5.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -6,13 +6,17 @@ Segment renal arteries, veins, ureters, tumors and parenchyma in multiphase CT w
6
6
 
7
7
  [![PyPI](https://img.shields.io/pypi/v/segresnet-mlx)](https://pypi.org/project/segresnet-mlx/)
8
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.4.0/LICENSE)
9
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/segresnet-mlx/blob/v0.5.0/LICENSE)
10
10
  [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
11
11
  [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
12
12
  [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
13
13
 
14
14
  [Weights](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx) · [Upstream bundle](https://github.com/Project-MONAI/model-zoo/tree/dev/models/renalStructures_CECT_segmentation) · [MedMLX](https://github.com/MedMLX/medmlx)
15
15
 
16
+ <img src="https://raw.githubusercontent.com/MedMLX/segresnet-mlx/main/docs/example.png" alt="Venous-phase CT of a left kidney with a renal tumor, the predicted renal labels on that slice, and a 3D view of the predicted kidney, tumor, vessels and collecting system" width="100%">
17
+
18
+ <sub>Three-phase CT from <a href="https://doi.org/10.7937/k9/tcia.2018.oblamn27">CPTAC-CCRCC</a> case C3N-00380 (The Cancer Imaging Archive, CC BY 4.0), segmented on a crop around each kidney. The 3D view smooths surfaces and hides fragments under 0.5 mL and labels more than 20 mm from the kidney.</sub>
19
+
16
20
  </div>
17
21
 
18
22
  | Input | Output |
@@ -28,18 +32,20 @@ Segment renal arteries, veins, ureters, tumors and parenchyma in multiphase CT w
28
32
  ```bash
29
33
  uv venv --python 3.13
30
34
  source .venv/bin/activate
31
- uv pip install "segresnet-mlx>=0.4.0"
35
+ uv pip install "segresnet-mlx>=0.5.0"
32
36
  ```
33
37
 
34
38
  ## Run
35
39
 
36
40
  ```python
37
- from segresnet_mlx.medmlx import renal_cect
38
-
39
- result = renal_cect(
40
- arterial_path="arterial.nii.gz",
41
- venous_path="venous.nii.gz",
42
- excretory_path="excretory.nii.gz",
41
+ from segresnet_mlx import run
42
+
43
+ result = run(
44
+ image_paths={
45
+ "arterial": "arterial.nii.gz",
46
+ "venous": "venous.nii.gz",
47
+ "excretory": "excretory.nii.gz",
48
+ },
43
49
  output_dir="out",
44
50
  )
45
51
  print(result["outputs"]["mask"])
@@ -47,40 +53,42 @@ print(result["outputs"]["mask"])
47
53
 
48
54
  Weights download from [`MedMLX/segresnet-renal-cect-mlx`](https://huggingface.co/MedMLX/segresnet-renal-cect-mlx)
49
55
  on first use; `medmlx setup segresnet-renal-cect` downloads ahead of time. For local
50
- weights, pass `weights_path` as a folder containing `segresnet-renal-cect.safetensors`
51
- or as the file itself.
56
+ weights, pass `weights_path` as a folder containing `segresnet-renal-cect.safetensors`.
52
57
 
53
58
  ### Inputs and outputs
54
59
 
55
60
  | Argument | Meaning |
56
61
  | --- | --- |
57
- | `arterial_path`, `venous_path`, `excretory_path` | Arterial, venous and excretory CT in NIfTI, on one voxel grid |
58
- | `output_dir` | Directory for `renalStructures_CECT_segmentation_mask.nii.gz`; created if missing |
59
- | `weights_path` | Optional `.safetensors` file or a folder containing it |
62
+ | `image_paths` | `{"arterial": ..., "venous": ..., "excretory": ...}`: CT phases in NIfTI, on one voxel grid |
63
+ | `output_dir` | Directory for `mask.nii.gz`; created if missing |
64
+ | `weights_path` | Optional folder containing `segresnet-renal-cect.safetensors` |
60
65
  | `overwrite` | `False` by default; an existing mask is replaced only when `True` |
61
- | `arithmetic_profile` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` |
66
+ | `precision` | `torch-order-fp32` (default), `compensated-fp32` or `compensated-fp48` |
62
67
  | `streaming` | `False` by default; `True` keeps blending intermediates and logits in temporary mapped files |
63
68
  | `scratch_dir` | Parent directory for the streaming files; defaults to the system temporary directory |
64
69
 
65
70
  Inputs are finite 3D volumes on one voxel grid, with spatial units in millimetres or
66
71
  unspecified. The mask is written on the input grid as the NIfTI reader corrects it.
67
72
 
73
+ The model was trained on CT cropped to the kidney region. Crop around each kidney,
74
+ with a margin of about 15 mm, before running it: on a wider field of view it can label
75
+ vertebral bodies or liver as neoplasm.
76
+
68
77
  The mask is float32 with labels 1 artery, 2 vein, 3 ureter, 4 neoplasm and
69
78
  5 parenchyma; where classes overlap, the lower label wins.
70
79
 
71
- | `arithmetic_profile` | Arithmetic |
80
+ | `precision` | Arithmetic |
72
81
  | :--- | :--- |
73
82
  | `torch-order-fp32` (default) | The default float32 profile |
74
83
  | `compensated-fp32` | Convolution and GroupNorm accumulate in paired Metal floats, with float32 layer outputs |
75
84
  | `compensated-fp48` | The pairs carry through the hidden layers and stitching runs in float64 on the host |
76
85
 
77
- The runner returns `{"outputs": {"mask": path}, "details": {...}}`, with run metadata in `details`.
86
+ `run` returns `{"outputs": {"mask": path}, "artifacts": {"mask": ...}, "details": {...}}`: the `mask` artifact names the labels and the input grid it is on, and `details` holds run metadata.
78
87
  Invalid inputs raise `InvalidInputError`; missing or mismatched weights raise
79
88
  `AssetNotReadyError`; inference failures raise `ModelExecutionError`.
80
89
 
81
90
  Streaming files are removed on success and failure. The final label volume stays in
82
- memory. `run(bundle="renalStructures_CECT_segmentation", weights_path=...)` takes the
83
- same inputs with an explicit `.safetensors` file.
91
+ memory.
84
92
 
85
93
  ### Python API
86
94
 
@@ -88,10 +96,10 @@ same inputs with an explicit `.safetensors` file.
88
96
  from pathlib import Path
89
97
 
90
98
  import numpy as np
91
- from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_model, predict_logits
99
+ from segresnet_mlx import BUNDLE_CONFIGS, SegResNetSpec, forward_patch, load_network, predict_logits
92
100
 
93
101
  spec = SegResNetSpec(3, 6, 32, upsample_mode="deconv") # renal CECT network
94
- network = load_model(Path("segresnet-renal-cect.safetensors"), spec=spec)
102
+ network = load_network(Path("segresnet-renal-cect.safetensors"), spec=spec)
95
103
  patch = np.zeros((1, 3, 32, 32, 32), dtype=np.float32)
96
104
  logits = forward_patch(network, patch) # float32 NCDHW -> float32 NumPy logits
97
105
  config = BUNDLE_CONFIGS["renalStructures_CECT_segmentation"]
@@ -101,7 +109,7 @@ volume_logits = predict_logits(patch, config, network=network) # stitched slidi
101
109
  - `forward_patch` needs spatial sizes divisible by `2 ** len(spec.blocks_up)`.
102
110
  - `predict_logits` takes preprocessed arrays of any size and stitches the bundle's
103
111
  sliding windows. Neither normalizes intensities, applies activations or maps labels.
104
- - `load_model` checks tensor names, shapes and finite float32 values against
112
+ - `load_network` checks tensor names, shapes and finite float32 values against
105
113
  `required_shapes(spec)`.
106
114
  - `WindowTelemetry` and `BundlePredictor` record bounded progress and timing.
107
115
  - Inference requires Apple Silicon with Metal.
@@ -123,4 +131,4 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
123
131
 
124
132
  ## License
125
133
 
126
- [Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.4.0/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.4.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
134
+ [Apache-2.0](https://github.com/MedMLX/segresnet-mlx/blob/v0.5.0/LICENSE). See [third-party notices](https://github.com/MedMLX/segresnet-mlx/blob/v0.5.0/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.4.0"
7
+ version = "0.5.0"
8
8
  description = "Segment renal arteries, veins, ureters, tumors and parenchyma in multiphase CT with MONAI SegResNet in native MLX"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.13,<3.14"
@@ -38,7 +38,7 @@ authors = [
38
38
  { name = "Alfredo Sandoval Jr." },
39
39
  ]
40
40
  dependencies = [
41
- "medmlx-core>=0.2.6,<0.3",
41
+ "medmlx-core>=0.3.1,<0.4",
42
42
  "mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'",
43
43
  "nibabel>=5.3,<6",
44
44
  "numpy>=2.0,<3",
@@ -49,7 +49,7 @@ segresnet-renal-cect = "segresnet_mlx.medmlx:RENAL_CECT_MODEL"
49
49
 
50
50
  [project.urls]
51
51
  Homepage = "https://medmlx.org"
52
- Documentation = "https://github.com/MedMLX/segresnet-mlx/blob/v0.4.0/README.md"
52
+ Documentation = "https://github.com/MedMLX/segresnet-mlx/blob/v0.5.0/README.md"
53
53
  Repository = "https://github.com/MedMLX/segresnet-mlx"
54
54
  Issues = "https://github.com/MedMLX/segresnet-mlx/issues"
55
55
  Weights = "https://huggingface.co/models?author=MedMLX&search=segresnet"
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING
9
9
 
10
10
  if TYPE_CHECKING:
11
11
  from segresnet_mlx.inference import forward_patch as forward_patch
12
+ from segresnet_mlx.medmlx import run as run
12
13
  from segresnet_mlx.network import SegResNet as SegResNet
13
14
  from segresnet_mlx.predictor import BUNDLE_CONFIGS as BUNDLE_CONFIGS
14
15
  from segresnet_mlx.predictor import BundlePredictor as BundlePredictor
@@ -16,10 +17,10 @@ if TYPE_CHECKING:
16
17
  from segresnet_mlx.predictor import predict_logits as predict_logits
17
18
  from segresnet_mlx.telemetry import WindowTelemetry as WindowTelemetry
18
19
  from segresnet_mlx.topology import SegResNetSpec as SegResNetSpec
19
- from segresnet_mlx.weights import load_model as load_model
20
+ from segresnet_mlx.weights import load_network as load_network
20
21
  from segresnet_mlx.weights import required_shapes as required_shapes
21
22
 
22
- __version__ = "0.4.0"
23
+ __version__ = "0.5.0"
23
24
 
24
25
  _EXPORTS = {
25
26
  "BUNDLE_CONFIGS": "segresnet_mlx.predictor",
@@ -29,9 +30,10 @@ _EXPORTS = {
29
30
  "SlidingWindowConfig": "segresnet_mlx.predictor",
30
31
  "WindowTelemetry": "segresnet_mlx.telemetry",
31
32
  "forward_patch": "segresnet_mlx.inference",
32
- "load_model": "segresnet_mlx.weights",
33
+ "load_network": "segresnet_mlx.weights",
33
34
  "predict_logits": "segresnet_mlx.predictor",
34
35
  "required_shapes": "segresnet_mlx.weights",
36
+ "run": "segresnet_mlx.medmlx",
35
37
  }
36
38
 
37
39
  __all__ = [
@@ -42,9 +44,10 @@ __all__ = [
42
44
  "SlidingWindowConfig",
43
45
  "WindowTelemetry",
44
46
  "forward_patch",
45
- "load_model",
47
+ "load_network",
46
48
  "predict_logits",
47
49
  "required_shapes",
50
+ "run",
48
51
  ]
49
52
 
50
53
 
@@ -5,6 +5,8 @@ from __future__ import annotations
5
5
  from collections.abc import Sequence
6
6
  from typing import NotRequired, TypedDict
7
7
 
8
+ from medmlx_core.outputs import RunResult as _RunResult
9
+
8
10
  from segresnet_mlx.topology import ArithmeticProfile
9
11
 
10
12
  type Json = bool | int | float | str | list[Json] | dict[str, Json] | None
@@ -59,7 +61,7 @@ class Details(TypedDict):
59
61
 
60
62
  weights_revision: NotRequired[str | None]
61
63
  bundle: str
62
- arithmetic_profile: ArithmeticProfile
64
+ precision: ArithmeticProfile
63
65
  streaming: NotRequired[bool]
64
66
  labels: dict[str, str]
65
67
  labels_present: list[int]
@@ -73,8 +75,7 @@ class Details(TypedDict):
73
75
  requires_human_review: bool
74
76
 
75
77
 
76
- class RunResult(TypedDict):
77
- """Result of ``segresnet_mlx.medmlx.run``: ``outputs["mask"]`` is the mask path."""
78
-
79
- outputs: dict[str, str]
80
- details: Details
78
+ # Result of ``segresnet_mlx.run``: ``outputs["mask"]`` is the mask path.
79
+ #
80
+ # ``artifacts["mask"]`` describes the mask file (label map, labels, source grid).
81
+ type RunResult = _RunResult[Details]
@@ -19,6 +19,9 @@ if TYPE_CHECKING:
19
19
  class WorkspaceOptions(TypedDict, total=False):
20
20
  workspace: VolumeWorkspace
21
21
 
22
+ class AccumulationOptions(TypedDict, total=False):
23
+ accumulation: Literal["mlx"]
24
+
22
25
  class MLX(MlxRuntime, Protocol):
23
26
  all = staticmethod(mx.all)
24
27
  isfinite = staticmethod(mx.isfinite)
@@ -35,14 +38,14 @@ if TYPE_CHECKING:
35
38
  inputs: Float32Array,
36
39
  roi_size: Sequence[int],
37
40
  sw_batch_size: int,
38
- predictor: Callable[[Float32Array | Array], Float32Array]
39
- | Callable[[Float32Array | Array, list[list[slice]]], Float32Array],
41
+ predictor: Callable[[Array], Array] | Callable[[Float32Array], Float32Array],
40
42
  *,
41
43
  overlap: float,
42
44
  mode: str,
43
45
  padding_mode: str,
44
46
  with_coord: bool = False,
45
- predictor_input: Literal["numpy"],
47
+ predictor_input: Literal["mlx", "numpy"],
48
+ accumulation: Literal["mlx", "numpy"] = "numpy",
46
49
  preserve_window_strides: bool = False,
47
50
  workspace: VolumeWorkspace | None = None,
48
51
  ) -> Float32Array:
@@ -2,8 +2,6 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import os
6
- import tempfile
7
5
  import time
8
6
  from collections.abc import Mapping
9
7
  from contextlib import nullcontext
@@ -25,7 +23,9 @@ from medmlx_core.errors import (
25
23
  InvalidInputError,
26
24
  ModelExecutionError,
27
25
  )
28
- from medmlx_core.weights import weights_dir, weights_revision
26
+ from medmlx_core.files import PathLike, input_channels, output_targets, publish
27
+ from medmlx_core.outputs import artifact
28
+ from medmlx_core.weights import model_folder, weights_revision
29
29
 
30
30
  from segresnet_mlx import transforms
31
31
  from segresnet_mlx.topology import ArithmeticProfile, SegResNetSpec
@@ -36,8 +36,8 @@ class Bundle:
36
36
  """One MONAI bundle: network topology, inferer settings and file contract.
37
37
 
38
38
  ``roi_size``, ``sw_batch_size``, ``overlap``, ``mode`` and ``padding_mode`` are the
39
- sliding-window settings described in ``SlidingWindowConfig``. ``roles`` names the
40
- ``run`` path arguments the bundle needs, in network channel order. ``labels`` maps
39
+ sliding-window settings described in ``SlidingWindowConfig``. ``channels`` names the
40
+ ``image_paths`` keys the bundle needs, in network channel order. ``labels`` maps
41
41
  each value written to the mask to its name; ``output_dtype`` is the NIfTI dtype.
42
42
  """
43
43
 
@@ -45,7 +45,7 @@ class Bundle:
45
45
  roi_size: tuple[int, int, int]
46
46
  sw_batch_size: int
47
47
  overlap: float
48
- roles: tuple[str, ...]
48
+ channels: tuple[str, ...]
49
49
  labels: Mapping[int, str]
50
50
  output_dtype: str
51
51
  mode: str = "constant"
@@ -60,7 +60,7 @@ BUNDLES: dict[str, Bundle] = {
60
60
  roi_size=(96, 96, 96),
61
61
  sw_batch_size=4,
62
62
  overlap=0.25,
63
- roles=("arterial_path", "venous_path", "excretory_path"),
63
+ channels=("arterial", "venous", "excretory"),
64
64
  labels={
65
65
  0: "background",
66
66
  1: "artery",
@@ -77,7 +77,7 @@ RENAL_CECT_MODEL = {
77
77
  "id": "segresnet-renal-cect",
78
78
  "label": "SegResNet renal CECT",
79
79
  "task": "segmentation",
80
- "run": "segresnet_mlx.medmlx:renal_cect",
80
+ "run": "segresnet_mlx.medmlx:run",
81
81
  # Measured MLX peak for a 478x277x161 three-phase CT; larger inputs need more.
82
82
  "peak_memory_gb": 4.1,
83
83
  "summary": "Renal structures from arterial, venous and excretory phase CT.",
@@ -87,6 +87,11 @@ RENAL_CECT_MODEL = {
87
87
  },
88
88
  }
89
89
 
90
+ RENAL = "renalStructures_CECT_segmentation"
91
+ MODEL_ID = "segresnet-renal-cect"
92
+ WEIGHTS_NAME = "segresnet-renal-cect.safetensors"
93
+ OUTPUT_NAME = "mask.nii.gz"
94
+
90
95
  # The renal bundle's Spacingd pixdim, in mm.
91
96
  _RENAL_SPACING = (0.8, 0.8, 0.8)
92
97
 
@@ -121,93 +126,82 @@ class SpatialInverse:
121
126
 
122
127
  def run(
123
128
  *,
124
- bundle: str,
125
- weights_path: str,
126
- output_dir: str,
127
- arterial_path: str | None = None,
128
- venous_path: str | None = None,
129
- excretory_path: str | None = None,
129
+ image_paths: Mapping[str, PathLike],
130
+ output_dir: PathLike,
131
+ weights_path: PathLike | None = None,
130
132
  overwrite: bool = False,
131
- arithmetic_profile: ArithmeticProfile = "torch-order-fp32",
133
+ precision: ArithmeticProfile = "torch-order-fp32",
132
134
  streaming: bool = False,
133
- scratch_dir: str | None = None,
135
+ scratch_dir: PathLike | None = None,
134
136
  ) -> RunResult:
135
- """Segment one case with a MONAI SegResNet bundle and write the label map.
136
-
137
- ``bundle`` is ``renalStructures_CECT_segmentation``, which takes
138
- ``arterial_path``, ``venous_path`` and ``excretory_path``: co-registered CT
139
- phases on one grid. ``weights_path`` is the native
140
- ``segresnet-renal-cect.safetensors`` file from ``MedMLX/segresnet-renal-cect-mlx``.
141
-
142
- Inputs must be finite 3D NIfTI volumes with identical shape and affine
143
- (atol 1e-5). Writes ``<bundle>_mask.nii.gz`` in ``output_dir`` on the first
144
- input's shape and reader-selected affine (see ``Volume``): float32 labels 0-5,
145
- as the bundle's ``SaveImaged`` wrote them. An existing mask is replaced only when
146
- ``overwrite`` is true; output aliases of input images are refused by a
147
- preflight check. Every argument is checked before weights or inputs are loaded.
148
- The NIfTI spatial-unit field must be mm or unspecified (then assumed mm); other
149
- units are refused, not converted. Paths are not locked against concurrent
150
- replacement after the alias check.
151
-
152
- ``arithmetic_profile="compensated-fp32"`` uses Metal float pairs for
153
- convolution and GroupNorm accumulation, with float32 layer boundaries.
154
- Its source comparison uses float64 internal accumulators and float32
155
- outputs. The default retains the existing Torch-order FP32 arithmetic.
156
- ``compensated-fp48`` carries both words through the hidden layers and uses
157
- float64 host stitching before one float32 logits export. It compares with the
158
- unchanged original graph evaluated in float64 throughout its network and inferer.
137
+ """Segment renal structures from co-registered arterial, venous and excretory CT.
138
+
139
+ ``image_paths`` maps ``arterial``, ``venous`` and ``excretory`` to finite 3D
140
+ NIfTI volumes with identical shape and affine (atol 1e-5); the bundle's
141
+ ``renalStructures_CECT_segmentation`` preprocessing, sliding window and
142
+ inverse transforms run unchanged. Writes ``mask.nii.gz`` in ``output_dir`` on
143
+ the arterial shape and reader-selected affine (see ``Volume``): float32 labels
144
+ 0-5, as the bundle's ``SaveImaged`` wrote them. Every argument and output target
145
+ is checked before weights download or inputs load. The NIfTI spatial-unit field
146
+ must be mm or unspecified (then assumed mm); other units are refused, not
147
+ converted. Paths are not locked against concurrent replacement after the alias
148
+ check.
149
+
150
+ ``precision="compensated-fp32"`` uses Metal float pairs for convolution and
151
+ GroupNorm accumulation, with float32 layer boundaries. Its source comparison
152
+ uses float64 internal accumulators and float32 outputs. The default retains the
153
+ Torch-order FP32 arithmetic. ``compensated-fp48`` carries both words through the
154
+ hidden layers and uses float64 host stitching before one float32 logits export.
155
+ It compares with the unchanged original graph evaluated in float64 throughout
156
+ its network and inferer.
159
157
 
160
158
  Args:
161
- bundle: ``renalStructures_CECT_segmentation``.
162
- weights_path: Path to ``segresnet-renal-cect.safetensors``. Hugging Face
163
- cache file paths are accepted; directories and Torch ``.pt`` checkpoints
164
- are not.
165
- output_dir: Directory for ``<bundle>_mask.nii.gz``; created if missing.
166
- arterial_path: Arterial-phase 3D CT NIfTI; required.
167
- venous_path: Venous-phase 3D CT NIfTI on the arterial grid; required.
168
- excretory_path: Excretory-phase 3D CT NIfTI on the arterial grid; required.
169
- overwrite: Replace an existing output mask when true; defaults to false.
170
- arithmetic_profile: ``torch-order-fp32`` (default), ``compensated-fp32``,
171
- or ``compensated-fp48``.
159
+ image_paths: ``{"arterial": ..., "venous": ..., "excretory": ...}`` CT NIfTI
160
+ files on one voxel grid.
161
+ output_dir: Directory for ``mask.nii.gz``; created if missing.
162
+ weights_path: Folder containing ``segresnet-renal-cect.safetensors`` as
163
+ published in ``MedMLX/segresnet-renal-cect-mlx``; ``None`` downloads it
164
+ into the shared MedMLX cache. Hub-cache symlinks keep their file name.
165
+ overwrite: Replace an existing ``mask.nii.gz`` when true; defaults to false.
166
+ precision: ``torch-order-fp32`` (default), ``compensated-fp32`` or
167
+ ``compensated-fp48``.
172
168
  streaming: Use bounded blending intermediates and temporary mapped logits.
173
169
  The final label volume remains resident; defaults to False.
174
- scratch_dir: Parent directory for temporary maps when streaming is enabled;
175
- None uses the system temporary directory. Files are cleaned up on exit.
170
+ scratch_dir: Existing parent folder for temporary maps when streaming is
171
+ enabled; None uses the system temporary directory. Files are removed on
172
+ exit.
176
173
 
177
174
  Returns:
178
- ``{"outputs": {"mask": path}, "details": {...}}``; ``details`` is described
179
- by ``segresnet_mlx._records.Details`` and always has
180
- ``requires_human_review`` set to true.
175
+ ``{"outputs": {"mask": path}, "artifacts": {"mask": ...}, "details": {...}}``.
176
+ The ``mask`` artifact is a ``label_map`` in ``image_physical`` space on the
177
+ arterial grid, listing the bundle's labels 0-5. ``details`` is described by
178
+ ``segresnet_mlx._records.Details`` and always has ``requires_human_review``
179
+ set to true.
181
180
 
182
181
  Raises:
183
- InvalidInputError: Unknown bundle or profile, missing or absent input paths,
184
- ``overwrite`` or ``streaming`` not a bool, ``output_dir`` not a directory,
185
- an existing output without ``overwrite``, or an unreadable, non-3D,
182
+ InvalidInputError: Unknown precision, wrong or absent ``image_paths`` channels,
183
+ ``overwrite`` or ``streaming`` not a bool, an output target that exists
184
+ without ``overwrite`` or aliases an input, or an unreadable, non-3D,
186
185
  non-finite, non-mm or mismatched-grid NIfTI input.
187
- AssetNotReadyError: The weights file is missing, not ``.safetensors``, or
188
- does not match the bundle's network.
186
+ AssetNotReadyError: The weights folder or file is missing, or the file does
187
+ not match the bundle's network.
189
188
  ModelExecutionError: Inference failed or produced a mask off the source grid
190
189
  or with labels outside the bundle's set.
191
190
  """
192
- values = {
193
- "arterial_path": arterial_path,
194
- "venous_path": venous_path,
195
- "excretory_path": excretory_path,
196
- }
197
- config, mask_path = _check_arguments(
198
- bundle,
199
- values,
191
+ config = BUNDLES[RENAL]
192
+ sources, mask_path = _check_arguments(
193
+ config,
194
+ image_paths,
200
195
  output_dir,
201
196
  overwrite=overwrite,
202
- arithmetic_profile=arithmetic_profile,
197
+ precision=precision,
203
198
  streaming=streaming,
204
199
  scratch_dir=scratch_dir,
205
200
  )
206
- output_root = mask_path.parent
207
- weights = _weights_file(weights_path)
201
+ weights = _weights_file(model_folder(MODEL_ID, weights_path) / WEIGHTS_NAME)
208
202
  started = time.perf_counter()
209
- volumes = load_inputs([(role, values[role]) for role in config.roles])
210
- network = _load_network(weights, config.spec, arithmetic_profile=arithmetic_profile)
203
+ volumes = load_inputs(list(sources.items()))
204
+ network = _load_network(weights, config.spec, arithmetic_profile=precision)
211
205
  loaded = time.perf_counter()
212
206
  image, inverse = preprocess_renal(volumes)
213
207
  prepared = time.perf_counter()
@@ -230,16 +224,24 @@ def run(
230
224
  else postprocess_streaming(logits[0], inverse)
231
225
  )
232
226
  _validate_mask(mask, volumes[0], config)
233
- output_root.mkdir(parents=True, exist_ok=True)
234
- write_atomic(mask_path, mask, volumes[0].affine, config.output_dtype)
227
+ affine, dtype = volumes[0].affine, config.output_dtype
228
+ publish({mask_path: lambda path: transforms.write_nifti(path, mask, affine, dtype)})
235
229
  finished = time.perf_counter()
236
230
  present = sorted(int(value) for value in np.unique(mask))
237
231
  return {
238
232
  "outputs": {"mask": mask_path.as_posix()},
233
+ "artifacts": {
234
+ "mask": artifact(
235
+ kind="label_map",
236
+ coordinate_space="image_physical",
237
+ grid_of=f"image_paths.{config.channels[0]}",
238
+ labels=[{"value": value, "name": name} for value, name in config.labels.items()],
239
+ )
240
+ },
239
241
  "details": {
240
242
  "weights_revision": weights_revision(weights.parent),
241
- "bundle": bundle,
242
- "arithmetic_profile": arithmetic_profile,
243
+ "bundle": RENAL,
244
+ "precision": precision,
243
245
  "streaming": streaming,
244
246
  "labels": {str(value): name for value, name in config.labels.items()},
245
247
  "labels_present": present,
@@ -266,119 +268,31 @@ def run(
266
268
  }
267
269
 
268
270
 
269
- def renal_cect(
270
- *,
271
- arterial_path: str,
272
- venous_path: str,
273
- excretory_path: str,
274
- output_dir: str,
275
- weights_path: str | None = None,
276
- overwrite: bool = False,
277
- arithmetic_profile: ArithmeticProfile = "torch-order-fp32",
278
- streaming: bool = False,
279
- scratch_dir: str | None = None,
280
- ) -> RunResult:
281
- """Segment renal CECT; omit weights_path to download its cached model folder.
282
-
283
- The arterial, venous and excretory CT volumes must share a voxel grid. An
284
- explicit folder contains ``segresnet-renal-cect.safetensors`` as published for
285
- this bundle; an explicit safetensors file is also accepted. Automatic downloads
286
- use ``MedMLX/segresnet-renal-cect-mlx``. Arithmetic and preprocessing are
287
- delegated unchanged to ``run``.
288
-
289
- Args:
290
- arterial_path: Arterial-phase CT NIfTI on the shared input grid.
291
- venous_path: Venous-phase CT NIfTI on the arterial grid.
292
- excretory_path: Excretory-phase CT NIfTI on the arterial grid.
293
- output_dir: Directory for the renal label map.
294
- weights_path: Optional folder containing ``segresnet-renal-cect.safetensors``;
295
- omit to download and reuse the renal bundle. Explicit files remain accepted.
296
- overwrite: Replace an existing output mask when true.
297
- arithmetic_profile: ``torch-order-fp32`` (default), ``compensated-fp32``
298
- or ``compensated-fp48``; see ``run`` for their arithmetic contracts.
299
- streaming: Use bounded blending and mapped logits, as in ``run``.
300
- scratch_dir: Existing parent directory for temporary streaming maps.
301
- """
302
- _check_arguments(
303
- "renalStructures_CECT_segmentation",
304
- {
305
- "arterial_path": arterial_path,
306
- "venous_path": venous_path,
307
- "excretory_path": excretory_path,
308
- },
309
- output_dir,
310
- overwrite=overwrite,
311
- arithmetic_profile=arithmetic_profile,
312
- streaming=streaming,
313
- scratch_dir=scratch_dir,
314
- )
315
- folder = (
316
- weights_dir("segresnet-renal-cect")
317
- if weights_path is None
318
- else Path(weights_path).expanduser()
319
- )
320
- checkpoint = folder / "segresnet-renal-cect.safetensors" if folder.is_dir() else folder
321
- return run(
322
- bundle="renalStructures_CECT_segmentation",
323
- weights_path=str(checkpoint),
324
- output_dir=output_dir,
325
- arterial_path=arterial_path,
326
- venous_path=venous_path,
327
- excretory_path=excretory_path,
328
- overwrite=overwrite,
329
- arithmetic_profile=arithmetic_profile,
330
- streaming=streaming,
331
- scratch_dir=scratch_dir,
332
- )
333
-
334
-
335
271
  def _check_arguments(
336
- bundle: str,
337
- values: Mapping[str, str | None],
338
- output_dir: str,
272
+ config: Bundle,
273
+ image_paths: Mapping[str, PathLike],
274
+ output_dir: PathLike,
339
275
  *,
340
276
  overwrite: bool,
341
- arithmetic_profile: ArithmeticProfile,
342
- streaming: bool = False,
343
- scratch_dir: str | None = None,
344
- ) -> tuple[Bundle, Path]:
277
+ precision: ArithmeticProfile,
278
+ streaming: bool,
279
+ scratch_dir: PathLike | None,
280
+ ) -> tuple[dict[str, Path], Path]:
345
281
  """Check every ``run`` argument before weights, inputs or MLX are loaded.
346
282
 
347
- Returns the bundle settings and the absolute mask path.
283
+ Returns the input files by channel, in network order, and the mask path.
348
284
  """
349
- if bundle not in BUNDLES:
350
- raise InvalidInputError(
351
- f"Unknown SegResNet bundle {bundle!r}; expected one of: {', '.join(BUNDLES)}"
352
- )
353
- if arithmetic_profile not in {"torch-order-fp32", "compensated-fp32", "compensated-fp48"}:
354
- raise InvalidInputError(f"Unknown SegResNet arithmetic profile {arithmetic_profile!r}")
355
- config = BUNDLES[bundle]
356
- missing = [role for role in config.roles if values.get(role) is None]
357
- if missing:
358
- raise InvalidInputError(
359
- f"{bundle} requires {', '.join(config.roles)}; missing {', '.join(missing)}"
360
- )
361
- sources = [Path(str(values[role])).expanduser() for role in config.roles]
362
- for role, source in zip(config.roles, sources, strict=True):
363
- if not source.is_file():
364
- raise InvalidInputError(f"{role} not found: {source}")
365
- for name, flag in (("overwrite", overwrite), ("streaming", streaming)):
366
- if not isinstance(cast(object, flag), bool):
367
- raise InvalidInputError(f"{name} must be true or false")
285
+ if precision not in {"torch-order-fp32", "compensated-fp32", "compensated-fp48"}:
286
+ raise InvalidInputError(f"Unknown SegResNet precision {precision!r}")
287
+ sources = input_channels(image_paths, config.channels)
288
+ if not isinstance(cast(object, streaming), bool):
289
+ raise InvalidInputError("streaming must be true or false")
368
290
  if streaming and scratch_dir is not None and not Path(scratch_dir).expanduser().is_dir():
369
291
  raise InvalidInputError("scratch_dir must name an existing directory")
370
- output_root = Path(output_dir).expanduser().resolve()
371
- if output_root.exists() and not output_root.is_dir():
372
- raise InvalidInputError(f"output_dir is not a directory: {output_root}")
373
- mask_path = output_root / f"{bundle}_mask.nii.gz"
374
- for source in sources:
375
- if mask_path.resolve() == source.resolve() or (
376
- mask_path.exists() and mask_path.samefile(source)
377
- ):
378
- raise InvalidInputError("SegResNet output must differ from every input image")
379
- if mask_path.exists() and not overwrite:
380
- raise InvalidInputError(f"Output exists: {mask_path}; pass overwrite=true to replace it")
381
- return config, mask_path
292
+ targets = output_targets(
293
+ output_dir, {"mask": OUTPUT_NAME}, overwrite=overwrite, inputs=sources.values()
294
+ )
295
+ return sources, targets["mask"]
382
296
 
383
297
 
384
298
  def preprocess_renal(volumes: list[Volume]) -> tuple[Float32Array, SpatialInverse]:
@@ -428,10 +342,14 @@ def postprocess_renal(logits: Float32Array, inverse: SpatialInverse) -> Float32A
428
342
  map (values 0-5) on the source grid. The inversion is applied to the logits
429
343
  before the sigmoid, in the bundle's order.
430
344
  """
431
- values, affine = transforms.invert_spacing(logits, inverse.affine, inverse.resampling)
345
+ # Background never contributes to the final class map.
346
+ values, affine = transforms.invert_spacing(logits[1:], inverse.affine, inverse.resampling)
432
347
  values, _ = transforms.invert_orientation(values, affine, inverse.orientation)
433
- binary = transforms.sigmoid_threshold_mask(values).astype(np.float32)
434
- return transforms.merge_classes(binary)[0]
348
+ # Preserve float32 sigmoid rounding at the threshold, including near-negative logits.
349
+ active = transforms.sigmoid_threshold_mask(values)
350
+ # Foreground channels correspond to class IDs 1..5; the first active one wins.
351
+ first_active = np.argmax(active, axis=0) + 1
352
+ return np.where(np.any(active, axis=0), first_active, 0).astype(np.float32)
435
353
 
436
354
 
437
355
  def postprocess_streaming(logits: Float32Array, inverse: SpatialInverse) -> Float32Array:
@@ -454,7 +372,7 @@ def postprocess_streaming(logits: Float32Array, inverse: SpatialInverse) -> Floa
454
372
  return labels
455
373
 
456
374
 
457
- def _weights_file(weights_path: str) -> Path:
375
+ def _weights_file(weights_path: str | Path) -> Path:
458
376
  """Validate a safetensors file path while retaining any Hub-cache symlink."""
459
377
  # MLX identifies the file format from the supplied name. Hub cache paths are
460
378
  # named .safetensors symlinks whose underlying content-addressed blobs have no suffix.
@@ -473,7 +391,7 @@ def _weights_file(weights_path: str) -> Path:
473
391
  return path
474
392
 
475
393
 
476
- def load_inputs(roles: list[tuple[str, str | None]]) -> list[Volume]:
394
+ def load_inputs(roles: list[tuple[str, str | Path | None]]) -> list[Volume]:
477
395
  """Load each ``(role, path)`` and require one shared voxel grid.
478
396
 
479
397
  Every volume must match the first one's shape and affine (``atol=1e-5``).
@@ -540,10 +458,10 @@ def _load_network(
540
458
  arithmetic_profile: ArithmeticProfile = "torch-order-fp32",
541
459
  ) -> SegResNet:
542
460
  """Strictly load converted weights for the bundle topology."""
543
- from segresnet_mlx.weights import load_model
461
+ from segresnet_mlx.weights import load_network
544
462
 
545
463
  try:
546
- return load_model(weights, spec=spec, arithmetic_profile=arithmetic_profile)
464
+ return load_network(weights, spec=spec, arithmetic_profile=arithmetic_profile)
547
465
  except (InvalidInputError, ValueError, RuntimeError) as error:
548
466
  raise AssetNotReadyError(
549
467
  f"SegResNet weights {weights} do not match {spec}: {error}",
@@ -594,18 +512,4 @@ def _validate_mask(mask: MaskArray, reference: Volume, config: Bundle) -> None:
594
512
  raise ModelExecutionError("SegResNet exported labels outside the bundle contract")
595
513
 
596
514
 
597
- def write_atomic(path: Path, mask: MaskArray, affine: Float64Array, dtype: str) -> None:
598
- """Write the mask NIfTI via a temporary file in ``path.parent``, then rename it.
599
-
600
- A failure therefore never leaves a partial file at ``path``.
601
- """
602
- descriptor, name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".nii.gz", dir=path.parent)
603
- os.close(descriptor)
604
- try:
605
- transforms.write_nifti(Path(name), mask, affine, dtype)
606
- os.replace(name, path)
607
- finally:
608
- Path(name).unlink(missing_ok=True)
609
-
610
-
611
- __all__ = ["BUNDLES", "RENAL_CECT_MODEL", "renal_cect", "run"]
515
+ __all__ = ["BUNDLES", "OUTPUT_NAME", "RENAL_CECT_MODEL", "run"]
@@ -3,10 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import time
6
- from collections.abc import Callable
7
- from contextlib import nullcontext
6
+ from collections.abc import Callable, Generator
7
+ from contextlib import contextmanager, nullcontext
8
8
  from dataclasses import dataclass
9
- from typing import TYPE_CHECKING, cast
9
+ from typing import TYPE_CHECKING, Literal, cast
10
10
 
11
11
  from segresnet_mlx._records import BundleConfig, InfererConfig
12
12
  from segresnet_mlx._runtime import import_mlx
@@ -15,7 +15,13 @@ if TYPE_CHECKING:
15
15
  from ignite.engine import Engine, Events
16
16
  from medmlx_core.volume_workspace import VolumeWorkspace
17
17
 
18
- from segresnet_mlx._types import MLX, Array, CoreSlidingWindow, WorkspaceOptions
18
+ from segresnet_mlx._types import (
19
+ MLX,
20
+ AccumulationOptions,
21
+ Array,
22
+ CoreSlidingWindow,
23
+ WorkspaceOptions,
24
+ )
19
25
  from segresnet_mlx.network import SegResNet
20
26
 
21
27
  import numpy as np
@@ -75,10 +81,10 @@ BUNDLE_CONFIGS = {
75
81
 
76
82
 
77
83
  class BundlePredictor:
78
- """Synchronized MLX window callback with an injected network.
84
+ """Native MLX window callback with an injected network.
79
85
 
80
- ``forward`` retains the MLX-array callback API; ``predict_logits`` passes
81
- synchronized NumPy logits directly to the host stitcher. Telemetry
86
+ ``forward`` retains the MLX-array callback API; ``predict_logits`` exports
87
+ host logits or opts into FP32 device slab stitching. Telemetry
82
88
  lifecycle remains caller-owned here, allowing an engine to finish only after
83
89
  postprocessing. The module-level ``predict_logits`` owns a direct-call session.
84
90
  """
@@ -107,10 +113,10 @@ class BundlePredictor:
107
113
  "network_device": str(self.mx.default_device()),
108
114
  "transforms_and_stitching_device": "cpu",
109
115
  "compile": False,
110
- "synchronization": "mx.eval and mx.synchronize before host export",
116
+ "synchronization": "mx.eval; global synchronization only for telemetry",
111
117
  "window_timing_scope": (
112
- "synchronized network, MLX input creation and host export; "
113
- "excludes validation and telemetry"
118
+ "synchronized network and MLX input creation; host export only "
119
+ "for host-output callbacks; excludes validation and telemetry"
114
120
  ),
115
121
  "peak_memory_scope": "predictor lifetime, including warmup",
116
122
  }
@@ -132,35 +138,64 @@ class BundlePredictor:
132
138
  def forward(self, values: HostArray | Array) -> Array:
133
139
  """Run one finite float32 window and return its logits as an MLX array.
134
140
 
135
- The logits are exported to host NumPy for the finite check and timing, then
136
- wrapped again as an MLX array for callers that expect one.
141
+ Device inputs and logits stay in MLX; finite checks read one Boolean.
137
142
  """
138
143
  try:
139
- return cast(ArrayFactory, self.mx.array)(self._forward_window(values))
144
+ if isinstance(values, self.mx.array):
145
+ if values.dtype != self.mx.float32 or not bool(
146
+ self.mx.all(self.mx.isfinite(values)).item()
147
+ ):
148
+ raise InvalidInputError(f"{self.network_label} input must be finite float32")
149
+ validated = values
150
+ else:
151
+ validated = self._host_input(values)
152
+ with self._measure_window():
153
+ device_input = (
154
+ validated if isinstance(validated, self.mx.array)
155
+ else cast(ArrayFactory, self.mx.array)(validated)
156
+ )
157
+ return self._forward_validated_mlx(device_input)
140
158
  except BaseException as error:
141
159
  if self.telemetry is not None:
142
160
  self.telemetry.fail(error)
143
161
  raise
144
162
 
145
163
  def _forward_window(self, values: HostArray | Array) -> Float32Array:
146
- """Run and synchronize one window, returning finite host logits."""
147
- host = self._host_input(values)
164
+ """Validate one standalone window and explicitly export finite host logits."""
165
+ return self._forward_validated_window(self._host_input(values))
166
+
167
+ def _forward_validated_mlx(self, values: Array) -> Array:
168
+ """Run validated float32 MLX input and check logits on device."""
169
+ logits = self.network(values)
170
+ finite = self.mx.all(self.mx.isfinite(logits))
171
+ self.mx.eval(logits, finite)
172
+ if not bool(finite.item()):
173
+ raise RuntimeError(f"{self.network_label} produced non-finite logits")
174
+ return logits
175
+
176
+ @contextmanager
177
+ def _measure_window(self) -> Generator[None]:
178
+ """Synchronize and time completed window work only when telemetry is active."""
179
+ if self.telemetry is None:
180
+ yield
181
+ return
148
182
  self.mx.synchronize()
149
183
  started = time.perf_counter()
150
- result = self.network(cast(ArrayFactory, self.mx.array)(host))
151
- self.mx.eval(result)
184
+ yield
152
185
  self.mx.synchronize()
153
- output = cast(Float32Array, np.array(result))
154
186
  elapsed = time.perf_counter() - started
155
- if not np.isfinite(output).all():
156
- raise RuntimeError(f"{self.network_label} produced non-finite logits")
157
- if self.telemetry is not None:
158
- self.telemetry.observe(elapsed, self.mx.get_peak_memory())
159
- # The allocator cache is kept across windows: every window has the same
160
- # shapes, so later windows reuse the buffers instead of reallocating
161
- # them. ``predict_logits`` releases the cache once the volume is done.
162
- del result
163
- return output
187
+ self.telemetry.observe(elapsed, self.mx.get_peak_memory())
188
+
189
+ def _forward_validated_window(self, values: Float32Array) -> Float32Array:
190
+ """Export one already-validated host patch without rescanning its input."""
191
+ with self._measure_window():
192
+ logits = self._forward_validated_mlx(cast(ArrayFactory, self.mx.array)(values))
193
+ return cast(Float32Array, np.array(logits))
194
+
195
+ def _forward_device_window(self, values: Array) -> Array:
196
+ """Run a patch of a validated volume, retaining its logits on device."""
197
+ with self._measure_window():
198
+ return self._forward_validated_mlx(values)
164
199
 
165
200
  def _host_input(self, values: HostArray | Array) -> Float32Array:
166
201
  """Admit finite float32 input as a NumPy array or raise an input error."""
@@ -175,6 +210,7 @@ class BundlePredictor:
175
210
  configuration: SlidingWindowConfig,
176
211
  *,
177
212
  workspace: VolumeWorkspace | None = None,
213
+ accumulation: Literal["numpy", "mlx"] = "numpy",
178
214
  ) -> Float32Array:
179
215
  """Stitch preprocessed ``(N, C, D, H, W)`` float32 data into full-volume logits.
180
216
 
@@ -183,6 +219,10 @@ class BundlePredictor:
183
219
  placement and blending follow MONAI's ``SlidingWindowInferer`` via the
184
220
  shared core. Callers own telemetry completion.
185
221
 
222
+ ``accumulation='mlx'`` opts into FP32 Metal slabs and completed-slab
223
+ export. The default uses host blending; the wide-precision API remains
224
+ a separate float64 host route.
225
+
186
226
  Raises:
187
227
  InvalidInputError: If ``values`` is not finite float32.
188
228
  ValueError: If ``values`` is not rank 5.
@@ -194,10 +234,17 @@ class BundlePredictor:
194
234
  ).sliding_window_inference
195
235
 
196
236
  try:
237
+ if accumulation not in {"numpy", "mlx"}:
238
+ raise ValueError("accumulation must be 'numpy' or 'mlx'")
197
239
  host = self._host_input(values)
198
240
  require_ncdhw(host, name="SegResNet input")
199
241
  if self.telemetry is not None:
200
- self.telemetry.set_metadata({"sw_batch_size": configuration.sw_batch_size})
242
+ self.telemetry.set_metadata({
243
+ "sw_batch_size": configuration.sw_batch_size,
244
+ "transforms_and_stitching_device": (
245
+ "cpu transforms, Metal stitching" if accumulation == "mlx" else "cpu"
246
+ ),
247
+ })
201
248
  if (
202
249
  workspace is None
203
250
  and host.shape[0] == 1
@@ -227,20 +274,25 @@ class BundlePredictor:
227
274
  )
228
275
  # One constant-weight window contributes its logits exactly once;
229
276
  # blending would only copy and divide the same full volume.
230
- return self._forward_window(window)[(slice(None), slice(None), *crop)]
277
+ return self._forward_validated_window(window)[(slice(None), slice(None), *crop)]
278
+ accumulation_options: AccumulationOptions = (
279
+ {"accumulation": "mlx"} if accumulation == "mlx" else {}
280
+ )
231
281
  return sliding_window_inference(
232
282
  host,
233
283
  configuration.roi_size,
234
284
  configuration.sw_batch_size,
235
- self._forward_window,
285
+ self._forward_device_window if accumulation == "mlx"
286
+ else self._forward_validated_window,
236
287
  overlap=configuration.overlap,
237
288
  mode=configuration.mode,
238
289
  padding_mode=configuration.padding_mode,
239
- predictor_input="numpy",
290
+ predictor_input="mlx" if accumulation == "mlx" else "numpy",
240
291
  # MLX reduction kernels depend on layout. Match MONAI's sliced
241
292
  # batch-one input without a second padded volume or patch copy.
242
293
  preserve_window_strides=True,
243
294
  workspace=workspace,
295
+ **accumulation_options,
244
296
  )
245
297
  except BaseException as error:
246
298
  if self.telemetry is not None:
@@ -256,16 +308,18 @@ def predict_logits(
256
308
  *,
257
309
  network: Callable[[Array], Array],
258
310
  telemetry: WindowTelemetry | None = None,
311
+ accumulation: Literal["numpy", "mlx"] = "numpy",
259
312
  ) -> Float32Array:
260
313
  """Return float32 NumPy NCDHW logits, completing optional window telemetry.
261
314
 
262
315
  ``values`` is preprocessed, finite float32 ``(N, C, D, H, W)``; the result has the
263
316
  same spatial size. Input preparation, activation, label mapping, image I/O and QC
264
- are external.
317
+ are external. ``accumulation='mlx'`` opts into FP32 Metal slab blending and
318
+ requires a shared core with that accumulation option.
265
319
  """
266
320
  with telemetry.session() if telemetry is not None else nullcontext():
267
321
  predictor = BundlePredictor(network, telemetry=telemetry)
268
- return predictor.predict_logits(values, configuration)
322
+ return predictor.predict_logits(values, configuration, accumulation=accumulation)
269
323
 
270
324
 
271
325
  def predict_wide_logits(
@@ -16,7 +16,9 @@ are in mm; the runner validates spatial units, and these functions assume mm.
16
16
 
17
17
  from __future__ import annotations
18
18
 
19
+ import os
19
20
  from collections.abc import Sequence
21
+ from concurrent.futures import ThreadPoolExecutor
20
22
  from dataclasses import dataclass
21
23
  from pathlib import Path
22
24
  from typing import cast
@@ -54,8 +56,9 @@ type Float64Array = npt.NDArray[np.float64]
54
56
  # monai.data.utils.AFFINE_TOL
55
57
  AFFINE_TOL = 1e-3
56
58
  _LABELS = (("L", "R"), ("P", "A"), ("I", "S"))
57
- # Bound the float64 corner arrays of one resampling chunk.
59
+ # Bound the float64 corner arrays of all resampling blocks in flight together.
58
60
  _CHUNK_VOXELS = 1 << 20
61
+ _THREADS = min(8, os.cpu_count() or 1)
59
62
 
60
63
 
61
64
  @dataclass(frozen=True, slots=True)
@@ -339,19 +342,37 @@ def _grid_sample(
339
342
  theta[row, column] == 0 for row in range(3) for column in range(3) if row != column
340
343
  )
341
344
  result = np.empty((data.shape[0], depth, height, width), dtype=np.float32)
342
- step = max(1, _CHUNK_VOXELS // max(1, height * width * data.shape[0]))
343
- for start in range(0, depth, step):
344
- stop = min(depth, start + step)
345
+ # Blocks of whole output rows, run on _THREADS threads (NumPy releases the
346
+ # GIL). Each block holds _CHUNK_VOXELS // _THREADS voxels, so the blocks in
347
+ # flight together hold about one serial chunk of float64 temporaries. Every
348
+ # voxel uses the same arithmetic in any split, so the result is bitwise
349
+ # identical to a single-threaded pass.
350
+ budget = max(1, _CHUNK_VOXELS // _THREADS)
351
+ row_voxels = max(1, width * data.shape[0])
352
+ planes = max(1, budget // (height * row_voxels))
353
+ rows = height if planes > 1 else min(height, max(1, budget // row_voxels))
354
+
355
+ def fill(start: int, top: int) -> None:
356
+ stop, bottom = min(depth, start + planes), min(height, top + rows)
345
357
  if separable:
346
358
  gx = zx[0][0] + ys[0][0]
347
- gy = zx[1][0, 0] + ys[1]
359
+ gy = zx[1][0, 0] + ys[1][top:bottom]
348
360
  gz = zx[2][start:stop, 0] + ys[2][0]
349
- result[:, start:stop] = _sample_separable(data, gx, gy, gz)
361
+ result[:, start:stop, top:bottom] = _sample_separable(data, gx, gy, gz)
350
362
  else:
351
363
  coordinates = [
352
- zx[row][start:stop, None, :] + ys[row][None, :, None] for row in range(3)
364
+ zx[row][start:stop, None, :] + ys[row][None, top:bottom, None] for row in range(3)
353
365
  ]
354
- result[:, start:stop] = _sample(data, *coordinates)
366
+ result[:, start:stop, top:bottom] = _sample(data, *coordinates)
367
+
368
+ with ThreadPoolExecutor(max_workers=_THREADS) as pool:
369
+ blocks = [
370
+ pool.submit(fill, start, top)
371
+ for start in range(0, depth, planes)
372
+ for top in range(0, height, rows)
373
+ ]
374
+ for block in blocks:
375
+ block.result()
355
376
  return result
356
377
 
357
378
 
@@ -64,7 +64,7 @@ def required_shapes(spec: SegResNetSpec) -> dict[str, tuple[int, ...]]:
64
64
  return shapes
65
65
 
66
66
 
67
- def load_model(
67
+ def load_network(
68
68
  weights_path: Path,
69
69
  *,
70
70
  spec: SegResNetSpec,
File without changes
File without changes