lesiondiffusion-mlx 0.2.4__tar.gz → 0.2.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. lesiondiffusion_mlx-0.2.6/.gitignore +38 -0
  2. lesiondiffusion_mlx-0.2.6/PKG-INFO +183 -0
  3. lesiondiffusion_mlx-0.2.6/README.md +135 -0
  4. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/THIRD_PARTY_NOTICES.md +5 -3
  5. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/pyproject.toml +41 -12
  6. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/__init__.py +1 -1
  7. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/_typing.py +4 -71
  8. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/medmlx.py +3 -1
  9. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/mlx_model.py +5 -5
  10. lesiondiffusion_mlx-0.2.4/.gitignore +0 -26
  11. lesiondiffusion_mlx-0.2.4/PKG-INFO +0 -78
  12. lesiondiffusion_mlx-0.2.4/README.md +0 -46
  13. lesiondiffusion_mlx-0.2.4/src/lesiondiffusion_mlx/_group_norm.py +0 -218
  14. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/LICENSE +0 -0
  15. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/_arrays.py +0 -0
  16. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/_attention.py +0 -0
  17. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/_nax_conv.py +0 -0
  18. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/_nifti.py +0 -0
  19. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/_reference.py +0 -0
  20. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/_schedules.py +0 -0
  21. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/_source_half.py +0 -0
  22. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/_spatial.py +0 -0
  23. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/mlx_pipeline.py +0 -0
  24. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/mlx_sampling.py +0 -0
  25. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/py.typed +0 -0
  26. {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.6}/src/lesiondiffusion_mlx/reference.json +0 -0
@@ -0,0 +1,38 @@
1
+ # MedMLX standard
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .venv
6
+ build/
7
+ dist/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .mypy_cache/
11
+ .hypothesis/
12
+ .coverage
13
+ htmlcov/
14
+ .DS_Store
15
+ # Never commit secrets (Hugging Face tokens)
16
+ .env
17
+ # Never commit data or weights
18
+ /data/
19
+ /work/
20
+ /weights/
21
+ /models/
22
+ /checkpoints/
23
+ /outputs/
24
+ *.nii
25
+ *.nii.gz
26
+ *.dcm
27
+ *.nrrd
28
+ *.mha
29
+ *.mhd
30
+ *.safetensors
31
+ *.pt
32
+ *.pth
33
+ *.ckpt
34
+ *.bin
35
+ *.h5
36
+ *.npy
37
+ *.npz
38
+ !tests/fixtures/**/*.npz
@@ -0,0 +1,183 @@
1
+ Metadata-Version: 2.5
2
+ Name: lesiondiffusion-mlx
3
+ Version: 0.2.6
4
+ Summary: Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype
5
+ Project-URL: Homepage, https://medmlx.org
6
+ Project-URL: Documentation, https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/README.md
7
+ Project-URL: Repository, https://github.com/MedMLX/lesiondiffusion-mlx
8
+ Project-URL: Issues, https://github.com/MedMLX/lesiondiffusion-mlx/issues
9
+ Project-URL: Weights, https://huggingface.co/MedMLX/lesiondiffusion-mlx
10
+ Project-URL: MedMLX, https://github.com/MedMLX/medmlx
11
+ Author: Joseph Sandoval, Alfredo Sandoval Jr.
12
+ License-Expression: Apache-2.0 AND MIT AND BSD-3-Clause
13
+ License-File: LICENSE
14
+ License-File: THIRD_PARTY_NOTICES.md
15
+ Keywords: apple-silicon,ct,diffusion,image-synthesis,lesion,medical-imaging,metal,mlx
16
+ Classifier: Development Status :: 4 - Beta
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Intended Audience :: Science/Research
19
+ Classifier: Operating System :: MacOS :: MacOS X
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
25
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
26
+ Requires-Python: <3.14,>=3.13
27
+ Requires-Dist: medmlx-core==0.2.6
28
+ Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
29
+ Requires-Dist: nibabel<6,>=5.3
30
+ Requires-Dist: numpy<3,>=2.2
31
+ Requires-Dist: safetensors<1,>=0.6
32
+ Requires-Dist: scipy<2,>=1.15
33
+ Requires-Dist: tokenizers<1,>=0.21
34
+ Provides-Extra: dev
35
+ Requires-Dist: einops<0.9,>=0.8.1; extra == 'dev'
36
+ Requires-Dist: hypothesis<7,>=6.100; extra == 'dev'
37
+ Requires-Dist: pillow<14,>=13; extra == 'dev'
38
+ Requires-Dist: pyright==1.1.414; extra == 'dev'
39
+ Requires-Dist: pytest<10,>=8.4; extra == 'dev'
40
+ Requires-Dist: ruff<1,>=0.13; extra == 'dev'
41
+ Requires-Dist: scipy-stubs<1.19,>=1.18.1.1; extra == 'dev'
42
+ Requires-Dist: torch<2.14,>=2.13; extra == 'dev'
43
+ Provides-Extra: reference
44
+ Requires-Dist: einops==0.8.2; extra == 'reference'
45
+ Requires-Dist: omegaconf==2.3.1; extra == 'reference'
46
+ Requires-Dist: transformers==5.19.0; extra == 'reference'
47
+ Description-Content-Type: text/markdown
48
+
49
+ <div align="center">
50
+
51
+ # lesiondiffusion-mlx
52
+
53
+ Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype.
54
+
55
+ [![PyPI](https://img.shields.io/pypi/v/lesiondiffusion-mlx)](https://pypi.org/project/lesiondiffusion-mlx/)
56
+ [![Python](https://img.shields.io/pypi/pyversions/lesiondiffusion-mlx)](https://pypi.org/project/lesiondiffusion-mlx/)
57
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/LICENSE)
58
+ [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
59
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
60
+ [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
61
+
62
+ [Model weights](https://huggingface.co/MedMLX/lesiondiffusion-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
63
+
64
+ <img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.6/docs/showcase.png" alt="CT with a synthetic lesion placed inside an organ mask" width="100%">
65
+
66
+ </div>
67
+
68
+ | | |
69
+ | :--- | :--- |
70
+ | **Input** | CT + aligned binary organ mask |
71
+ | **Output** | Synthetic CT and lesion mask |
72
+ | **Hardware** | Apple Silicon with Metal; **18.74 GB** peak MLX memory for `lesiondiffusion` in source mode on a 160×160×128, 1 mm RAS crop. |
73
+
74
+ The [v0.2.5 measurement](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/docs/technical.md#upstream-decisions-and-qualification)
75
+ used the AMOS case 0008 crop and 200 diffusion steps with
76
+ `inference_mode="source"`: FP32 LMNet and text encoder, FP16 LINet and VQ.
77
+ It does not measure the default conditioned mode or larger volumes. Peak MLX
78
+ memory excludes host preprocessing and other applications.
79
+
80
+ ## Use with MedMLX
81
+
82
+ 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 `lesiondiffusion` for you.
83
+
84
+ ```sh
85
+ uv tool install --python 3.13 "medmlx[generate,mcp]"
86
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
87
+ mkdir -p "$HOME/medmlx-work"
88
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
89
+ ```
90
+
91
+ 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 lesiondiffusion`.
92
+
93
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
94
+
95
+ ## Install
96
+
97
+ ```bash
98
+ uv venv --python 3.13
99
+ source .venv/bin/activate
100
+ uv pip install "lesiondiffusion-mlx>=0.2.6"
101
+ ```
102
+
103
+ ## Run
104
+
105
+ ```python
106
+ from lesiondiffusion_mlx.medmlx import run
107
+
108
+ result = run(
109
+ image_path="ct_1mm_ras.nii.gz",
110
+ organ_mask_path="liver_mask.nii.gz",
111
+ output_dir="out",
112
+ organ="liver",
113
+ lesion_type="tumor",
114
+ bbox_size_mm=[30, 30, 20],
115
+ placement="inside_parenchyma",
116
+ )
117
+ print(result["outputs"]["synthetic_image"])
118
+ ```
119
+
120
+ Omitting `weights_path` downloads `MedMLX/lesiondiffusion-mlx` into the shared MedMLX
121
+ cache on first use; interrupted downloads resume and later runs work offline. With
122
+ MedMLX installed, `medmlx setup lesiondiffusion` downloads it ahead of time. To use your
123
+ own copy, pass a folder containing `model.safetensors` and `tokenizer.json` as
124
+ `weights_path`. Conversion receipts are not required. `details.weights_revision` records
125
+ the downloaded commit, or `null` for a folder without a MedMLX download record.
126
+
127
+ ### Inputs and outputs
128
+
129
+ | Argument | Meaning |
130
+ | --- | --- |
131
+ | `image_path` | One 3D CT in NIfTI (`.nii` or `.nii.gz`), in Hounsfield units |
132
+ | `organ_mask_path` | Binary organ mask (background 0, organ 1) on the CT grid |
133
+ | `output_dir` | Directory for the outputs; created if missing |
134
+ | `organ` | A key of `lesiondiffusion_mlx.medmlx.SOURCE_ORGAN_LABELS`, such as `liver` |
135
+ | `lesion_type` | Free text such as `"tumor"` |
136
+ | `bbox_size_mm` | Lesion box extent (X, Y, Z) in mm; required unless `lesion_mask_path` is given |
137
+ | `placement` | `inside_parenchyma`, `protruding_from_parenchyma`, `within_lumen` or `wall_thickening` |
138
+ | `lesion_mask_path` | Optional lesion shape (background 0, lesion 1) to inpaint instead of generating one |
139
+ | `anatomy_mask_path` | Optional 104-label surrounding-organ map that conditions mask generation |
140
+ | `bbox_center_voxel` | Optional `[I, J, K]` box center on the standardized grid; placement is automatic otherwise |
141
+ | `diffusion_steps`, `seed` | Sampling controls; the upstream defaults are 200 and 23 |
142
+ | `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
143
+ | `output_region` | `"full"` (default) or `"box"` |
144
+ | `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
145
+ | `overwrite` | `False` by default; existing outputs are never replaced |
146
+
147
+ The phenotype text arguments `shape`, `density`, `density_variation`, `enhancement`,
148
+ `surface`, `adjacent_relationship` and `specific_features` default to the upstream
149
+ wording (irregular, hypodense, heterogeneous, non-contrast CT, ill-defined margin).
150
+ They condition the generator but do not guarantee a particular HU contrast or
151
+ appearance.
152
+
153
+ The CT and masks must be finite, axis-aligned grids that match after they are
154
+ reoriented and resampled to RAS 1 mm; oblique or sheared grids are refused. They must
155
+ fit the 64×152×152 mask crop and the 128×128×128 inpainting crop (Z, Y, X); with
156
+ `lesion_mask_path` only the inpainting crop applies. A supplied lesion mask must be a
157
+ single connected component that overlaps the organ mask, so split multifocal
158
+ segmentations first. The box guides generation, but generated lesions can extend past
159
+ the box or organ.
160
+
161
+ The outputs are `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
162
+ `organ_mask.nii.gz` (uint8) on the standardized grid. The decoder reconstructs the
163
+ whole CT, so voxels outside the lesion can change. `output_region="box"` keeps the
164
+ generated CT only over the lesion box, feathers it into the input over 6 mm and also
165
+ writes the full reconstruction as `raw_synthetic_ct.nii.gz`. `run` returns
166
+ `{"outputs": {...}, "details": {...}}` with the generation settings, quality checks,
167
+ stage timing and weights revision. Invalid inputs raise `InvalidInputError`; missing
168
+ or mismatched weights raise `AssetNotReadyError`. Synthetic output is not ground truth.
169
+
170
+ ### Inference modes
171
+
172
+ `"conditioned"`, the default, enables the inpainting network's trained text context,
173
+ which the pinned upstream configuration turns off, and runs FP16 convolution, fused
174
+ attention and compiled denoisers natively. `"source"` follows the upstream inference
175
+ configuration and arithmetic for reproduction; its results can differ from
176
+ conditioned output. MLX and Torch random streams differ, so a seed repeats results
177
+ only within MLX. Inference needs Apple Silicon with Metal and has no CPU fallback.
178
+
179
+ ## License
180
+
181
+ [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
182
+
183
+ For research and education. Outputs require human review.
@@ -0,0 +1,135 @@
1
+ <div align="center">
2
+
3
+ # lesiondiffusion-mlx
4
+
5
+ Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype.
6
+
7
+ [![PyPI](https://img.shields.io/pypi/v/lesiondiffusion-mlx)](https://pypi.org/project/lesiondiffusion-mlx/)
8
+ [![Python](https://img.shields.io/pypi/pyversions/lesiondiffusion-mlx)](https://pypi.org/project/lesiondiffusion-mlx/)
9
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/LICENSE)
10
+ [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
11
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
12
+ [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
13
+
14
+ [Model weights](https://huggingface.co/MedMLX/lesiondiffusion-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
15
+
16
+ <img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.6/docs/showcase.png" alt="CT with a synthetic lesion placed inside an organ mask" width="100%">
17
+
18
+ </div>
19
+
20
+ | | |
21
+ | :--- | :--- |
22
+ | **Input** | CT + aligned binary organ mask |
23
+ | **Output** | Synthetic CT and lesion mask |
24
+ | **Hardware** | Apple Silicon with Metal; **18.74 GB** peak MLX memory for `lesiondiffusion` in source mode on a 160×160×128, 1 mm RAS crop. |
25
+
26
+ The [v0.2.5 measurement](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/docs/technical.md#upstream-decisions-and-qualification)
27
+ used the AMOS case 0008 crop and 200 diffusion steps with
28
+ `inference_mode="source"`: FP32 LMNet and text encoder, FP16 LINet and VQ.
29
+ It does not measure the default conditioned mode or larger volumes. Peak MLX
30
+ memory excludes host preprocessing and other applications.
31
+
32
+ ## Use with MedMLX
33
+
34
+ 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 `lesiondiffusion` for you.
35
+
36
+ ```sh
37
+ uv tool install --python 3.13 "medmlx[generate,mcp]"
38
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
39
+ mkdir -p "$HOME/medmlx-work"
40
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
41
+ ```
42
+
43
+ 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 lesiondiffusion`.
44
+
45
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
46
+
47
+ ## Install
48
+
49
+ ```bash
50
+ uv venv --python 3.13
51
+ source .venv/bin/activate
52
+ uv pip install "lesiondiffusion-mlx>=0.2.6"
53
+ ```
54
+
55
+ ## Run
56
+
57
+ ```python
58
+ from lesiondiffusion_mlx.medmlx import run
59
+
60
+ result = run(
61
+ image_path="ct_1mm_ras.nii.gz",
62
+ organ_mask_path="liver_mask.nii.gz",
63
+ output_dir="out",
64
+ organ="liver",
65
+ lesion_type="tumor",
66
+ bbox_size_mm=[30, 30, 20],
67
+ placement="inside_parenchyma",
68
+ )
69
+ print(result["outputs"]["synthetic_image"])
70
+ ```
71
+
72
+ Omitting `weights_path` downloads `MedMLX/lesiondiffusion-mlx` into the shared MedMLX
73
+ cache on first use; interrupted downloads resume and later runs work offline. With
74
+ MedMLX installed, `medmlx setup lesiondiffusion` downloads it ahead of time. To use your
75
+ own copy, pass a folder containing `model.safetensors` and `tokenizer.json` as
76
+ `weights_path`. Conversion receipts are not required. `details.weights_revision` records
77
+ the downloaded commit, or `null` for a folder without a MedMLX download record.
78
+
79
+ ### Inputs and outputs
80
+
81
+ | Argument | Meaning |
82
+ | --- | --- |
83
+ | `image_path` | One 3D CT in NIfTI (`.nii` or `.nii.gz`), in Hounsfield units |
84
+ | `organ_mask_path` | Binary organ mask (background 0, organ 1) on the CT grid |
85
+ | `output_dir` | Directory for the outputs; created if missing |
86
+ | `organ` | A key of `lesiondiffusion_mlx.medmlx.SOURCE_ORGAN_LABELS`, such as `liver` |
87
+ | `lesion_type` | Free text such as `"tumor"` |
88
+ | `bbox_size_mm` | Lesion box extent (X, Y, Z) in mm; required unless `lesion_mask_path` is given |
89
+ | `placement` | `inside_parenchyma`, `protruding_from_parenchyma`, `within_lumen` or `wall_thickening` |
90
+ | `lesion_mask_path` | Optional lesion shape (background 0, lesion 1) to inpaint instead of generating one |
91
+ | `anatomy_mask_path` | Optional 104-label surrounding-organ map that conditions mask generation |
92
+ | `bbox_center_voxel` | Optional `[I, J, K]` box center on the standardized grid; placement is automatic otherwise |
93
+ | `diffusion_steps`, `seed` | Sampling controls; the upstream defaults are 200 and 23 |
94
+ | `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
95
+ | `output_region` | `"full"` (default) or `"box"` |
96
+ | `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
97
+ | `overwrite` | `False` by default; existing outputs are never replaced |
98
+
99
+ The phenotype text arguments `shape`, `density`, `density_variation`, `enhancement`,
100
+ `surface`, `adjacent_relationship` and `specific_features` default to the upstream
101
+ wording (irregular, hypodense, heterogeneous, non-contrast CT, ill-defined margin).
102
+ They condition the generator but do not guarantee a particular HU contrast or
103
+ appearance.
104
+
105
+ The CT and masks must be finite, axis-aligned grids that match after they are
106
+ reoriented and resampled to RAS 1 mm; oblique or sheared grids are refused. They must
107
+ fit the 64×152×152 mask crop and the 128×128×128 inpainting crop (Z, Y, X); with
108
+ `lesion_mask_path` only the inpainting crop applies. A supplied lesion mask must be a
109
+ single connected component that overlaps the organ mask, so split multifocal
110
+ segmentations first. The box guides generation, but generated lesions can extend past
111
+ the box or organ.
112
+
113
+ The outputs are `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
114
+ `organ_mask.nii.gz` (uint8) on the standardized grid. The decoder reconstructs the
115
+ whole CT, so voxels outside the lesion can change. `output_region="box"` keeps the
116
+ generated CT only over the lesion box, feathers it into the input over 6 mm and also
117
+ writes the full reconstruction as `raw_synthetic_ct.nii.gz`. `run` returns
118
+ `{"outputs": {...}, "details": {...}}` with the generation settings, quality checks,
119
+ stage timing and weights revision. Invalid inputs raise `InvalidInputError`; missing
120
+ or mismatched weights raise `AssetNotReadyError`. Synthetic output is not ground truth.
121
+
122
+ ### Inference modes
123
+
124
+ `"conditioned"`, the default, enables the inpainting network's trained text context,
125
+ which the pinned upstream configuration turns off, and runs FP16 convolution, fused
126
+ attention and compiled denoisers natively. `"source"` follows the upstream inference
127
+ configuration and arithmetic for reproduction; its results can differ from
128
+ conditioned output. MLX and Torch random streams differ, so a seed repeats results
129
+ only within MLX. Inference needs Apple Silicon with Metal and has no CPU fallback.
130
+
131
+ ## License
132
+
133
+ [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
134
+
135
+ For research and education. Outputs require human review.
@@ -142,6 +142,8 @@ POSSIBILITY OF SUCH DAMAGE.
142
142
 
143
143
  ## Showcase image
144
144
 
145
- The CT images are from [AMOS22](https://doi.org/10.5281/zenodo.7262581),
146
- Ji, Yuanfeng et al., licensed [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
147
- The showcase uses cropped views with model-derived overlays or maps.
145
+ The showcase uses cropped CT views from [AMOS22](https://doi.org/10.5281/zenodo.7262581)
146
+ by Yuanfeng Ji et al., with model-derived overlays or maps. The Zenodo record lists
147
+ CC BY 4.0, while the dataset archive's metadata lists CC BY-SA 4.0. The showcase
148
+ is shared under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)
149
+ pending clarification; the repository's Apache-2.0 license does not relicense it.
@@ -4,16 +4,41 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "lesiondiffusion-mlx"
7
- version = "0.2.4"
8
- description = "Native MLX implementation of LesionDiffusion"
7
+ version = "0.2.6"
8
+ description = "Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype"
9
9
  readme = "README.md"
10
- requires-python = ">=3.13,<3.15"
11
- classifiers = ["Operating System :: MacOS :: MacOS X"]
10
+ requires-python = ">=3.13,<3.14"
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Intended Audience :: Science/Research",
15
+ "Operating System :: MacOS :: MacOS X",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Topic :: Scientific/Engineering :: Image Processing",
21
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
22
+ ]
23
+ keywords = [
24
+ "mlx",
25
+ "apple-silicon",
26
+ "metal",
27
+ "medical-imaging",
28
+ "ct",
29
+ "lesion",
30
+ "diffusion",
31
+ "image-synthesis",
32
+ ]
12
33
  license = "Apache-2.0 AND MIT AND BSD-3-Clause"
13
34
  license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]
14
- authors = [{ name = "Joseph Sandoval" }, { name = "Alfredo Sandoval Jr." }]
35
+ authors = [
36
+ { name = "Joseph Sandoval" },
37
+ { name = "Alfredo Sandoval Jr." },
38
+ ]
15
39
  dependencies = [
16
- "medmlx-core==0.2.5",
40
+ "medmlx-core==0.2.6",
41
+ "mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'",
17
42
  "nibabel>=5.3,<6",
18
43
  "numpy>=2.2,<3",
19
44
  "safetensors>=0.6,<1",
@@ -22,7 +47,12 @@ dependencies = [
22
47
  ]
23
48
 
24
49
  [project.urls]
25
- Homepage = "https://huggingface.co/MedMLX/lesiondiffusion-mlx"
50
+ Homepage = "https://medmlx.org"
51
+ Documentation = "https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.6/README.md"
52
+ Repository = "https://github.com/MedMLX/lesiondiffusion-mlx"
53
+ Issues = "https://github.com/MedMLX/lesiondiffusion-mlx/issues"
54
+ Weights = "https://huggingface.co/MedMLX/lesiondiffusion-mlx"
55
+ MedMLX = "https://github.com/MedMLX/medmlx"
26
56
 
27
57
  [project.entry-points."medmlx.models"]
28
58
  lesiondiffusion = "lesiondiffusion_mlx.medmlx:MODEL"
@@ -53,20 +83,21 @@ addopts = "--strict-config --strict-markers"
53
83
  [tool.uv]
54
84
  constraint-dependencies = ["setuptools>=84.1.0", "filelock>=4.2.1", "certifi>=2026.10.19"]
55
85
  environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
86
+ required-environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
56
87
 
57
88
  [tool.ruff]
58
89
  line-length = 100
59
90
  target-version = "py313"
60
91
 
61
92
  [tool.ruff.lint]
62
- extend-select = ["TID251", "TID252", "ANN401"]
93
+ extend-select = ["TID251", "TID252"]
63
94
  select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
64
95
 
65
96
  [tool.pyright]
66
97
  include = ["scripts","src","tests","typings"]
67
- extraPaths = ["src"]
98
+ extraPaths = ["src", "scripts"]
68
99
  pythonVersion = "3.13"
69
- typeCheckingMode = "strict"
100
+ typeCheckingMode = "standard"
70
101
  enableTypeIgnoreComments = false
71
102
  reportUnnecessaryTypeIgnoreComment = "error"
72
103
 
@@ -74,8 +105,6 @@ reportUnnecessaryTypeIgnoreComment = "error"
74
105
  ban-relative-imports = "all"
75
106
 
76
107
  [tool.ruff.lint.flake8-tidy-imports.banned-api]
77
- "typing.Any" = {msg = "Use a precise type and parse untyped values at the boundary."}
78
- "typing_extensions.Any" = {msg = "Use a precise type and parse untyped values at the boundary."}
79
108
 
80
109
  [tool.hatch.build.targets.sdist]
81
110
  only-include = [
@@ -32,7 +32,7 @@ if TYPE_CHECKING:
32
32
  )
33
33
  from lesiondiffusion_mlx.mlx_sampling import DdimSampler as DdimSampler
34
34
 
35
- __version__ = "0.2.4"
35
+ __version__ = "0.2.6"
36
36
 
37
37
  __all__ = [
38
38
  "LINET_CONFIG",
@@ -2,18 +2,17 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING, Literal, Protocol
5
+ from typing import TYPE_CHECKING, Any, Protocol
6
6
 
7
7
  from tokenizers import Encoding
8
8
 
9
9
  from lesiondiffusion_mlx._arrays import HostArray as HostArray
10
10
 
11
11
  if TYPE_CHECKING:
12
- from collections.abc import Callable, Sequence
12
+ from collections.abc import Sequence
13
13
 
14
14
  import mlx.core as mx
15
15
  from medmlx_core.typing import FastRuntime as CoreFastRuntime
16
- from medmlx_core.typing import MlxRuntime
17
16
 
18
17
  type Array = mx.array
19
18
  type Dtype = mx.Dtype
@@ -91,72 +90,7 @@ if TYPE_CHECKING:
91
90
  """Draw normally distributed native values."""
92
91
  ...
93
92
 
94
- class Mlx(MlxRuntime, Protocol):
95
- """The MLX module surface consumed by this port, without importing it eagerly."""
96
-
97
- @property
98
- def fast(self) -> Fast:
99
- """Return the native fast operations boundary."""
100
- ...
101
-
102
- random: Random
103
-
104
- def addmm(self, c: Array, a: Array, b: Array, /) -> Array:
105
- """Multiply matrices and add the supplied bias."""
106
- ...
107
- def all(self, a: Array, /) -> Array:
108
- """Reduce a native array with logical all."""
109
- ...
110
- def argmin(self, a: Array, /, *, axis: int | None = None) -> Array:
111
- """Return indices of minimum values along an axis."""
112
- ...
113
- def clear_cache(self) -> None:
114
- """Clear the native allocator cache."""
115
- ...
116
- def compile[**P, R](self, fun: Callable[P, R], /) -> Callable[P, R]:
117
- """Compile a callable for native execution."""
118
- ...
119
- def contiguous(self, a: Array, /) -> Array:
120
- """Return a contiguous native array."""
121
- ...
122
- def cos(self, a: Array, /) -> Array:
123
- """Compute elementwise cosine."""
124
- ...
125
- def device_info(self) -> dict[str, str | int]:
126
- """Return native device capability information."""
127
- ...
128
- def erf(self, a: Array, /) -> Array:
129
- """Compute the elementwise error function."""
130
- ...
131
- def exp(self, a: Array, /) -> Array:
132
- """Compute the elementwise exponential."""
133
- ...
134
- def full(self, shape: Sequence[int], vals: object, *, dtype: Dtype) -> Array:
135
- """Create a native array filled with the supplied value."""
136
- ...
137
- def isfinite(self, a: Array, /) -> Array:
138
- """Test native values for finiteness."""
139
- ...
140
- def load(self, file: str, *, format: Literal["safetensors"]) -> dict[str, Array]:
141
- """Load named arrays from a safetensors file."""
142
- ...
143
- def reciprocal(self, a: Array, /) -> Array:
144
- """Compute elementwise reciprocals."""
145
- ...
146
- def sin(self, a: Array, /) -> Array:
147
- """Compute elementwise sine."""
148
- ...
149
- def softmax(
150
- self, a: Array, /, *, axis: int | None = None, precise: bool = False
151
- ) -> Array:
152
- """Normalize scores along the requested axis."""
153
- ...
154
- def sqrt(self, a: Array | float, /) -> Array:
155
- """Compute elementwise square roots."""
156
- ...
157
- def sum(self, a: Array, /, *, axis: int | None = None, keepdims: bool = False) -> Array:
158
- """Sum native values over an optional axis."""
159
- ...
93
+ Mlx = Any
160
94
  else:
161
95
 
162
96
  class ArrayConstructor(Protocol):
@@ -174,5 +108,4 @@ else:
174
108
  class Random(Protocol):
175
109
  pass
176
110
 
177
- class Mlx(Protocol):
178
- pass
111
+ Mlx = Any
@@ -102,7 +102,7 @@ _RAW_SYNTHETIC_CT = "raw_synthetic_ct.nii.gz"
102
102
  _LESION_MASK = "lesion_mask.nii.gz"
103
103
  _ORGAN_MASK = "organ_mask.nii.gz"
104
104
 
105
- MODEL: Final[dict[str, str]] = {
105
+ MODEL: Final[dict[str, str | float]] = {
106
106
  "id": MODEL_ID,
107
107
  "label": "LesionDiffusion CT lesion insertion",
108
108
  "task": "generation",
@@ -111,6 +111,8 @@ MODEL: Final[dict[str, str]] = {
111
111
  "Insert one phenotype-controlled synthetic lesion into a CT, given a binary organ "
112
112
  "mask, or inpaint a supplied binary lesion mask. Outputs use a RAS 1 mm grid."
113
113
  ),
114
+ # README: source mode, 200 steps, 160x160x128 RAS 1 mm AMOS case 0008 crop.
115
+ "peak_memory_gb": 18.74,
114
116
  }
115
117
 
116
118
 
@@ -16,6 +16,11 @@ from typing import TYPE_CHECKING, cast
16
16
  if TYPE_CHECKING:
17
17
  from lesiondiffusion_mlx._typing import Array, Mlx
18
18
 
19
+ from medmlx_core.group_norm import (
20
+ group_norm_affine,
21
+ native_group_norm,
22
+ native_group_norm_eligible,
23
+ )
19
24
  from medmlx_core.ops import (
20
25
  conv3d_ncdhw,
21
26
  group_norm_ncdhw,
@@ -24,11 +29,6 @@ from medmlx_core.ops import (
24
29
  )
25
30
 
26
31
  from lesiondiffusion_mlx._attention import flash_attention, flash_eligible
27
- from lesiondiffusion_mlx._group_norm import (
28
- group_norm_affine,
29
- native_group_norm,
30
- native_group_norm_eligible,
31
- )
32
32
  from lesiondiffusion_mlx._nax_conv import (
33
33
  nax_available,
34
34
  nax_conv3d,
@@ -1,26 +0,0 @@
1
- __pycache__/
2
- *.py[cod]
3
- .venv/
4
- *.egg-info/
5
- dist/
6
- build/
7
- .pytest_cache/
8
- .ruff_cache/
9
-
10
- # Checkpoints and converted weights are never committed.
11
- checkpoints/
12
- weights/
13
- *.safetensors
14
- *.npz
15
- !tests/fixtures/*.npz
16
- !tests/fixtures/*/*.npz
17
- *.pt
18
- *.pth
19
- *.ckpt
20
-
21
- # Imaging data is never committed.
22
- data/
23
- *.nii
24
- *.nii.gz
25
- *.dcm
26
- .DS_Store
@@ -1,78 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: lesiondiffusion-mlx
3
- Version: 0.2.4
4
- Summary: Native MLX implementation of LesionDiffusion
5
- Project-URL: Homepage, https://huggingface.co/MedMLX/lesiondiffusion-mlx
6
- Author: Joseph Sandoval, Alfredo Sandoval Jr.
7
- License-Expression: Apache-2.0 AND MIT AND BSD-3-Clause
8
- License-File: LICENSE
9
- License-File: THIRD_PARTY_NOTICES.md
10
- Classifier: Operating System :: MacOS :: MacOS X
11
- Requires-Python: <3.15,>=3.13
12
- Requires-Dist: medmlx-core==0.2.5
13
- Requires-Dist: nibabel<6,>=5.3
14
- Requires-Dist: numpy<3,>=2.2
15
- Requires-Dist: safetensors<1,>=0.6
16
- Requires-Dist: scipy<2,>=1.15
17
- Requires-Dist: tokenizers<1,>=0.21
18
- Provides-Extra: dev
19
- Requires-Dist: einops<0.9,>=0.8.1; extra == 'dev'
20
- Requires-Dist: hypothesis<7,>=6.100; extra == 'dev'
21
- Requires-Dist: pillow<14,>=13; extra == 'dev'
22
- Requires-Dist: pyright==1.1.414; extra == 'dev'
23
- Requires-Dist: pytest<10,>=8.4; extra == 'dev'
24
- Requires-Dist: ruff<1,>=0.13; extra == 'dev'
25
- Requires-Dist: scipy-stubs<1.19,>=1.18.1.1; extra == 'dev'
26
- Requires-Dist: torch<2.14,>=2.13; extra == 'dev'
27
- Provides-Extra: reference
28
- Requires-Dist: einops==0.8.2; extra == 'reference'
29
- Requires-Dist: omegaconf==2.3.1; extra == 'reference'
30
- Requires-Dist: transformers==5.19.0; extra == 'reference'
31
- Description-Content-Type: text/markdown
32
-
33
- # lesiondiffusion-mlx
34
-
35
- Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype.
36
-
37
- [Model weights](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
38
-
39
- | Input | Output |
40
- | :--- | :--- |
41
- | CT + aligned binary organ mask | Synthetic CT and lesion mask |
42
-
43
- **Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
44
-
45
- ## Quick start
46
-
47
- ```bash
48
- uv venv --python 3.13
49
- source .venv/bin/activate
50
- uv pip install "lesiondiffusion-mlx>=0.2.4"
51
- ```
52
-
53
- ```python
54
- from lesiondiffusion_mlx.medmlx import run
55
-
56
- result = run(
57
- image_path="ct_1mm_ras.nii.gz",
58
- organ_mask_path="liver_mask.nii.gz",
59
- output_dir="out",
60
- organ="liver",
61
- lesion_type="tumor",
62
- bbox_size_mm=[30, 30, 20],
63
- placement="inside_parenchyma",
64
- )
65
- print(result["outputs"]["synthetic_image"])
66
- ```
67
-
68
- Weights download from `MedMLX/lesiondiffusion-mlx` on first use. A local native
69
- folder can also be passed as `weights_path`; it needs `model.safetensors` and
70
- `tokenizer.json`. Conversion receipts are not required.
71
-
72
- Version 0.2.3 accepts `lesion_mask_path` instead of `bbox_size_mm` to inpaint a supplied lesion shape. Inputs must support the documented crop sizes. Outputs use a RAS 1 mm grid; voxels outside the lesion can change. Synthetic output is not ground truth.
73
-
74
- ## License
75
-
76
- Apache-2.0; license and third-party notices are included in the distribution. Model weights retain their publisher terms.
77
-
78
- For research and education. Outputs require human review.
@@ -1,46 +0,0 @@
1
- # lesiondiffusion-mlx
2
-
3
- Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype.
4
-
5
- [Model weights](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
6
-
7
- | Input | Output |
8
- | :--- | :--- |
9
- | CT + aligned binary organ mask | Synthetic CT and lesion mask |
10
-
11
- **Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
12
-
13
- ## Quick start
14
-
15
- ```bash
16
- uv venv --python 3.13
17
- source .venv/bin/activate
18
- uv pip install "lesiondiffusion-mlx>=0.2.4"
19
- ```
20
-
21
- ```python
22
- from lesiondiffusion_mlx.medmlx import run
23
-
24
- result = run(
25
- image_path="ct_1mm_ras.nii.gz",
26
- organ_mask_path="liver_mask.nii.gz",
27
- output_dir="out",
28
- organ="liver",
29
- lesion_type="tumor",
30
- bbox_size_mm=[30, 30, 20],
31
- placement="inside_parenchyma",
32
- )
33
- print(result["outputs"]["synthetic_image"])
34
- ```
35
-
36
- Weights download from `MedMLX/lesiondiffusion-mlx` on first use. A local native
37
- folder can also be passed as `weights_path`; it needs `model.safetensors` and
38
- `tokenizer.json`. Conversion receipts are not required.
39
-
40
- Version 0.2.3 accepts `lesion_mask_path` instead of `bbox_size_mm` to inpaint a supplied lesion shape. Inputs must support the documented crop sizes. Outputs use a RAS 1 mm grid; voxels outside the lesion can change. Synthetic output is not ground truth.
41
-
42
- ## License
43
-
44
- Apache-2.0; license and third-party notices are included in the distribution. Model weights retain their publisher terms.
45
-
46
- For research and education. Outputs require human review.
@@ -1,218 +0,0 @@
1
- """Native NCDHW group normalization with an optional fused SiLU.
2
-
3
- Conditioned mode does not need the source-ordered Welford cascade in
4
- ``_source_half``. In NCDHW each ``(batch, group)`` is one contiguous run of
5
- ``C / G * D * H * W`` values, so statistics take three Metal dispatches:
6
-
7
- 1. Every threadgroup sums a ``CHUNK``-value slice of one group, shifted by the
8
- group's first value, accumulating the sum and sum of squares in FP32.
9
- 2. One thread per group converts each chunk to a mean and M2, merges chunks
10
- with Chan's parallel update, and writes each channel's FP32 scale and offset.
11
- 3. A vectorized pass applies ``scale * x + offset`` and, optionally,
12
- ``y / (1 + exp(-y))``, rounding once to the input dtype.
13
-
14
- Shifting by a sample of the group keeps the per-chunk sums well conditioned;
15
- the chunk merge avoids the global ``E[x^2] - E[x]^2`` cancellation. Results
16
- match FP32 statistics to FP32 rounding. For FP16 inputs the single rounding
17
- after SiLU differs from normalizing, rounding to FP16 and then applying SiLU.
18
- """
19
-
20
- from __future__ import annotations
21
-
22
- import math
23
- from functools import lru_cache
24
- from typing import TYPE_CHECKING, cast
25
-
26
- from lesiondiffusion_mlx._typing import ArrayConstructor
27
-
28
- if TYPE_CHECKING:
29
- from lesiondiffusion_mlx._typing import Array, MetalKernel, Mlx
30
-
31
- _CHUNK = 16384
32
- _THREADS = 256
33
-
34
- _PARTIAL = r"""
35
- const uint chunk = threadgroup_position_in_grid.x, bg = threadgroup_position_in_grid.y;
36
- const uint tid = thread_position_in_threadgroup.x;
37
- const ulong base = ulong(bg) * SIZE;
38
- const float shift = float(x[base]);
39
- const uint start = chunk * CHUNK, stop = min(start + CHUNK, uint(SIZE));
40
- float s = 0.0f, ss = 0.0f;
41
- for (uint i = start + tid * 4; i < stop; i += TG * 4) {
42
- const float4 v = float4(*reinterpret_cast<const device vec<T, 4>*>(x + base + i)) - shift;
43
- s += v.x + v.y + v.z + v.w;
44
- ss = fma(v.x, v.x, fma(v.y, v.y, fma(v.z, v.z, fma(v.w, v.w, ss))));
45
- }
46
- threadgroup float reduced[2][TG / 32];
47
- s = simd_sum(s);
48
- ss = simd_sum(ss);
49
- if (thread_index_in_simdgroup == 0) {
50
- reduced[0][simdgroup_index_in_threadgroup] = s;
51
- reduced[1][simdgroup_index_in_threadgroup] = ss;
52
- }
53
- threadgroup_barrier(mem_flags::mem_threadgroup);
54
- if (tid == 0) {
55
- float a = 0.0f, b = 0.0f;
56
- for (uint i = 0; i < TG / 32; i++) { a += reduced[0][i]; b += reduced[1][i]; }
57
- partials[(bg * CHUNKS + chunk) * 2] = a;
58
- partials[(bg * CHUNKS + chunk) * 2 + 1] = b;
59
- }
60
- """
61
-
62
- _AFFINE = r"""
63
- const uint bg = thread_position_in_grid.x;
64
- if (bg >= B * G) return;
65
- float count = 0.0f, mean = 0.0f, m2 = 0.0f;
66
- for (uint c = 0; c < CHUNKS; c++) {
67
- const float n = float(min(uint(CHUNK), uint(SIZE) - c * CHUNK));
68
- const float s = partials[(bg * CHUNKS + c) * 2], ss = partials[(bg * CHUNKS + c) * 2 + 1];
69
- const float chunk_mean = s / n;
70
- const float total = count + n;
71
- const float delta = chunk_mean - mean;
72
- mean += delta * (n / total);
73
- m2 += max(ss - s * chunk_mean, 0.0f) + delta * delta * (count * n / total);
74
- count = total;
75
- }
76
- mean += float(x[ulong(bg) * SIZE]);
77
- const float rstd = metal::precise::rsqrt(m2 / count + epsilon[0]);
78
- const uint g = bg % G, b = bg / G;
79
- for (uint j = 0; j < C / G; j++) {
80
- const uint c = g * (C / G) + j;
81
- const float scale = rstd * float(weight[c]);
82
- affine[(b * C + c) * 2] = scale;
83
- affine[(b * C + c) * 2 + 1] = float(bias[c]) - mean * scale;
84
- }
85
- """
86
-
87
- _APPLY = r"""
88
- const uint vector = thread_position_in_grid.x;
89
- const uint bc = thread_position_in_grid.y;
90
- if (vector * 4 >= SPATIAL) return;
91
- const ulong index = ulong(bc) * SPATIAL + vector * 4;
92
- const float scale = affine[bc * 2], offset = affine[bc * 2 + 1];
93
- float4 y = float4(*reinterpret_cast<const device vec<T, 4>*>(x + index)) * scale + offset;
94
- if (SILU) y = y / (1.0f + metal::precise::exp(-y));
95
- *reinterpret_cast<device vec<T, 4>*>(out + index) = vec<T, 4>(y);
96
- """
97
-
98
-
99
- @lru_cache(maxsize=1)
100
- def _kernels(mx: Mlx) -> tuple[MetalKernel, MetalKernel, MetalKernel]:
101
- """Build or reuse the native group-normalization Metal kernels."""
102
- return (
103
- mx.fast.metal_kernel(
104
- name="lesion_group_norm_partial",
105
- input_names=["x"],
106
- output_names=["partials"],
107
- source=_PARTIAL,
108
- ),
109
- mx.fast.metal_kernel(
110
- name="lesion_group_norm_affine",
111
- input_names=["x", "partials", "weight", "bias", "epsilon"],
112
- output_names=["affine"],
113
- source=_AFFINE,
114
- ),
115
- mx.fast.metal_kernel(
116
- name="lesion_group_norm_apply",
117
- input_names=["x", "affine"],
118
- output_names=["out"],
119
- source=_APPLY,
120
- ),
121
- )
122
-
123
-
124
- def native_group_norm_eligible(x: Array, groups: int) -> bool:
125
- """Whether NCDHW ``x`` fits the vectorized kernels: rank 5, ``groups | C``, ``4 | DHW``."""
126
- return (
127
- x.ndim == 5
128
- and int(x.shape[1]) % groups == 0
129
- and math.prod(int(size) for size in x.shape[2:]) % 4 == 0
130
- )
131
-
132
-
133
- def group_norm_affine(
134
- x: Array, weight: Array, bias: Array, *, groups: int, eps: float, mx: Mlx
135
- ) -> Array:
136
- """Fold NCDHW group statistics and the affine into per-channel FP32 pairs.
137
-
138
- Args:
139
- x: Contiguous ``(B, C, D, H, W)`` float16 or float32 input satisfying
140
- ``native_group_norm_eligible``.
141
- weight: Per-channel scale ``(C,)``.
142
- bias: Per-channel shift ``(C,)``.
143
- groups: Number of groups dividing ``C``.
144
- eps: Variance epsilon.
145
- mx: The imported ``mlx.core`` module.
146
-
147
- Returns:
148
- FP32 ``(B * C * 2)`` array; entries ``2 i`` and ``2 i + 1`` are the
149
- scale and offset that normalize channel ``i = b * C + c`` as
150
- ``x * scale + offset``.
151
- """
152
- batch, channels = int(x.shape[0]), int(x.shape[1])
153
- spatial = math.prod(int(size) for size in x.shape[2:])
154
- size = channels // groups * spatial
155
- chunks = -(-size // _CHUNK)
156
- partial_kernel, affine_kernel, _ = _kernels(mx)
157
- partials = partial_kernel(
158
- inputs=[x],
159
- template=[
160
- ("T", x.dtype),
161
- ("SIZE", size),
162
- ("CHUNK", _CHUNK),
163
- ("CHUNKS", chunks),
164
- ("TG", _THREADS),
165
- ],
166
- grid=(_THREADS * chunks, batch * groups, 1),
167
- threadgroup=(_THREADS, 1, 1),
168
- output_shapes=[(batch * groups * chunks * 2,)],
169
- output_dtypes=[mx.float32],
170
- )[0]
171
- epsilon = cast(ArrayConstructor, mx.array)([eps], dtype=mx.float32)
172
- return affine_kernel(
173
- inputs=[x, partials, weight, bias, epsilon],
174
- template=[
175
- ("B", batch),
176
- ("G", groups),
177
- ("C", channels),
178
- ("SIZE", size),
179
- ("CHUNK", _CHUNK),
180
- ("CHUNKS", chunks),
181
- ],
182
- grid=(batch * groups, 1, 1),
183
- threadgroup=(min(32, batch * groups), 1, 1),
184
- output_shapes=[(batch * channels * 2,)],
185
- output_dtypes=[mx.float32],
186
- )[0]
187
-
188
-
189
- def native_group_norm(
190
- x: Array, weight: Array, bias: Array, *, groups: int, eps: float, silu: bool, mx: Mlx
191
- ) -> Array:
192
- """Group-normalize NCDHW ``x`` with per-channel affine, then optionally SiLU.
193
-
194
- Args:
195
- x: ``(B, C, D, H, W)`` float16 or float32 input satisfying
196
- ``native_group_norm_eligible``.
197
- weight: Per-channel scale ``(C,)``.
198
- bias: Per-channel shift ``(C,)``.
199
- groups: Number of groups dividing ``C``.
200
- eps: Variance epsilon.
201
- silu: Apply SiLU to the FP32 normalized value before rounding.
202
- mx: The imported ``mlx.core`` module.
203
-
204
- Returns:
205
- Contiguous array with ``x``'s shape and dtype.
206
- """
207
- # Every kernel reads x; one shared contiguous copy avoids three.
208
- x = mx.contiguous(x)
209
- affine = group_norm_affine(x, weight, bias, groups=groups, eps=eps, mx=mx)
210
- spatial = math.prod(int(size) for size in x.shape[2:])
211
- return _kernels(mx)[2](
212
- inputs=[x, affine],
213
- template=[("T", x.dtype), ("SPATIAL", spatial), ("SILU", silu)],
214
- grid=(spatial // 4, int(x.shape[0]) * int(x.shape[1]), 1),
215
- threadgroup=(_THREADS, 1, 1),
216
- output_shapes=[tuple(x.shape)],
217
- output_dtypes=[x.dtype],
218
- )[0]