flexray-mlx 0.2.7__tar.gz → 0.3.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.
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flexray-mlx
3
- Version: 0.2.7
3
+ Version: 0.3.0
4
4
  Summary: Segment anatomical structures in radiographs with FleXray and native MLX
5
5
  Project-URL: Homepage, https://medmlx.org
6
- Project-URL: Documentation, https://github.com/MedMLX/flexray-mlx/blob/v0.2.7/README.md
6
+ Project-URL: Documentation, https://github.com/MedMLX/flexray-mlx/blob/v0.3.0/README.md
7
7
  Project-URL: Repository, https://github.com/MedMLX/flexray-mlx
8
8
  Project-URL: Issues, https://github.com/MedMLX/flexray-mlx/issues
9
9
  Project-URL: Weights, https://huggingface.co/MedMLX/flexray-mlx
@@ -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
28
28
  Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
29
29
  Requires-Dist: numpy<3,>=2.0
30
30
  Requires-Dist: pillow<14,>=13
@@ -45,14 +45,12 @@ Segment anatomical structures in radiographs with FleXray and native MLX.
45
45
 
46
46
  [![PyPI](https://img.shields.io/pypi/v/flexray-mlx)](https://pypi.org/project/flexray-mlx/)
47
47
  [![Python](https://img.shields.io/pypi/pyversions/flexray-mlx)](https://pypi.org/project/flexray-mlx/)
48
- [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/flexray-mlx/blob/v0.2.7/LICENSE)
48
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/flexray-mlx/blob/v0.3.0/LICENSE)
49
49
  [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
50
50
  [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/flexray-mlx)
51
51
  [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
52
52
 
53
- [Model weights](https://huggingface.co/MedMLX/flexray-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
54
-
55
- <img src="https://raw.githubusercontent.com/MedMLX/flexray-mlx/v0.2.7/docs/showcase.png" alt="Chest radiograph with lung, heart and individual rib segmentations" width="100%">
53
+ <img src="https://raw.githubusercontent.com/MedMLX/flexray-mlx/main/docs/showcase.png" alt="Chest radiograph with lung, heart and individual rib segmentations" width="100%">
56
54
 
57
55
  </div>
58
56
 
@@ -60,52 +58,37 @@ Segment anatomical structures in radiographs with FleXray and native MLX.
60
58
  | :--- | :--- |
61
59
  | Raster image or single-frame DICOM | Structure masks and probabilities |
62
60
 
63
- Weights: 2.0 GB download, all five ensemble members. Peak MLX memory: 1.2 GB for a 1929×2207 chest radiograph with the default single model.
64
-
65
- ## Use with MedMLX
66
-
67
- The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this model. It installs this runtime, downloads its weights on first use, and lets an AI agent describe, check and run `flexray` for you.
68
-
69
- ```sh
70
- uv tool install --python 3.13 "medmlx[segment,mcp]"
71
- MEDMLX="$(uv tool dir --bin --color never)/medmlx"
72
- mkdir -p "$HOME/medmlx-work"
73
- claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
74
- ```
75
-
76
- 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 flexray`.
77
-
78
- > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
61
+ | Model | Weights download | Peak MLX memory | Measured on |
62
+ | :--- | ---: | ---: | :--- |
63
+ | `flexray` | 2.0 GB for all five ensemble members | 1.2 GB | 1929×2207 chest radiograph, default single model |
79
64
 
80
65
  ## Install
81
66
 
82
67
  ```bash
83
68
  uv venv --python 3.13
84
69
  source .venv/bin/activate
85
- uv pip install "flexray-mlx>=0.2.7"
70
+ uv pip install "flexray-mlx>=0.3.0"
86
71
  ```
87
72
 
88
73
  ## Run
89
74
 
90
75
  ```python
91
- from flexray_mlx.medmlx import run
76
+ from flexray_mlx import run
92
77
 
93
78
  result = run(image_path="chest.png", output_dir="out")
94
79
  print(result["outputs"]["mask"])
95
80
  ```
96
81
 
97
- Omitting `weights_path` downloads `MedMLX/flexray-mlx` into the shared MedMLX cache on
98
- first use; interrupted downloads resume and later runs work offline. With MedMLX
99
- installed, `medmlx setup flexray` downloads it ahead of time. To use your own copy, pass
100
- a folder containing `ensemble.json` and
101
- `members/flux0375/{config.yml,label_schema.json,model.safetensors,preprocessing.json}`
102
- as `weights_path`. Automatic setup prepares the flagship (`ensemble=False`);
103
- `ensemble=True` requires all five members in an explicit folder.
104
- `details.weights_revision` records the downloaded commit, or `null` for a folder without
105
- a MedMLX download record.
106
-
107
82
  Use `label_name` to select a structure.
108
83
 
84
+ | `ensemble` | Weights |
85
+ | :--- | :--- |
86
+ | `False` (default) | The flagship `flux0375`. Omitting `weights_path` downloads `MedMLX/flexray-mlx` into the shared MedMLX cache on first use; with MedMLX installed, `medmlx setup flexray` downloads it ahead of time |
87
+ | `True` | All five members, in an explicit `weights_path` folder |
88
+
89
+ A local folder holds `ensemble.json` and
90
+ `members/flux0375/{config.yml,label_schema.json,model.safetensors,preprocessing.json}`.
91
+
109
92
  ### Inputs and outputs
110
93
 
111
94
  | Argument | Meaning |
@@ -120,37 +103,44 @@ Use `label_name` to select a structure.
120
103
  | `tta_seed` | `None` by default, unseeded as in FleXray; an integer reproduces Torch CPU augmentation draws |
121
104
  | `normalization_scheme` | `None` keeps the bundle's; or `none`, `minmax`, `percentile_minmax` or `standardize` |
122
105
  | `overwrite` | `False` by default; existing outputs are replaced only when `True` |
106
+ | `member_residency` | `all` by default; `one` loads ensemble members one at a time, spooling per-view probabilities to a temporary folder, with identical results |
123
107
 
124
- DICOM files end in `.dcm` or `.dicom` (any case) or have `DICM` at byte 128. Accepting
125
- a file does not mean the model suits its modality. Output paths must differ from each
126
- other, the input and the bundle files, including links, even with `overwrite`.
108
+ - **DICOM:** files end in `.dcm` or `.dicom` (any case) or have `DICM` at byte 128.
109
+ Accepting a file does not mean the model suits its modality.
110
+ - **Output paths** must differ from each other, the input and the bundle files,
111
+ including links, even with `overwrite`.
127
112
 
128
113
  | Output | File | Content |
129
114
  | --- | --- | --- |
130
115
  | `mask` | `source_image_label.png` | uint8 0/1 mask of the selected structure on the source pixel grid |
131
- | `display_source` | `source_image.png` | 8-bit grayscale source the mask overlays |
116
+ | `preview` | `source_image.png` | 8-bit grayscale source the mask overlays |
132
117
  | `probabilities` | `probabilities.npy` | float32 61×256×256 sigmoid probabilities on the padded model grid |
133
- | `prediction` | `prediction.json` | Labels, selected channel, threshold, members and content box |
134
-
135
- FleXray thresholds on the model grid and exports no source-grid images; the PNGs are a
136
- MedMLX addition. The mask is thresholded first, then cropped to the content box and
137
- restored to the source size with nearest-neighbour resampling, so no new decisions come
138
- from interpolation. `run` returns `{"outputs": {...}, "details": {...}}`; `details`
139
- repeats the label and channel, threshold, members, TTA passes, seed, normalization,
140
- source size, content box and mask pixel count. Missing or incompatible assets raise
141
- `AssetNotReadyError`; invalid inputs or existing outputs raise `InvalidInputError`;
142
- non-finite probabilities raise `ModelExecutionError` before anything is written.
143
-
144
- The [published bundle](https://huggingface.co/MedMLX/flexray-mlx/tree/722d8341570e8b9e1196cf50e57892da84974fcc)
118
+ | `metadata` | `prediction.json` | Labels, selected channel, threshold, members and content box |
119
+
120
+ - **Source-grid PNGs:** FleXray thresholds on the model grid and exports no source-grid
121
+ images; the PNGs are a MedMLX addition. The mask is thresholded first, then resized
122
+ with nearest neighbor to the padded canvas and unpadded, which inverts the
123
+ preprocessing geometry, so no new decisions come from interpolation.
124
+ - **Return value:** `{"outputs": {...}, "artifacts": {...}, "details": {...}}`. `artifacts` marks
125
+ the mask as a binary mask named for `label_name` on the input's pixel grid, and the probabilities
126
+ as a field on the model grid; run metadata is in `details`.
127
+
128
+ | Error | Raised when |
129
+ | :--- | :--- |
130
+ | `AssetNotReadyError` | Assets are missing or incompatible |
131
+ | `InvalidInputError` | Inputs are invalid or outputs already exist |
132
+ | `ModelExecutionError` | Probabilities are non-finite; raised before anything is written |
133
+
134
+ **Ensemble members.** The [published bundle](https://huggingface.co/MedMLX/flexray-mlx/tree/722d8341570e8b9e1196cf50e57892da84974fcc)
145
135
  holds only `flux0375`; its `ensemble.json` still lists all five members in order
146
136
  (`flux0375`, `flux000`, `flux025`, `flux050`, `flux075`). For `ensemble=True`, use the
147
137
  [upstream snapshot](https://huggingface.co/VictorButoi/flexray/tree/6b63ddf09cfdff99aea494e3738cf243a4e22cdb)
148
138
  with all five member folders.
149
139
 
150
- Augmented views follow FleXray's `tta_v3` chain: flips, inversion, CLAHE or gamma,
151
- contrast, sharpness and Gaussian noise. Gamma on negative normalized pixels can produce
152
- NaN, which the runner rejects. The released weights were trained with percentile
153
- normalization; other schemes are not validated.
140
+ **Augmentation and normalization.** Augmented views follow FleXray's `tta_v3` chain:
141
+ flips, inversion, CLAHE or gamma, contrast, sharpness and Gaussian noise. Gamma on
142
+ negative normalized pixels can produce NaN, which the runner rejects. The released
143
+ weights were trained with percentile normalization; other schemes are not validated.
154
144
 
155
145
  ### Python API
156
146
 
@@ -164,17 +154,34 @@ model = FleXrayMlxModel(Path("flexray/members/flux0375"))
164
154
  logits = model(np.zeros((1, 1, 256, 256), dtype=np.float32)) # Bx1x256x256 -> Bx61x256x256
165
155
  ```
166
156
 
167
- The member folder needs the released `config.yml` and `model.safetensors`; loading
168
- converts convolution weights to MLX layout and every tensor to float32, keeping the
169
- names. Inputs are prepared images; preparation, sigmoid, ensembling, TTA and
170
- source-grid restoration are the caller's. `flexray_mlx.tta.predict_with_tta(forward_fn,
171
- images, tta_samples=..., seed=..., normalizer=...)` takes one or more forward callables
172
- and already normalized float32 BxCxHxW images, and returns `(logits, probabilities)`;
173
- pass the `normalize` method of `flexray_mlx.medmlx.ImagePreprocessing` as `normalizer`
174
- to follow the bundle. Inference needs Apple Silicon with Metal and has no CPU fallback.
157
+ - The member folder needs the released `config.yml` and `model.safetensors`. Loading
158
+ converts convolution weights to MLX layout and every tensor to float32, keeping the
159
+ names, and rejects tensor names or shapes that differ from the released network.
160
+ - Inputs are prepared images; preparation, sigmoid, ensembling, TTA and source-grid
161
+ restoration are the caller's.
162
+ - `flexray_mlx.tta.predict_with_tta(forward_fn, images, tta_samples=..., seed=..., normalizer=...)`
163
+ takes one or more forward callables and already normalized float32 BxCxHxW images, and
164
+ returns `(logits, probabilities)`. Pass the `normalize` method of
165
+ `flexray_mlx.medmlx.ImagePreprocessing` as `normalizer` to follow the bundle.
166
+ `flexray_mlx.tta.tta_probabilities` takes the same arguments and returns only the
167
+ probabilities.
168
+ - Inference requires Apple Silicon with Metal.
175
169
 
176
- ## License
170
+ ## Use with MedMLX
171
+
172
+ Use the [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) to run `flexray` from an MCP client. Weights download on first use.
177
173
 
178
- [Apache-2.0](https://github.com/MedMLX/flexray-mlx/blob/v0.2.7/LICENSE). See [third-party notices](https://github.com/MedMLX/flexray-mlx/blob/v0.2.7/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms. FleXray weights are noncommercial (CC-BY-NC-4.0).
174
+ ```sh
175
+ uv tool install --python 3.13 "medmlx[segment,mcp]"
176
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
177
+ mkdir -p "$HOME/medmlx-work"
178
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
179
+ ```
180
+
181
+ 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 flexray`.
182
+
183
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
184
+
185
+ ## License
179
186
 
180
- For research and education. Outputs require human review.
187
+ [Apache-2.0](https://github.com/MedMLX/flexray-mlx/blob/v0.3.0/LICENSE). See [third-party notices](https://github.com/MedMLX/flexray-mlx/blob/v0.3.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms. FleXray weights are noncommercial (CC-BY-NC-4.0).
@@ -0,0 +1,148 @@
1
+ <div align="center">
2
+
3
+ # flexray-mlx
4
+
5
+ Segment anatomical structures in radiographs with FleXray and native MLX.
6
+
7
+ [![PyPI](https://img.shields.io/pypi/v/flexray-mlx)](https://pypi.org/project/flexray-mlx/)
8
+ [![Python](https://img.shields.io/pypi/pyversions/flexray-mlx)](https://pypi.org/project/flexray-mlx/)
9
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/flexray-mlx/blob/v0.3.0/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/flexray-mlx)
12
+ [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
13
+
14
+ <img src="https://raw.githubusercontent.com/MedMLX/flexray-mlx/main/docs/showcase.png" alt="Chest radiograph with lung, heart and individual rib segmentations" width="100%">
15
+
16
+ </div>
17
+
18
+ | Input | Output |
19
+ | :--- | :--- |
20
+ | Raster image or single-frame DICOM | Structure masks and probabilities |
21
+
22
+ | Model | Weights download | Peak MLX memory | Measured on |
23
+ | :--- | ---: | ---: | :--- |
24
+ | `flexray` | 2.0 GB for all five ensemble members | 1.2 GB | 1929×2207 chest radiograph, default single model |
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ uv venv --python 3.13
30
+ source .venv/bin/activate
31
+ uv pip install "flexray-mlx>=0.3.0"
32
+ ```
33
+
34
+ ## Run
35
+
36
+ ```python
37
+ from flexray_mlx import run
38
+
39
+ result = run(image_path="chest.png", output_dir="out")
40
+ print(result["outputs"]["mask"])
41
+ ```
42
+
43
+ Use `label_name` to select a structure.
44
+
45
+ | `ensemble` | Weights |
46
+ | :--- | :--- |
47
+ | `False` (default) | The flagship `flux0375`. Omitting `weights_path` downloads `MedMLX/flexray-mlx` into the shared MedMLX cache on first use; with MedMLX installed, `medmlx setup flexray` downloads it ahead of time |
48
+ | `True` | All five members, in an explicit `weights_path` folder |
49
+
50
+ A local folder holds `ensemble.json` and
51
+ `members/flux0375/{config.yml,label_schema.json,model.safetensors,preprocessing.json}`.
52
+
53
+ ### Inputs and outputs
54
+
55
+ | Argument | Meaning |
56
+ | --- | --- |
57
+ | `image_path` | One radiograph: an image Pillow reads (PNG, TIFF, ...) or a single-frame 2D DICOM |
58
+ | `output_dir` | Output directory, created if missing |
59
+ | `weights_path` | Optional bundle folder, as above |
60
+ | `label_name` | Structure to threshold into the mask, `lungs` by default (any label, such as `heart`, `rib_5` or `vertebra_l1`) |
61
+ | `ensemble` | `False` by default; `True` averages all five released members |
62
+ | `threshold` | Probability cutoff in [0, 1], 0.5 by default |
63
+ | `tta_samples` | Passes per member, 1 by default: one plain view plus augmented views |
64
+ | `tta_seed` | `None` by default, unseeded as in FleXray; an integer reproduces Torch CPU augmentation draws |
65
+ | `normalization_scheme` | `None` keeps the bundle's; or `none`, `minmax`, `percentile_minmax` or `standardize` |
66
+ | `overwrite` | `False` by default; existing outputs are replaced only when `True` |
67
+ | `member_residency` | `all` by default; `one` loads ensemble members one at a time, spooling per-view probabilities to a temporary folder, with identical results |
68
+
69
+ - **DICOM:** files end in `.dcm` or `.dicom` (any case) or have `DICM` at byte 128.
70
+ Accepting a file does not mean the model suits its modality.
71
+ - **Output paths** must differ from each other, the input and the bundle files,
72
+ including links, even with `overwrite`.
73
+
74
+ | Output | File | Content |
75
+ | --- | --- | --- |
76
+ | `mask` | `source_image_label.png` | uint8 0/1 mask of the selected structure on the source pixel grid |
77
+ | `preview` | `source_image.png` | 8-bit grayscale source the mask overlays |
78
+ | `probabilities` | `probabilities.npy` | float32 61×256×256 sigmoid probabilities on the padded model grid |
79
+ | `metadata` | `prediction.json` | Labels, selected channel, threshold, members and content box |
80
+
81
+ - **Source-grid PNGs:** FleXray thresholds on the model grid and exports no source-grid
82
+ images; the PNGs are a MedMLX addition. The mask is thresholded first, then resized
83
+ with nearest neighbor to the padded canvas and unpadded, which inverts the
84
+ preprocessing geometry, so no new decisions come from interpolation.
85
+ - **Return value:** `{"outputs": {...}, "artifacts": {...}, "details": {...}}`. `artifacts` marks
86
+ the mask as a binary mask named for `label_name` on the input's pixel grid, and the probabilities
87
+ as a field on the model grid; run metadata is in `details`.
88
+
89
+ | Error | Raised when |
90
+ | :--- | :--- |
91
+ | `AssetNotReadyError` | Assets are missing or incompatible |
92
+ | `InvalidInputError` | Inputs are invalid or outputs already exist |
93
+ | `ModelExecutionError` | Probabilities are non-finite; raised before anything is written |
94
+
95
+ **Ensemble members.** The [published bundle](https://huggingface.co/MedMLX/flexray-mlx/tree/722d8341570e8b9e1196cf50e57892da84974fcc)
96
+ holds only `flux0375`; its `ensemble.json` still lists all five members in order
97
+ (`flux0375`, `flux000`, `flux025`, `flux050`, `flux075`). For `ensemble=True`, use the
98
+ [upstream snapshot](https://huggingface.co/VictorButoi/flexray/tree/6b63ddf09cfdff99aea494e3738cf243a4e22cdb)
99
+ with all five member folders.
100
+
101
+ **Augmentation and normalization.** Augmented views follow FleXray's `tta_v3` chain:
102
+ flips, inversion, CLAHE or gamma, contrast, sharpness and Gaussian noise. Gamma on
103
+ negative normalized pixels can produce NaN, which the runner rejects. The released
104
+ weights were trained with percentile normalization; other schemes are not validated.
105
+
106
+ ### Python API
107
+
108
+ ```python
109
+ from pathlib import Path
110
+
111
+ import numpy as np
112
+ from flexray_mlx import FleXrayMlxModel
113
+
114
+ model = FleXrayMlxModel(Path("flexray/members/flux0375"))
115
+ logits = model(np.zeros((1, 1, 256, 256), dtype=np.float32)) # Bx1x256x256 -> Bx61x256x256
116
+ ```
117
+
118
+ - The member folder needs the released `config.yml` and `model.safetensors`. Loading
119
+ converts convolution weights to MLX layout and every tensor to float32, keeping the
120
+ names, and rejects tensor names or shapes that differ from the released network.
121
+ - Inputs are prepared images; preparation, sigmoid, ensembling, TTA and source-grid
122
+ restoration are the caller's.
123
+ - `flexray_mlx.tta.predict_with_tta(forward_fn, images, tta_samples=..., seed=..., normalizer=...)`
124
+ takes one or more forward callables and already normalized float32 BxCxHxW images, and
125
+ returns `(logits, probabilities)`. Pass the `normalize` method of
126
+ `flexray_mlx.medmlx.ImagePreprocessing` as `normalizer` to follow the bundle.
127
+ `flexray_mlx.tta.tta_probabilities` takes the same arguments and returns only the
128
+ probabilities.
129
+ - Inference requires Apple Silicon with Metal.
130
+
131
+ ## Use with MedMLX
132
+
133
+ Use the [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) to run `flexray` from an MCP client. Weights download on first use.
134
+
135
+ ```sh
136
+ uv tool install --python 3.13 "medmlx[segment,mcp]"
137
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
138
+ mkdir -p "$HOME/medmlx-work"
139
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
140
+ ```
141
+
142
+ 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 flexray`.
143
+
144
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
145
+
146
+ ## License
147
+
148
+ [Apache-2.0](https://github.com/MedMLX/flexray-mlx/blob/v0.3.0/LICENSE). See [third-party notices](https://github.com/MedMLX/flexray-mlx/blob/v0.3.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms. FleXray weights are noncommercial (CC-BY-NC-4.0).
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "flexray-mlx"
7
- version = "0.2.7"
7
+ version = "0.3.0"
8
8
  description = "Segment anatomical structures in radiographs with FleXray and native MLX"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.13,<3.14"
@@ -37,7 +37,7 @@ authors = [
37
37
  { name = "Alfredo Sandoval Jr." },
38
38
  ]
39
39
  dependencies = [
40
- "medmlx-core>=0.2.6,<0.3",
40
+ "medmlx-core>=0.3,<0.4",
41
41
  "mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'",
42
42
  "numpy>=2.0,<3",
43
43
  "pillow>=13,<14",
@@ -48,7 +48,7 @@ dependencies = [
48
48
 
49
49
  [project.urls]
50
50
  Homepage = "https://medmlx.org"
51
- Documentation = "https://github.com/MedMLX/flexray-mlx/blob/v0.2.7/README.md"
51
+ Documentation = "https://github.com/MedMLX/flexray-mlx/blob/v0.3.0/README.md"
52
52
  Repository = "https://github.com/MedMLX/flexray-mlx"
53
53
  Issues = "https://github.com/MedMLX/flexray-mlx/issues"
54
54
  Weights = "https://huggingface.co/MedMLX/flexray-mlx"
@@ -0,0 +1,30 @@
1
+ """Radiograph anatomy segmentation with FleXray in native MLX.
2
+
3
+ ``run`` runs one radiograph end to end. Names load on first access, so
4
+ importing the package (or the medmlx declaration) does not import MLX.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from importlib import import_module
10
+ from typing import TYPE_CHECKING
11
+
12
+ if TYPE_CHECKING:
13
+ from flexray_mlx.medmlx import run as run
14
+ from flexray_mlx.mlx_model import FleXrayMlxModel as FleXrayMlxModel
15
+
16
+ __all__ = ["FleXrayMlxModel", "run"]
17
+
18
+ __version__ = "0.3.0"
19
+
20
+ _EXPORTS = {"FleXrayMlxModel": "flexray_mlx.mlx_model", "run": "flexray_mlx.medmlx"}
21
+
22
+
23
+ def __getattr__(name: str) -> object:
24
+ """Load a public name from its module on first access and cache it."""
25
+ module = _EXPORTS.get(name)
26
+ if module is None:
27
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
28
+ value = getattr(import_module(module), name)
29
+ globals()[name] = value
30
+ return value
@@ -0,0 +1,200 @@
1
+ """FP32 Metal fusions for the released FleXray decoder's NHWC tensors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import lru_cache
6
+ from typing import TYPE_CHECKING, cast
7
+
8
+ from medmlx_core.typing import MetalKernel
9
+
10
+ from flexray_mlx._types import NativeRuntime
11
+
12
+ if TYPE_CHECKING:
13
+ from mlx.core import array
14
+
15
+
16
+ _RESIZE_CONCAT = """
17
+ // Preserve the original graph's separate multiply/add rounding.
18
+ #pragma clang fp contract(off)
19
+ uint i = thread_position_in_grid.x;
20
+ constexpr int C = CI + CS;
21
+ if (i >= N * OH * OW * C) return;
22
+ uint c = i % C;
23
+ uint ox = (i / C) % OW;
24
+ uint oy = (i / (C * OW)) % OH;
25
+ uint n = i / (C * OW * OH);
26
+ if (c >= CI) {
27
+ out[i] = skip[((n * OH + oy) * OW + ox) * CS + c - CI];
28
+ return;
29
+ }
30
+ // align_corners=True: match the FP32 source-to-destination endpoint ratio.
31
+ float iy = float(oy) * (float(H - 1) / float(OH - 1));
32
+ float ix = float(ox) * (float(W - 1) / float(OW - 1));
33
+ iy = metal::clamp(iy, 0.0f, float(H - 1));
34
+ ix = metal::clamp(ix, 0.0f, float(W - 1));
35
+ uint y0 = uint(metal::floor(iy)), y1 = uint(metal::ceil(iy));
36
+ uint x0 = uint(metal::floor(ix)), x1 = uint(metal::ceil(ix));
37
+ float fy = iy - float(y0), fx = ix - float(x0);
38
+ float a = inp[((n * H + y0) * W + x0) * CI + c];
39
+ float b = inp[((n * H + y0) * W + x1) * CI + c];
40
+ float d = inp[((n * H + y1) * W + x0) * CI + c];
41
+ float e = inp[((n * H + y1) * W + x1) * CI + c];
42
+ out[i] = ((1.0f - fy) * (1.0f - fx)) * a
43
+ + ((1.0f - fy) * fx) * b
44
+ + (fy * (1.0f - fx)) * d
45
+ + (fy * fx) * e;
46
+ """
47
+
48
+
49
+ @lru_cache(maxsize=1)
50
+ def _resize_concat_kernel(mx: NativeRuntime) -> MetalKernel:
51
+ """Compile and cache the Metal kernel for corner-aligned resize and concatenation."""
52
+ return cast(
53
+ MetalKernel,
54
+ mx.fast.metal_kernel(
55
+ name="flexray_bilinear_concat",
56
+ input_names=["inp", "skip"],
57
+ output_names=["out"],
58
+ source=_RESIZE_CONCAT,
59
+ compile_options={"math_mode": "safe"},
60
+ ),
61
+ )
62
+
63
+
64
+ def upsample_concat(x: array, skip: array, *, mx: NativeRuntime) -> array:
65
+ """Join a 2x bilinear NHWC resize with ``skip``, keeping resized channels first.
66
+
67
+ Inputs must be FP32, with the same positive batch size and a skip grid
68
+ exactly twice ``x`` in both spatial dimensions. Corner-aligned sampling
69
+ matches the released decoder, including singleton source dimensions.
70
+ One kernel writes the joined tensor without materializing the four bilinear
71
+ sample tensors or the separate resized image. Noncontiguous inputs are
72
+ made contiguous by MLX's custom-kernel boundary.
73
+
74
+ Raises ``ValueError`` when the output exceeds signed 32-bit indexing, before
75
+ dispatch. The output is larger than either input, so this also bounds their
76
+ index products.
77
+ """
78
+ if x.ndim != 4 or skip.ndim != 4:
79
+ raise ValueError("FleXray decoder fusion requires NHWC tensors")
80
+ n, h, w, ci = x.shape
81
+ if min(n, h, w, ci, skip.shape[-1]) < 1 or skip.shape[:3] != (n, 2 * h, 2 * w):
82
+ raise ValueError("FleXray MLX decoder grid mismatch")
83
+ if x.dtype != mx.float32 or skip.dtype != mx.float32:
84
+ raise TypeError("FleXray decoder fusion requires float32 inputs")
85
+ oh, ow, cs = skip.shape[1:]
86
+ shape = (n, oh, ow, ci + cs)
87
+ count = n * oh * ow * (ci + cs)
88
+ if count > 2**31 - 1:
89
+ raise ValueError("FleXray decoder fusion exceeds signed 32-bit indexing")
90
+ return _resize_concat_kernel(mx)(
91
+ inputs=[x, skip],
92
+ template=[
93
+ ("N", n), ("H", h), ("W", w), ("CI", ci), ("CS", cs), ("OH", oh), ("OW", ow),
94
+ ],
95
+ grid=(count, 1, 1),
96
+ threadgroup=(256, 1, 1),
97
+ output_shapes=[shape],
98
+ output_dtypes=[mx.float32],
99
+ )[0]
100
+
101
+
102
+ # Torch's float32 CPU ``sigmoid`` is ``1 / (exp(0 - x) + 1)`` with SLEEF's FMA
103
+ # ``expf``; ``medmlx.sleef_expf`` emulates it in NumPy. This kernel performs the
104
+ # same float32 operations in the same order with explicit FMAs and contraction
105
+ # disabled. Metal flushes subnormal arithmetic results to zero, so a quotient
106
+ # below the smallest normal float is formed by integer round-to-nearest-even
107
+ # division instead; its bits equal the IEEE float32 quotient.
108
+ _SLEEF_SIGMOID = """
109
+ #pragma clang fp contract(off)
110
+ uint i = thread_position_in_grid.x;
111
+ if (i >= N * C * H * W) return;
112
+ uint x = i % W;
113
+ uint y = (i / W) % H;
114
+ uint c = (i / (W * H)) % C;
115
+ uint n = i / (W * H * C);
116
+ uint source_x = flipped[n] != 0 ? W - 1 - x : x;
117
+ float d = 0.0f - logits[((n * H + y) * W + source_x) * C + c];
118
+ int q = int(metal::rint(d * 1.442695040888963407359924681001892137426645954152985934135449406931f));
119
+ float qf = float(q);
120
+ float s = metal::fma(qf, -0.693145751953125f, d);
121
+ s = metal::fma(qf, -1.428606765330187045e-06f, s);
122
+ float u = 0.000198527617612853646278381f;
123
+ u = metal::fma(u, s, 0.00139304355252534151077271f);
124
+ u = metal::fma(u, s, 0.00833336077630519866943359f);
125
+ u = metal::fma(u, s, 0.0416664853692054748535156f);
126
+ u = metal::fma(u, s, 0.166666671633720397949219f);
127
+ u = metal::fma(u, s, 0.5f);
128
+ float squared = s * s;
129
+ u = 1.0f + metal::fma(squared, u, s);
130
+ int half_q = q >> 1;
131
+ u = u * metal::ldexp(1.0f, half_q);
132
+ u = u * metal::ldexp(1.0f, q - half_q);
133
+ if (d < -104.0f) u = 0.0f;
134
+ if (100.0f < d) u = INFINITY;
135
+ float denominator = u + 1.0f;
136
+ uint bits = as_type<uint>(denominator);
137
+ if (bits >= 0x7E800000u && bits < 0x7F800000u) {
138
+ // 2**126 <= denominator < inf: the quotient is at most 2**-126. With
139
+ // denominator = m * 2**(e - 23), the result is k * 2**-149 for
140
+ // k = round(2**(172 - e) / m), and k is also the result's bit pattern.
141
+ ulong m = ulong((bits & 0x7FFFFFu) | 0x800000u);
142
+ uint e = (bits >> 23) - 127u;
143
+ ulong numerator = 1ul << (172u - e);
144
+ ulong k = numerator / m;
145
+ ulong twice_remainder = 2ul * (numerator - k * m);
146
+ if (twice_remainder > m || (twice_remainder == m && (k & 1ul) != 0ul)) k += 1ul;
147
+ out[i] = as_type<float>(uint(k));
148
+ } else {
149
+ out[i] = 1.0f / denominator;
150
+ }
151
+ """
152
+
153
+
154
+ @lru_cache(maxsize=1)
155
+ def _sigmoid_kernel(mx: NativeRuntime) -> MetalKernel:
156
+ """Compile and cache the Torch-CPU-exact sigmoid kernel."""
157
+ return cast(
158
+ MetalKernel,
159
+ mx.fast.metal_kernel(
160
+ name="flexray_torch_cpu_sigmoid",
161
+ input_names=["logits", "flipped"],
162
+ output_names=["out"],
163
+ source=_SLEEF_SIGMOID,
164
+ compile_options={"math_mode": "safe"},
165
+ ),
166
+ )
167
+
168
+
169
+ def torch_cpu_sigmoid(logits: array, flipped: array, *, mx: NativeRuntime) -> array:
170
+ """Unflip NHWC logits and return Torch-CPU-exact sigmoid probabilities in NCHW.
171
+
172
+ Args:
173
+ logits: Float32 ``(B, H, W, C)`` logits, channels last.
174
+ flipped: ``(B,)`` int32; nonzero samples are mirrored back along ``W``.
175
+
176
+ Returns:
177
+ Float32 ``(B, C, H, W)`` probabilities whose bits equal
178
+ ``medmlx.multilabel_probabilities`` of the unflipped NCHW logits for
179
+ every non-NaN input (NaN logits give NaN).
180
+
181
+ Raises:
182
+ ValueError: Wrong ranks or batch sizes, or more than 2**31 - 1 elements.
183
+ TypeError: ``logits`` is not float32 or ``flipped`` is not int32.
184
+ """
185
+ if logits.ndim != 4 or flipped.ndim != 1 or flipped.shape[0] != logits.shape[0]:
186
+ raise ValueError("FleXray sigmoid requires NHWC logits and one flip flag per sample")
187
+ if logits.dtype != mx.float32 or flipped.dtype != mx.int32:
188
+ raise TypeError("FleXray sigmoid requires float32 logits and int32 flip flags")
189
+ n, h, w, c = logits.shape
190
+ count = n * h * w * c
191
+ if min(n, h, w, c) < 1 or count > 2**31 - 1:
192
+ raise ValueError("FleXray sigmoid requires positive dimensions within 32-bit indexing")
193
+ return _sigmoid_kernel(mx)(
194
+ inputs=[logits, flipped],
195
+ template=[("N", n), ("H", h), ("W", w), ("C", c)],
196
+ grid=(count, 1, 1),
197
+ threadgroup=(256, 1, 1),
198
+ output_shapes=[(n, c, h, w)],
199
+ output_dtypes=[mx.float32],
200
+ )[0]