lesiondiffusion-mlx 0.2.8__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.
Files changed (28) hide show
  1. lesiondiffusion_mlx-0.3.0/PKG-INFO +245 -0
  2. lesiondiffusion_mlx-0.3.0/README.md +197 -0
  3. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/pyproject.toml +4 -4
  4. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/__init__.py +8 -2
  5. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/_attention.py +19 -7
  6. lesiondiffusion_mlx-0.3.0/src/lesiondiffusion_mlx/_attention_half.py +147 -0
  7. lesiondiffusion_mlx-0.3.0/src/lesiondiffusion_mlx/_dpm.py +153 -0
  8. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/_nax_conv.py +41 -13
  9. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/_nifti.py +12 -0
  10. lesiondiffusion_mlx-0.3.0/src/lesiondiffusion_mlx/_scaled_vq.py +118 -0
  11. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/_schedules.py +16 -0
  12. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/_source_half.py +1 -0
  13. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/_spatial.py +12 -0
  14. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/_typing.py +9 -0
  15. lesiondiffusion_mlx-0.3.0/src/lesiondiffusion_mlx/_vq.py +82 -0
  16. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/medmlx.py +600 -144
  17. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/mlx_model.py +154 -38
  18. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/mlx_pipeline.py +2 -2
  19. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/mlx_sampling.py +65 -0
  20. lesiondiffusion_mlx-0.2.8/PKG-INFO +0 -190
  21. lesiondiffusion_mlx-0.2.8/README.md +0 -142
  22. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/.gitignore +0 -0
  23. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/LICENSE +0 -0
  24. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/THIRD_PARTY_NOTICES.md +0 -0
  25. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/_arrays.py +0 -0
  26. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/_reference.py +0 -0
  27. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/py.typed +0 -0
  28. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.3.0}/src/lesiondiffusion_mlx/reference.json +0 -0
@@ -0,0 +1,245 @@
1
+ Metadata-Version: 2.5
2
+ Name: lesiondiffusion-mlx
3
+ Version: 0.3.0
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.3.0/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.4,>=0.3
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.3.0/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
+ <img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/main/docs/showcase.png" alt="Liver, kidney, lung and bladder CT with the target site boxed, and a close-up of each generated lesion" width="100%">
63
+
64
+ <sub>Source CT from [KiTS23](https://kits-challenge.org/kits23/), CC BY-NC-SA 4.0, and [LUNA16](https://zenodo.org/records/3723295), CC BY 4.0.</sub>
65
+
66
+ </div>
67
+
68
+ | Input | Output |
69
+ | :--- | :--- |
70
+ | CT + aligned binary organ mask | Synthetic CT and lesion mask |
71
+
72
+ | Model | Weights download | Peak MLX memory | Measured on |
73
+ | :--- | ---: | ---: | :--- |
74
+ | `lesiondiffusion`, conditioned mode (default) | 1.7 GB | 5.19 GB | 160×160×128, 1 mm RAS crop, 200 diffusion steps |
75
+ | `lesiondiffusion`, source mode | 1.7 GB | 3.46 GB | 160×160×128, 1 mm RAS crop, 200 diffusion steps |
76
+
77
+ Requires Apple Silicon with Metal. The [technical notes](https://github.com/MedMLX/lesiondiffusion-mlx/blob/main/docs/technical.md)
78
+ give the precision of each network in these measurements.
79
+
80
+ ## Install
81
+
82
+ ```bash
83
+ uv venv --python 3.13
84
+ source .venv/bin/activate
85
+ uv pip install "lesiondiffusion-mlx>=0.3.0"
86
+ ```
87
+
88
+ ## Run
89
+
90
+ ```python
91
+ from lesiondiffusion_mlx import run
92
+
93
+ result = run(
94
+ image_path="ct_1mm_ras.nii.gz",
95
+ organ_mask_path="liver_mask.nii.gz",
96
+ output_dir="out",
97
+ organ="liver",
98
+ lesion_type="tumor",
99
+ bbox_size_mm=[30, 30, 20],
100
+ placement="inside_parenchyma",
101
+ output_region="lesion",
102
+ )
103
+ print(result["outputs"]["image"])
104
+ ```
105
+
106
+ The synthetic CT is written on the standardized RAS 1 mm grid. `output_region="lesion"`
107
+ limits changes to the neighborhood of the lesion; the default `"full"` reconstructs the
108
+ whole volume (see below).
109
+
110
+ Weights download from `MedMLX/lesiondiffusion-mlx` on first use; `medmlx setup lesiondiffusion`
111
+ downloads them ahead of time. To use your own copy, pass a folder containing
112
+ `model.safetensors` and `tokenizer.json` as `weights_path`. Conversion receipts are not
113
+ required.
114
+
115
+ ### Inputs and outputs
116
+
117
+ | Argument | Meaning |
118
+ | --- | --- |
119
+ | `image_path` | One 3D CT in NIfTI (`.nii` or `.nii.gz`), in Hounsfield units |
120
+ | `organ_mask_path` | Binary organ mask (background 0, organ 1) on the CT grid |
121
+ | `output_dir` | Directory for the outputs; created if missing |
122
+ | `organ` | A key of `lesiondiffusion_mlx.medmlx.SOURCE_ORGAN_LABELS`, such as `liver` |
123
+ | `lesion_type` | Free text such as `"tumor"` |
124
+ | `bbox_size_mm` | Lesion box extent (X, Y, Z) in mm; required unless `lesion_mask_path` is given |
125
+ | `placement` | `inside_parenchyma`, `protruding_from_parenchyma`, `within_lumen` or `wall_thickening` |
126
+ | `lesion_mask_path` | Optional lesion shape (background 0, lesion 1) to inpaint instead of generating one |
127
+ | `anatomy_mask_path` | Optional 104-label surrounding-organ map that conditions mask generation |
128
+ | `bbox_center_voxel` | Optional `[I, J, K]` box center on the standardized grid; placement is automatic otherwise |
129
+ | `diffusion_steps`, `seed` | Sampling controls; the upstream defaults are 200 and 23 |
130
+ | `lmnet_diffusion_steps`, `linet_diffusion_steps` | Optional stage overrides; each defaults to `diffusion_steps` |
131
+ | `sampler` | `"ddim"` (default) or `"dpmpp_2m"` in conditioned mode |
132
+ | `decoder_mode` | `"reference"` (default) or `"scaled_fp16"` with conditioned mode and enabled NAX |
133
+ | `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
134
+ | `output_region` | `"full"` (default), `"box"` or `"lesion"`; see below |
135
+ | `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
136
+ | `overwrite` | `False` by default; existing outputs are never replaced |
137
+
138
+ For repeated seeds or phenotype controls on one supplied lesion outline, load the
139
+ model once. Its `run` takes the same arguments without `weights_path`, the box
140
+ and the anatomy map, and returns what the one-shot call would:
141
+
142
+ ```python
143
+ from lesiondiffusion_mlx import load_model
144
+
145
+ with load_model() as model:
146
+ for seed in (1, 2, 3):
147
+ model.run(
148
+ image_path="ct.nii.gz", organ_mask_path="liver.nii.gz",
149
+ lesion_mask_path="lesion.nii.gz", output_dir=f"out/seed-{seed}",
150
+ organ="liver", lesion_type="tumor", placement="inside_parenchyma",
151
+ output_region="lesion", seed=seed,
152
+ )
153
+ ```
154
+
155
+ The model keeps the validated geometry, the encoded CT latent and, for lesion
156
+ output, the unmodified reconstruction; each draw builds fresh text conditioning and
157
+ sampler state. The CT, masks, weights, organ, inference mode, decoder mode and
158
+ output region stay fixed after the first draw.
159
+
160
+ To keep 200-step mask generation and use 50-step CT inpainting, pass
161
+ `lmnet_diffusion_steps=200, linet_diffusion_steps=50`. Changing the inpainting
162
+ step count changes the generated CT trajectory while retaining the mask for the
163
+ same seed and mask-generation settings. Results record requested and actual
164
+ step counts for each stage.
165
+
166
+ `sampler="dpmpp_2m"` uses deterministic DPM-Solver++ 2M with exactly the requested
167
+ number of denoiser calls per sampling attempt (1–999). Mask QC can request a
168
+ second attempt. It changes both sampling trajectories.
169
+ The default 200-step DDIM path remains the reference; source mode uses DDIM.
170
+
171
+ `decoder_mode="scaled_fp16"` keeps FP32 codebook selection and uses half decoder
172
+ weights and scaled half activations. Scaling prevents the known upsampling
173
+ overflow; half rounding changes decoded HU. It requires NAX on an M5-class GPU.
174
+ Native generation in this mode caps MLX's free-buffer cache at 4 GiB, respects
175
+ an existing tighter limit and restores the caller's limit afterward.
176
+ `decoder_mode="reference"` keeps conditioned decoding in FP32. Numerical results
177
+ and measurements are in [the technical notes](docs/technical.md).
178
+
179
+ [LesionControl](research/lesioncontrol/README.md) adds reference-conditioned
180
+ radiomics profiles, bounded control search and a learned context adapter. Its
181
+ research code includes real-HCC adapter training and paired-seed evaluation;
182
+ it has a separate environment under `research/lesioncontrol`.
183
+
184
+ **Phenotype text.** `shape`, `density`, `density_variation`, `enhancement`, `surface`,
185
+ `adjacent_relationship` and `specific_features` default to the upstream wording
186
+ (irregular, hypodense, heterogeneous, non-contrast CT, ill-defined margin). They
187
+ condition the generator but do not guarantee a particular HU contrast or appearance.
188
+
189
+ **Input geometry**
190
+
191
+ - The CT and masks must be finite, axis-aligned grids that match after they are
192
+ reoriented and resampled to RAS 1 mm; oblique or sheared grids are refused.
193
+ - They must fit the 64×152×152 mask crop and the 128×128×128 inpainting crop (Z, Y, X);
194
+ with `lesion_mask_path` only the inpainting crop applies.
195
+ - A supplied lesion mask must be a single connected component that overlaps the organ
196
+ mask, so split multifocal segmentations first.
197
+ - The box guides generation, but generated lesions can extend past the box or organ.
198
+
199
+ **Outputs.** `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
200
+ `organ_mask.nii.gz` (uint8) on the standardized grid. The decoder reconstructs the whole
201
+ CT, and that reconstruction does not reproduce the input exactly: away from the lesion
202
+ it shifts attenuation by several HU, by an amount that depends on the volume.
203
+ `output_region` controls how much of it reaches `synthetic_ct.nii.gz`:
204
+
205
+ | `output_region` | `synthetic_ct.nii.gz` holds |
206
+ | :--- | :--- |
207
+ | `"full"` (default) | The reconstruction, as upstream writes it, so every voxel can change |
208
+ | `"box"` | The reconstruction over the lesion box, feathered into the input over 6 mm. Tissue inside the box keeps the shift |
209
+ | `"lesion"` | Also decodes the unchanged input, and adds only the difference between the two decodes to the input CT, within 33 voxels of the lesion along each axis. The shift cancels, and voxels farther away are the input unchanged. Use it when the surrounding anatomy should keep its measured values |
210
+
211
+ `"box"` and `"lesion"` also write the full reconstruction as `raw_synthetic_ct.nii.gz`.
212
+ `run` returns `{"outputs": {...}, "artifacts": {...}, "details": {...}}`. The output
213
+ roles are `image`, `mask` and `organ_mask`, plus `raw_image` for `"box"` and `"lesion"`;
214
+ `artifacts` describes each file and `details` holds run metadata.
215
+ Invalid inputs raise `InvalidInputError`; missing
216
+ or mismatched weights raise `AssetNotReadyError`. Synthetic output is not ground truth.
217
+
218
+ ### Inference modes
219
+
220
+ | `inference_mode` | Behavior |
221
+ | :--- | :--- |
222
+ | `"conditioned"` (default) | Enables the inpainting network's trained text context, which the pinned upstream configuration turns off, and runs FP16 convolution, fused attention and compiled denoisers natively. Decodes in FP32, because the decoder's activations can exceed the FP16 range on some volumes |
223
+ | `"source"` | Follows the upstream inference configuration and arithmetic for reproduction, including FP16 decoding; when that overflows, the run raises an error instead of writing a CT. Results can differ from conditioned output |
224
+
225
+ MLX and Torch random streams differ, so a seed repeats results only within MLX.
226
+ Inference requires Apple Silicon with Metal.
227
+
228
+ ## Use with MedMLX
229
+
230
+ Use the [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) to run `lesiondiffusion` from an MCP client. Weights download on first use.
231
+
232
+ ```sh
233
+ uv tool install --python 3.13 "medmlx[generate,mcp]"
234
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
235
+ mkdir -p "$HOME/medmlx-work"
236
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
237
+ ```
238
+
239
+ 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`.
240
+
241
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
242
+
243
+ ## License
244
+
245
+ [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.3.0/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.3.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -0,0 +1,197 @@
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.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/lesiondiffusion-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/lesiondiffusion-mlx/main/docs/showcase.png" alt="Liver, kidney, lung and bladder CT with the target site boxed, and a close-up of each generated lesion" width="100%">
15
+
16
+ <sub>Source CT from [KiTS23](https://kits-challenge.org/kits23/), CC BY-NC-SA 4.0, and [LUNA16](https://zenodo.org/records/3723295), CC BY 4.0.</sub>
17
+
18
+ </div>
19
+
20
+ | Input | Output |
21
+ | :--- | :--- |
22
+ | CT + aligned binary organ mask | Synthetic CT and lesion mask |
23
+
24
+ | Model | Weights download | Peak MLX memory | Measured on |
25
+ | :--- | ---: | ---: | :--- |
26
+ | `lesiondiffusion`, conditioned mode (default) | 1.7 GB | 5.19 GB | 160×160×128, 1 mm RAS crop, 200 diffusion steps |
27
+ | `lesiondiffusion`, source mode | 1.7 GB | 3.46 GB | 160×160×128, 1 mm RAS crop, 200 diffusion steps |
28
+
29
+ Requires Apple Silicon with Metal. The [technical notes](https://github.com/MedMLX/lesiondiffusion-mlx/blob/main/docs/technical.md)
30
+ give the precision of each network in these measurements.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ uv venv --python 3.13
36
+ source .venv/bin/activate
37
+ uv pip install "lesiondiffusion-mlx>=0.3.0"
38
+ ```
39
+
40
+ ## Run
41
+
42
+ ```python
43
+ from lesiondiffusion_mlx import run
44
+
45
+ result = run(
46
+ image_path="ct_1mm_ras.nii.gz",
47
+ organ_mask_path="liver_mask.nii.gz",
48
+ output_dir="out",
49
+ organ="liver",
50
+ lesion_type="tumor",
51
+ bbox_size_mm=[30, 30, 20],
52
+ placement="inside_parenchyma",
53
+ output_region="lesion",
54
+ )
55
+ print(result["outputs"]["image"])
56
+ ```
57
+
58
+ The synthetic CT is written on the standardized RAS 1 mm grid. `output_region="lesion"`
59
+ limits changes to the neighborhood of the lesion; the default `"full"` reconstructs the
60
+ whole volume (see below).
61
+
62
+ Weights download from `MedMLX/lesiondiffusion-mlx` on first use; `medmlx setup lesiondiffusion`
63
+ downloads them ahead of time. To use your own copy, pass a folder containing
64
+ `model.safetensors` and `tokenizer.json` as `weights_path`. Conversion receipts are not
65
+ required.
66
+
67
+ ### Inputs and outputs
68
+
69
+ | Argument | Meaning |
70
+ | --- | --- |
71
+ | `image_path` | One 3D CT in NIfTI (`.nii` or `.nii.gz`), in Hounsfield units |
72
+ | `organ_mask_path` | Binary organ mask (background 0, organ 1) on the CT grid |
73
+ | `output_dir` | Directory for the outputs; created if missing |
74
+ | `organ` | A key of `lesiondiffusion_mlx.medmlx.SOURCE_ORGAN_LABELS`, such as `liver` |
75
+ | `lesion_type` | Free text such as `"tumor"` |
76
+ | `bbox_size_mm` | Lesion box extent (X, Y, Z) in mm; required unless `lesion_mask_path` is given |
77
+ | `placement` | `inside_parenchyma`, `protruding_from_parenchyma`, `within_lumen` or `wall_thickening` |
78
+ | `lesion_mask_path` | Optional lesion shape (background 0, lesion 1) to inpaint instead of generating one |
79
+ | `anatomy_mask_path` | Optional 104-label surrounding-organ map that conditions mask generation |
80
+ | `bbox_center_voxel` | Optional `[I, J, K]` box center on the standardized grid; placement is automatic otherwise |
81
+ | `diffusion_steps`, `seed` | Sampling controls; the upstream defaults are 200 and 23 |
82
+ | `lmnet_diffusion_steps`, `linet_diffusion_steps` | Optional stage overrides; each defaults to `diffusion_steps` |
83
+ | `sampler` | `"ddim"` (default) or `"dpmpp_2m"` in conditioned mode |
84
+ | `decoder_mode` | `"reference"` (default) or `"scaled_fp16"` with conditioned mode and enabled NAX |
85
+ | `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
86
+ | `output_region` | `"full"` (default), `"box"` or `"lesion"`; see below |
87
+ | `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
88
+ | `overwrite` | `False` by default; existing outputs are never replaced |
89
+
90
+ For repeated seeds or phenotype controls on one supplied lesion outline, load the
91
+ model once. Its `run` takes the same arguments without `weights_path`, the box
92
+ and the anatomy map, and returns what the one-shot call would:
93
+
94
+ ```python
95
+ from lesiondiffusion_mlx import load_model
96
+
97
+ with load_model() as model:
98
+ for seed in (1, 2, 3):
99
+ model.run(
100
+ image_path="ct.nii.gz", organ_mask_path="liver.nii.gz",
101
+ lesion_mask_path="lesion.nii.gz", output_dir=f"out/seed-{seed}",
102
+ organ="liver", lesion_type="tumor", placement="inside_parenchyma",
103
+ output_region="lesion", seed=seed,
104
+ )
105
+ ```
106
+
107
+ The model keeps the validated geometry, the encoded CT latent and, for lesion
108
+ output, the unmodified reconstruction; each draw builds fresh text conditioning and
109
+ sampler state. The CT, masks, weights, organ, inference mode, decoder mode and
110
+ output region stay fixed after the first draw.
111
+
112
+ To keep 200-step mask generation and use 50-step CT inpainting, pass
113
+ `lmnet_diffusion_steps=200, linet_diffusion_steps=50`. Changing the inpainting
114
+ step count changes the generated CT trajectory while retaining the mask for the
115
+ same seed and mask-generation settings. Results record requested and actual
116
+ step counts for each stage.
117
+
118
+ `sampler="dpmpp_2m"` uses deterministic DPM-Solver++ 2M with exactly the requested
119
+ number of denoiser calls per sampling attempt (1–999). Mask QC can request a
120
+ second attempt. It changes both sampling trajectories.
121
+ The default 200-step DDIM path remains the reference; source mode uses DDIM.
122
+
123
+ `decoder_mode="scaled_fp16"` keeps FP32 codebook selection and uses half decoder
124
+ weights and scaled half activations. Scaling prevents the known upsampling
125
+ overflow; half rounding changes decoded HU. It requires NAX on an M5-class GPU.
126
+ Native generation in this mode caps MLX's free-buffer cache at 4 GiB, respects
127
+ an existing tighter limit and restores the caller's limit afterward.
128
+ `decoder_mode="reference"` keeps conditioned decoding in FP32. Numerical results
129
+ and measurements are in [the technical notes](docs/technical.md).
130
+
131
+ [LesionControl](research/lesioncontrol/README.md) adds reference-conditioned
132
+ radiomics profiles, bounded control search and a learned context adapter. Its
133
+ research code includes real-HCC adapter training and paired-seed evaluation;
134
+ it has a separate environment under `research/lesioncontrol`.
135
+
136
+ **Phenotype text.** `shape`, `density`, `density_variation`, `enhancement`, `surface`,
137
+ `adjacent_relationship` and `specific_features` default to the upstream wording
138
+ (irregular, hypodense, heterogeneous, non-contrast CT, ill-defined margin). They
139
+ condition the generator but do not guarantee a particular HU contrast or appearance.
140
+
141
+ **Input geometry**
142
+
143
+ - The CT and masks must be finite, axis-aligned grids that match after they are
144
+ reoriented and resampled to RAS 1 mm; oblique or sheared grids are refused.
145
+ - They must fit the 64×152×152 mask crop and the 128×128×128 inpainting crop (Z, Y, X);
146
+ with `lesion_mask_path` only the inpainting crop applies.
147
+ - A supplied lesion mask must be a single connected component that overlaps the organ
148
+ mask, so split multifocal segmentations first.
149
+ - The box guides generation, but generated lesions can extend past the box or organ.
150
+
151
+ **Outputs.** `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
152
+ `organ_mask.nii.gz` (uint8) on the standardized grid. The decoder reconstructs the whole
153
+ CT, and that reconstruction does not reproduce the input exactly: away from the lesion
154
+ it shifts attenuation by several HU, by an amount that depends on the volume.
155
+ `output_region` controls how much of it reaches `synthetic_ct.nii.gz`:
156
+
157
+ | `output_region` | `synthetic_ct.nii.gz` holds |
158
+ | :--- | :--- |
159
+ | `"full"` (default) | The reconstruction, as upstream writes it, so every voxel can change |
160
+ | `"box"` | The reconstruction over the lesion box, feathered into the input over 6 mm. Tissue inside the box keeps the shift |
161
+ | `"lesion"` | Also decodes the unchanged input, and adds only the difference between the two decodes to the input CT, within 33 voxels of the lesion along each axis. The shift cancels, and voxels farther away are the input unchanged. Use it when the surrounding anatomy should keep its measured values |
162
+
163
+ `"box"` and `"lesion"` also write the full reconstruction as `raw_synthetic_ct.nii.gz`.
164
+ `run` returns `{"outputs": {...}, "artifacts": {...}, "details": {...}}`. The output
165
+ roles are `image`, `mask` and `organ_mask`, plus `raw_image` for `"box"` and `"lesion"`;
166
+ `artifacts` describes each file and `details` holds run metadata.
167
+ Invalid inputs raise `InvalidInputError`; missing
168
+ or mismatched weights raise `AssetNotReadyError`. Synthetic output is not ground truth.
169
+
170
+ ### Inference modes
171
+
172
+ | `inference_mode` | Behavior |
173
+ | :--- | :--- |
174
+ | `"conditioned"` (default) | Enables the inpainting network's trained text context, which the pinned upstream configuration turns off, and runs FP16 convolution, fused attention and compiled denoisers natively. Decodes in FP32, because the decoder's activations can exceed the FP16 range on some volumes |
175
+ | `"source"` | Follows the upstream inference configuration and arithmetic for reproduction, including FP16 decoding; when that overflows, the run raises an error instead of writing a CT. Results can differ from conditioned output |
176
+
177
+ MLX and Torch random streams differ, so a seed repeats results only within MLX.
178
+ Inference requires Apple Silicon with Metal.
179
+
180
+ ## Use with MedMLX
181
+
182
+ Use the [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) to run `lesiondiffusion` from an MCP client. Weights download on first use.
183
+
184
+ ```sh
185
+ uv tool install --python 3.13 "medmlx[generate,mcp]"
186
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
187
+ mkdir -p "$HOME/medmlx-work"
188
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
189
+ ```
190
+
191
+ 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`.
192
+
193
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
194
+
195
+ ## License
196
+
197
+ [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.3.0/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.3.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "lesiondiffusion-mlx"
7
- version = "0.2.8"
7
+ version = "0.3.0"
8
8
  description = "Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype"
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
  "nibabel>=5.3,<6",
43
43
  "numpy>=2.2,<3",
@@ -48,7 +48,7 @@ dependencies = [
48
48
 
49
49
  [project.urls]
50
50
  Homepage = "https://medmlx.org"
51
- Documentation = "https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.8/README.md"
51
+ Documentation = "https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.3.0/README.md"
52
52
  Repository = "https://github.com/MedMLX/lesiondiffusion-mlx"
53
53
  Issues = "https://github.com/MedMLX/lesiondiffusion-mlx/issues"
54
54
  Weights = "https://huggingface.co/MedMLX/lesiondiffusion-mlx"
@@ -94,7 +94,7 @@ extend-select = ["TID251", "TID252"]
94
94
  select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
95
95
 
96
96
  [tool.pyright]
97
- include = ["src", "tests", "typings"]
97
+ include = ["src", "tests", "benchmarks", "typings"]
98
98
  extraPaths = ["src"]
99
99
  pythonVersion = "3.13"
100
100
  typeCheckingMode = "strict"
@@ -9,6 +9,8 @@ if TYPE_CHECKING:
9
9
  from lesiondiffusion_mlx._schedules import (
10
10
  lesion_diffusion_timesteps as lesion_diffusion_timesteps,
11
11
  )
12
+ from lesiondiffusion_mlx.medmlx import load_model as load_model
13
+ from lesiondiffusion_mlx.medmlx import run as run
12
14
  from lesiondiffusion_mlx.mlx_model import (
13
15
  LINET_CONFIG as LINET_CONFIG,
14
16
  )
@@ -32,7 +34,7 @@ if TYPE_CHECKING:
32
34
  )
33
35
  from lesiondiffusion_mlx.mlx_sampling import DdimSampler as DdimSampler
34
36
 
35
- __version__ = "0.2.8"
37
+ __version__ = "0.3.0"
36
38
 
37
39
  __all__ = [
38
40
  "LINET_CONFIG",
@@ -44,6 +46,8 @@ __all__ = [
44
46
  "UnetConfig",
45
47
  "VqAutoencoder",
46
48
  "lesion_diffusion_timesteps",
49
+ "load_model",
50
+ "run",
47
51
  ]
48
52
 
49
53
 
@@ -52,7 +56,9 @@ def __getattr__(name: str) -> object:
52
56
  if name not in __all__:
53
57
  raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
54
58
  module = (
55
- "_schedules"
59
+ "medmlx"
60
+ if name in {"run", "load_model"}
61
+ else "_schedules"
56
62
  if name == "lesion_diffusion_timesteps"
57
63
  else "mlx_sampling"
58
64
  if name == "DdimSampler"
@@ -1,4 +1,4 @@
1
- """FP32 flash attention for 32-wide heads, kept in the projection layout.
1
+ """Flash attention for 32-wide heads, kept in the projection layout.
2
2
 
3
3
  MLX 0.32 has no fused full-attention kernel for 32-wide FP32 heads. Using its
4
4
  64-wide kernel requires zero-padding heads to 64, doing twice the arithmetic.
@@ -26,6 +26,10 @@ per FP32 product. Each simdgroup owns 16 query rows; a ``16 x 32`` score tile
26
26
  already has the register layout of ``P V``'s left operand, so probabilities
27
27
  are split in registers. It runs at about the accelerators' FP16 throughput,
28
28
  roughly 1.5x the SIMD kernel on LMNet's 23104-token layers.
29
+
30
+ FP16 self-attention uses direct NAX products with FP32 accumulation and online
31
+ softmax state, rounding probabilities and final outputs to FP16. It keeps the
32
+ same projection layout and avoids padding LINet's 32-wide heads to 64.
29
33
  """
30
34
 
31
35
  from __future__ import annotations
@@ -34,6 +38,7 @@ import math
34
38
  from functools import lru_cache
35
39
  from typing import TYPE_CHECKING, cast
36
40
 
41
+ from lesiondiffusion_mlx._attention_half import flash_attention_half
37
42
  from lesiondiffusion_mlx._nax_conv import NAX_MMA_HEADER, nax_available
38
43
  from lesiondiffusion_mlx._typing import ArrayConstructor
39
44
 
@@ -278,11 +283,15 @@ for (short i = 0; i < 2; i++) {
278
283
  def flash_eligible(q: Array, k: Array, heads: int, mx: Mlx) -> bool:
279
284
  """Whether projections ``(B, L, heads * 32)`` fit the kernel.
280
285
 
281
- Requires FP32, 32-wide heads, and query and key lengths divisible by 32.
286
+ Requires 32-wide heads and query/key lengths divisible by 32. FP32 supports
287
+ both kernels; FP16 additionally requires NAX and equal query/key lengths.
282
288
  """
283
289
  return (
284
- q.dtype == mx.float32
285
- and k.dtype == mx.float32
290
+ q.dtype == k.dtype
291
+ and (
292
+ q.dtype == mx.float32
293
+ or (q.dtype == mx.float16 and q.shape[1] == k.shape[1] and nax_available(mx))
294
+ )
286
295
  and int(q.shape[-1]) == heads * 32
287
296
  and int(k.shape[-1]) == heads * 32
288
297
  and int(q.shape[1]) % _BLOCK == 0
@@ -331,12 +340,15 @@ def flash_attention(q: Array, k: Array, v: Array, *, heads: int, scale: float, m
331
340
  mx: The imported ``mlx.core`` module.
332
341
 
333
342
  Returns:
334
- ``(B, L, heads * 32)`` FP32 attention output in the same head layout,
343
+ ``(B, L, heads * 32)`` attention output in the inputs' dtype and head layout,
335
344
  ready for the output projection. On M5-class GPUs the NAX split-FP16
336
- kernel computes it, which needs ``|q * scale * log2(e)|``, ``|k|`` and
345
+ kernel computes FP32 inputs, which needs ``|q * scale * log2(e)|``, ``|k|`` and
337
346
  ``|v|`` below 65504; these ranges are not checked. When ``nax_available``
338
- is false, the FP32 SIMD kernel computes it.
347
+ is false, the FP32 SIMD kernel computes it. Eligible FP16 self-attention
348
+ uses direct NAX products, with FP32 accumulation and online softmax.
339
349
  """
350
+ if q.dtype == mx.float16:
351
+ return flash_attention_half(q, k, v, heads=heads, scale=scale, mx=mx)
340
352
  batch, length = int(q.shape[0]), int(q.shape[1])
341
353
  if nax_available(mx):
342
354
  (qh, ql), (kh, kl), (vh, vl) = (