flexray-mlx 0.2.7__tar.gz → 0.3.1__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.1
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.1/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.2
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.1/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.1"
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`. It downloads from `MedMLX/flexray-mlx` on first use; `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,45 @@ 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 no suffix and `DICM`
109
+ at byte 128; other suffixes, such as `.ima`, are read as raster images.
110
+ Accepting a file does not mean the model suits its modality.
111
+ - **Output paths** must differ from each other, the input and the bundle files,
112
+ including links, even with `overwrite`.
127
113
 
128
114
  | Output | File | Content |
129
115
  | --- | --- | --- |
130
116
  | `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 |
117
+ | `preview` | `source_image.png` | 8-bit grayscale source the mask overlays |
132
118
  | `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)
119
+ | `metadata` | `prediction.json` | Labels, selected channel, threshold, members and content box |
120
+
121
+ - **Source-grid PNGs:** FleXray thresholds on the model grid and exports no source-grid
122
+ images; the PNGs are a MedMLX addition. The mask is thresholded first, then resized
123
+ with nearest neighbor to the padded canvas and unpadded, which inverts the
124
+ preprocessing geometry, so no new decisions come from interpolation.
125
+ - **Return value:** `{"outputs": {...}, "artifacts": {...}, "details": {...}}`. `artifacts` marks
126
+ the mask as a binary mask named for `label_name` on the input's pixel grid, and the probabilities
127
+ as a field on the model grid; run metadata is in `details`.
128
+
129
+ | Error | Raised when |
130
+ | :--- | :--- |
131
+ | `AssetNotReadyError` | Assets are missing or incompatible |
132
+ | `InvalidInputError` | Inputs are invalid or outputs already exist |
133
+ | `ModelExecutionError` | Probabilities are non-finite; raised before anything is written |
134
+
135
+ **Ensemble members.** The [published bundle](https://huggingface.co/MedMLX/flexray-mlx/tree/722d8341570e8b9e1196cf50e57892da84974fcc)
145
136
  holds only `flux0375`; its `ensemble.json` still lists all five members in order
146
137
  (`flux0375`, `flux000`, `flux025`, `flux050`, `flux075`). For `ensemble=True`, use the
147
138
  [upstream snapshot](https://huggingface.co/VictorButoi/flexray/tree/6b63ddf09cfdff99aea494e3738cf243a4e22cdb)
148
139
  with all five member folders.
149
140
 
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.
141
+ **Augmentation and normalization.** Augmented views follow FleXray's `tta_v3` chain:
142
+ flips, inversion, CLAHE or gamma, contrast, sharpness and Gaussian noise. Gamma on
143
+ negative normalized pixels can produce NaN, which the runner rejects. The released
144
+ weights were trained with percentile normalization; other schemes are not validated.
154
145
 
155
146
  ### Python API
156
147
 
@@ -164,17 +155,33 @@ model = FleXrayMlxModel(Path("flexray/members/flux0375"))
164
155
  logits = model(np.zeros((1, 1, 256, 256), dtype=np.float32)) # Bx1x256x256 -> Bx61x256x256
165
156
  ```
166
157
 
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.
158
+ - The member folder needs the released `config.yml` and `model.safetensors`. Loading
159
+ converts convolution weights to MLX layout and every tensor to float32, keeping the
160
+ names, and rejects tensor names or shapes that differ from the released network.
161
+ - Inputs are prepared images; preparation, sigmoid, ensembling, TTA and source-grid
162
+ restoration are up to you.
163
+ - `flexray_mlx.tta.predict_with_tta(forward_fn, images, tta_samples=..., seed=..., normalizer=...)`
164
+ takes one or more forward callables and already normalized float32 BxCxHxW images, and
165
+ returns `(logits, probabilities)`. Pass the `normalize` method of
166
+ `flexray_mlx.medmlx.ImagePreprocessing` as `normalizer` to follow the bundle.
167
+ `flexray_mlx.tta.tta_probabilities` takes the same arguments and returns only the
168
+ probabilities.
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.1/LICENSE). See [third-party notices](https://github.com/MedMLX/flexray-mlx/blob/v0.3.1/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.1/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.1"
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`. It downloads from `MedMLX/flexray-mlx` on first use; `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 no suffix and `DICM`
70
+ at byte 128; other suffixes, such as `.ima`, are read as raster images.
71
+ Accepting a file does not mean the model suits its modality.
72
+ - **Output paths** must differ from each other, the input and the bundle files,
73
+ including links, even with `overwrite`.
74
+
75
+ | Output | File | Content |
76
+ | --- | --- | --- |
77
+ | `mask` | `source_image_label.png` | uint8 0/1 mask of the selected structure on the source pixel grid |
78
+ | `preview` | `source_image.png` | 8-bit grayscale source the mask overlays |
79
+ | `probabilities` | `probabilities.npy` | float32 61×256×256 sigmoid probabilities on the padded model grid |
80
+ | `metadata` | `prediction.json` | Labels, selected channel, threshold, members and content box |
81
+
82
+ - **Source-grid PNGs:** FleXray thresholds on the model grid and exports no source-grid
83
+ images; the PNGs are a MedMLX addition. The mask is thresholded first, then resized
84
+ with nearest neighbor to the padded canvas and unpadded, which inverts the
85
+ preprocessing geometry, so no new decisions come from interpolation.
86
+ - **Return value:** `{"outputs": {...}, "artifacts": {...}, "details": {...}}`. `artifacts` marks
87
+ the mask as a binary mask named for `label_name` on the input's pixel grid, and the probabilities
88
+ as a field on the model grid; run metadata is in `details`.
89
+
90
+ | Error | Raised when |
91
+ | :--- | :--- |
92
+ | `AssetNotReadyError` | Assets are missing or incompatible |
93
+ | `InvalidInputError` | Inputs are invalid or outputs already exist |
94
+ | `ModelExecutionError` | Probabilities are non-finite; raised before anything is written |
95
+
96
+ **Ensemble members.** The [published bundle](https://huggingface.co/MedMLX/flexray-mlx/tree/722d8341570e8b9e1196cf50e57892da84974fcc)
97
+ holds only `flux0375`; its `ensemble.json` still lists all five members in order
98
+ (`flux0375`, `flux000`, `flux025`, `flux050`, `flux075`). For `ensemble=True`, use the
99
+ [upstream snapshot](https://huggingface.co/VictorButoi/flexray/tree/6b63ddf09cfdff99aea494e3738cf243a4e22cdb)
100
+ with all five member folders.
101
+
102
+ **Augmentation and normalization.** Augmented views follow FleXray's `tta_v3` chain:
103
+ flips, inversion, CLAHE or gamma, contrast, sharpness and Gaussian noise. Gamma on
104
+ negative normalized pixels can produce NaN, which the runner rejects. The released
105
+ weights were trained with percentile normalization; other schemes are not validated.
106
+
107
+ ### Python API
108
+
109
+ ```python
110
+ from pathlib import Path
111
+
112
+ import numpy as np
113
+ from flexray_mlx import FleXrayMlxModel
114
+
115
+ model = FleXrayMlxModel(Path("flexray/members/flux0375"))
116
+ logits = model(np.zeros((1, 1, 256, 256), dtype=np.float32)) # Bx1x256x256 -> Bx61x256x256
117
+ ```
118
+
119
+ - The member folder needs the released `config.yml` and `model.safetensors`. Loading
120
+ converts convolution weights to MLX layout and every tensor to float32, keeping the
121
+ names, and rejects tensor names or shapes that differ from the released network.
122
+ - Inputs are prepared images; preparation, sigmoid, ensembling, TTA and source-grid
123
+ restoration are up to you.
124
+ - `flexray_mlx.tta.predict_with_tta(forward_fn, images, tta_samples=..., seed=..., normalizer=...)`
125
+ takes one or more forward callables and already normalized float32 BxCxHxW images, and
126
+ returns `(logits, probabilities)`. Pass the `normalize` method of
127
+ `flexray_mlx.medmlx.ImagePreprocessing` as `normalizer` to follow the bundle.
128
+ `flexray_mlx.tta.tta_probabilities` takes the same arguments and returns only the
129
+ probabilities.
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.1/LICENSE). See [third-party notices](https://github.com/MedMLX/flexray-mlx/blob/v0.3.1/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.1"
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.2,<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.1/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.1"
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,192 @@
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
7
+
8
+ from medmlx_core.typing import MetalKernel, MlxRuntime
9
+
10
+ if TYPE_CHECKING:
11
+ from mlx.core import array
12
+
13
+
14
+ _RESIZE_CONCAT = """
15
+ // Preserve the original graph's separate multiply/add rounding.
16
+ #pragma clang fp contract(off)
17
+ uint i = thread_position_in_grid.x;
18
+ constexpr int C = CI + CS;
19
+ if (i >= N * OH * OW * C) return;
20
+ uint c = i % C;
21
+ uint ox = (i / C) % OW;
22
+ uint oy = (i / (C * OW)) % OH;
23
+ uint n = i / (C * OW * OH);
24
+ if (c >= CI) {
25
+ out[i] = skip[((n * OH + oy) * OW + ox) * CS + c - CI];
26
+ return;
27
+ }
28
+ // align_corners=True: match the FP32 source-to-destination endpoint ratio.
29
+ float iy = float(oy) * (float(H - 1) / float(OH - 1));
30
+ float ix = float(ox) * (float(W - 1) / float(OW - 1));
31
+ iy = metal::clamp(iy, 0.0f, float(H - 1));
32
+ ix = metal::clamp(ix, 0.0f, float(W - 1));
33
+ uint y0 = uint(metal::floor(iy)), y1 = uint(metal::ceil(iy));
34
+ uint x0 = uint(metal::floor(ix)), x1 = uint(metal::ceil(ix));
35
+ float fy = iy - float(y0), fx = ix - float(x0);
36
+ float a = inp[((n * H + y0) * W + x0) * CI + c];
37
+ float b = inp[((n * H + y0) * W + x1) * CI + c];
38
+ float d = inp[((n * H + y1) * W + x0) * CI + c];
39
+ float e = inp[((n * H + y1) * W + x1) * CI + c];
40
+ out[i] = ((1.0f - fy) * (1.0f - fx)) * a
41
+ + ((1.0f - fy) * fx) * b
42
+ + (fy * (1.0f - fx)) * d
43
+ + (fy * fx) * e;
44
+ """
45
+
46
+
47
+ @lru_cache(maxsize=1)
48
+ def _resize_concat_kernel(mx: MlxRuntime) -> MetalKernel:
49
+ """Compile and cache the Metal kernel for corner-aligned resize and concatenation."""
50
+ return mx.fast.metal_kernel(
51
+ name="flexray_bilinear_concat",
52
+ input_names=["inp", "skip"],
53
+ output_names=["out"],
54
+ source=_RESIZE_CONCAT,
55
+ compile_options={"math_mode": "safe"},
56
+ )
57
+
58
+
59
+ def upsample_concat(x: array, skip: array, *, mx: MlxRuntime) -> array:
60
+ """Join a 2x bilinear NHWC resize with ``skip``, keeping resized channels first.
61
+
62
+ Inputs must be FP32, with the same positive batch size and a skip grid
63
+ exactly twice ``x`` in both spatial dimensions. Corner-aligned sampling
64
+ matches the released decoder, including singleton source dimensions.
65
+ One kernel writes the joined tensor without materializing the four bilinear
66
+ sample tensors or the separate resized image. Noncontiguous inputs are
67
+ made contiguous by MLX's custom-kernel boundary.
68
+
69
+ Raises ``ValueError`` when the output exceeds signed 32-bit indexing, before
70
+ dispatch. The output is larger than either input, so this also bounds their
71
+ index products.
72
+ """
73
+ if x.ndim != 4 or skip.ndim != 4:
74
+ raise ValueError("FleXray decoder fusion requires NHWC tensors")
75
+ n, h, w, ci = x.shape
76
+ if min(n, h, w, ci, skip.shape[-1]) < 1 or skip.shape[:3] != (n, 2 * h, 2 * w):
77
+ raise ValueError("FleXray MLX decoder grid mismatch")
78
+ if x.dtype != mx.float32 or skip.dtype != mx.float32:
79
+ raise TypeError("FleXray decoder fusion requires float32 inputs")
80
+ oh, ow, cs = skip.shape[1:]
81
+ shape = (n, oh, ow, ci + cs)
82
+ count = n * oh * ow * (ci + cs)
83
+ if count > 2**31 - 1:
84
+ raise ValueError("FleXray decoder fusion exceeds signed 32-bit indexing")
85
+ return _resize_concat_kernel(mx)(
86
+ inputs=[x, skip],
87
+ template=[
88
+ ("N", n), ("H", h), ("W", w), ("CI", ci), ("CS", cs), ("OH", oh), ("OW", ow),
89
+ ],
90
+ grid=(count, 1, 1),
91
+ threadgroup=(256, 1, 1),
92
+ output_shapes=[shape],
93
+ output_dtypes=[mx.float32],
94
+ )[0]
95
+
96
+
97
+ # Torch's float32 CPU ``sigmoid`` is ``1 / (exp(0 - x) + 1)`` with SLEEF's FMA
98
+ # ``expf``; ``medmlx.sleef_expf`` emulates it in NumPy. This kernel performs the
99
+ # same float32 operations in the same order with explicit FMAs and contraction
100
+ # disabled. Metal flushes subnormal arithmetic results to zero, so a quotient
101
+ # below the smallest normal float is formed by integer round-to-nearest-even
102
+ # division instead; its bits equal the IEEE float32 quotient.
103
+ _SLEEF_SIGMOID = """
104
+ #pragma clang fp contract(off)
105
+ uint i = thread_position_in_grid.x;
106
+ if (i >= N * C * H * W) return;
107
+ uint x = i % W;
108
+ uint y = (i / W) % H;
109
+ uint c = (i / (W * H)) % C;
110
+ uint n = i / (W * H * C);
111
+ uint source_x = flipped[n] != 0 ? W - 1 - x : x;
112
+ float d = 0.0f - logits[((n * H + y) * W + source_x) * C + c];
113
+ int q = int(metal::rint(d * 1.442695040888963407359924681001892137426645954152985934135449406931f));
114
+ float qf = float(q);
115
+ float s = metal::fma(qf, -0.693145751953125f, d);
116
+ s = metal::fma(qf, -1.428606765330187045e-06f, s);
117
+ float u = 0.000198527617612853646278381f;
118
+ u = metal::fma(u, s, 0.00139304355252534151077271f);
119
+ u = metal::fma(u, s, 0.00833336077630519866943359f);
120
+ u = metal::fma(u, s, 0.0416664853692054748535156f);
121
+ u = metal::fma(u, s, 0.166666671633720397949219f);
122
+ u = metal::fma(u, s, 0.5f);
123
+ float squared = s * s;
124
+ u = 1.0f + metal::fma(squared, u, s);
125
+ int half_q = q >> 1;
126
+ u = u * metal::ldexp(1.0f, half_q);
127
+ u = u * metal::ldexp(1.0f, q - half_q);
128
+ if (d < -104.0f) u = 0.0f;
129
+ if (100.0f < d) u = INFINITY;
130
+ float denominator = u + 1.0f;
131
+ uint bits = as_type<uint>(denominator);
132
+ if (bits >= 0x7E800000u && bits < 0x7F800000u) {
133
+ // 2**126 <= denominator < inf: the quotient is at most 2**-126. With
134
+ // denominator = m * 2**(e - 23), the result is k * 2**-149 for
135
+ // k = round(2**(172 - e) / m), and k is also the result's bit pattern.
136
+ ulong m = ulong((bits & 0x7FFFFFu) | 0x800000u);
137
+ uint e = (bits >> 23) - 127u;
138
+ ulong numerator = 1ul << (172u - e);
139
+ ulong k = numerator / m;
140
+ ulong twice_remainder = 2ul * (numerator - k * m);
141
+ if (twice_remainder > m || (twice_remainder == m && (k & 1ul) != 0ul)) k += 1ul;
142
+ out[i] = as_type<float>(uint(k));
143
+ } else {
144
+ out[i] = 1.0f / denominator;
145
+ }
146
+ """
147
+
148
+
149
+ @lru_cache(maxsize=1)
150
+ def _sigmoid_kernel(mx: MlxRuntime) -> MetalKernel:
151
+ """Compile and cache the Torch-CPU-exact sigmoid kernel."""
152
+ return mx.fast.metal_kernel(
153
+ name="flexray_torch_cpu_sigmoid",
154
+ input_names=["logits", "flipped"],
155
+ output_names=["out"],
156
+ source=_SLEEF_SIGMOID,
157
+ compile_options={"math_mode": "safe"},
158
+ )
159
+
160
+
161
+ def torch_cpu_sigmoid(logits: array, flipped: array, *, mx: MlxRuntime) -> array:
162
+ """Unflip NHWC logits and return Torch-CPU-exact sigmoid probabilities in NCHW.
163
+
164
+ Args:
165
+ logits: Float32 ``(B, H, W, C)`` logits, channels last.
166
+ flipped: ``(B,)`` int32; nonzero samples are mirrored back along ``W``.
167
+
168
+ Returns:
169
+ Float32 ``(B, C, H, W)`` probabilities whose bits equal
170
+ ``medmlx.multilabel_probabilities`` of the unflipped NCHW logits for
171
+ every non-NaN input (NaN logits give NaN).
172
+
173
+ Raises:
174
+ ValueError: Wrong ranks or batch sizes, or more than 2**31 - 1 elements.
175
+ TypeError: ``logits`` is not float32 or ``flipped`` is not int32.
176
+ """
177
+ if logits.ndim != 4 or flipped.ndim != 1 or flipped.shape[0] != logits.shape[0]:
178
+ raise ValueError("FleXray sigmoid requires NHWC logits and one flip flag per sample")
179
+ if logits.dtype != mx.float32 or flipped.dtype != mx.int32:
180
+ raise TypeError("FleXray sigmoid requires float32 logits and int32 flip flags")
181
+ n, h, w, c = logits.shape
182
+ count = n * h * w * c
183
+ if min(n, h, w, c) < 1 or count > 2**31 - 1:
184
+ raise ValueError("FleXray sigmoid requires positive dimensions within 32-bit indexing")
185
+ return _sigmoid_kernel(mx)(
186
+ inputs=[logits, flipped],
187
+ template=[("N", n), ("H", h), ("W", w), ("C", c)],
188
+ grid=(count, 1, 1),
189
+ threadgroup=(256, 1, 1),
190
+ output_shapes=[(n, c, h, w)],
191
+ output_dtypes=[mx.float32],
192
+ )[0]