lesiondiffusion-mlx 0.2.8__tar.gz → 0.4.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 (30) hide show
  1. lesiondiffusion_mlx-0.4.0/PKG-INFO +265 -0
  2. lesiondiffusion_mlx-0.4.0/README.md +217 -0
  3. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/pyproject.toml +4 -4
  4. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/__init__.py +10 -2
  5. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_attention.py +31 -16
  6. lesiondiffusion_mlx-0.4.0/src/lesiondiffusion_mlx/_attention_half.py +148 -0
  7. lesiondiffusion_mlx-0.4.0/src/lesiondiffusion_mlx/_dpm.py +154 -0
  8. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_nax_conv.py +50 -20
  9. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_nifti.py +21 -1
  10. lesiondiffusion_mlx-0.4.0/src/lesiondiffusion_mlx/_scaled_vq.py +120 -0
  11. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_schedules.py +16 -0
  12. lesiondiffusion_mlx-0.4.0/src/lesiondiffusion_mlx/_slab_vq.py +305 -0
  13. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_source_half.py +12 -9
  14. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_spatial.py +17 -3
  15. lesiondiffusion_mlx-0.4.0/src/lesiondiffusion_mlx/_typing.py +29 -0
  16. lesiondiffusion_mlx-0.4.0/src/lesiondiffusion_mlx/_vq.py +84 -0
  17. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/medmlx.py +904 -202
  18. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/mlx_model.py +214 -65
  19. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/mlx_pipeline.py +9 -11
  20. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/mlx_sampling.py +71 -5
  21. lesiondiffusion_mlx-0.2.8/PKG-INFO +0 -190
  22. lesiondiffusion_mlx-0.2.8/README.md +0 -142
  23. lesiondiffusion_mlx-0.2.8/src/lesiondiffusion_mlx/_typing.py +0 -129
  24. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/.gitignore +0 -0
  25. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/LICENSE +0 -0
  26. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/THIRD_PARTY_NOTICES.md +0 -0
  27. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_arrays.py +0 -0
  28. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_reference.py +0 -0
  29. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/py.typed +0 -0
  30. {lesiondiffusion_mlx-0.2.8 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/reference.json +0 -0
@@ -0,0 +1,265 @@
1
+ Metadata-Version: 2.5
2
+ Name: lesiondiffusion-mlx
3
+ Version: 0.4.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.4.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[nifti]<0.4,>=0.3.2
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.4.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 | M5 Max, 160×160×128, 1 mm RAS crop, 200 diffusion steps |
75
+ | `lesiondiffusion`, conditioned mode (default) | 1.7 GB | 7.58 GB | M1 Max (64 GB), 160×160×128, 1 mm RAS crop, 200 diffusion steps |
76
+ | `lesiondiffusion`, source mode | 1.7 GB | 3.46 GB | M5 Max, 160×160×128, 1 mm RAS crop, 200 diffusion steps |
77
+ | `lesiondiffusion`, conditioned mode (default) | 1.7 GB | 92.4 GB | M1 Max (64 GB), 440×440×248, 1 mm RAS, 200 diffusion steps |
78
+ | `lesiondiffusion`, conditioned with `vq_mode="slab"` | 1.7 GB | 2.81 GB | M1 Max (64 GB), 440×440×248, 1 mm RAS from a 512×512×99 abdominal CT, 20 diffusion steps |
79
+
80
+ In the default mode, memory grows with the standardized 1 mm volume, because the
81
+ whole volume is encoded and decoded. For a large CT, either crop the CT and organ
82
+ mask together on the same grid, or pass `vq_mode="slab"` to reconstruct the full
83
+ volume with less MLX memory. The slab path needs temporary disk space on `TMPDIR`
84
+ or the system temp volume: allow 56 GB free for a 440×440×248 grid.
85
+
86
+ The [technical notes](https://github.com/MedMLX/lesiondiffusion-mlx/blob/main/docs/technical.md)
87
+ give the precision of each network in these measurements.
88
+
89
+ ## Install
90
+
91
+ ```bash
92
+ uv venv --python 3.13
93
+ source .venv/bin/activate
94
+ uv pip install "lesiondiffusion-mlx>=0.4.0"
95
+ ```
96
+
97
+ ## Run
98
+
99
+ ```python
100
+ from lesiondiffusion_mlx import run
101
+
102
+ result = run(
103
+ image_path="ct_1mm_ras.nii.gz",
104
+ organ_mask_path="liver_mask.nii.gz",
105
+ output_dir="out",
106
+ organ="liver",
107
+ lesion_type="tumor",
108
+ bbox_size_mm=[30, 30, 20],
109
+ placement="inside_parenchyma",
110
+ output_region="lesion",
111
+ )
112
+ print(result["outputs"]["image"])
113
+ ```
114
+
115
+ The synthetic CT is written on the standardized RAS 1 mm grid. `output_region="lesion"`
116
+ limits changes to the neighborhood of the lesion; the default `"full"` reconstructs the
117
+ whole volume (see below).
118
+
119
+ Weights download from `MedMLX/lesiondiffusion-mlx` on first use; `medmlx setup lesiondiffusion`
120
+ downloads them ahead of time. To use your own copy, pass a folder containing
121
+ `model.safetensors` and `tokenizer.json` as `weights_path`.
122
+
123
+ ### Inputs and outputs
124
+
125
+ | Argument | Meaning |
126
+ | --- | --- |
127
+ | `image_path` | One 3D CT in NIfTI (`.nii` or `.nii.gz`), in Hounsfield units |
128
+ | `organ_mask_path` | Binary organ mask (background 0, organ 1) on the CT grid |
129
+ | `output_dir` | Directory for the outputs; created if missing |
130
+ | `organ` | A key of `lesiondiffusion_mlx.medmlx.SOURCE_ORGAN_LABELS`, such as `liver` |
131
+ | `lesion_type` | Free text such as `"tumor"` |
132
+ | `bbox_size_mm` | Lesion box extent (X, Y, Z) in mm; required unless `lesion_mask_path` is given |
133
+ | `placement` | `inside_parenchyma`, `protruding_from_parenchyma`, `within_lumen` or `wall_thickening` |
134
+ | `lesion_mask_path` | Optional lesion shape (background 0, lesion 1) to inpaint instead of generating one |
135
+ | `anatomy_mask_path` | Optional 104-label surrounding-organ map that conditions mask generation |
136
+ | `bbox_center_voxel` | Optional `[I, J, K]` box center on the standardized grid; placement is automatic otherwise |
137
+ | `diffusion_steps`, `seed` | Sampling controls; the upstream defaults are 200 and 23 |
138
+ | `lmnet_diffusion_steps`, `linet_diffusion_steps` | Optional stage overrides; each defaults to `diffusion_steps` |
139
+ | `sampler` | `"ddim"` (default) or `"dpmpp_2m"` in conditioned mode |
140
+ | `decoder_mode` | `"reference"` (default) or `"scaled_fp16"` with conditioned mode and enabled NAX |
141
+ | `vq_mode` | `"whole"` (default) or `"slab"` in conditioned mode with the reference decoder. Slab mode uses temporary files for VQ activations and supports all output regions |
142
+ | `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
143
+ | `output_region` | `"full"` (default), `"box"` or `"lesion"`; see below |
144
+ | `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
145
+ | `overwrite` | `False` by default; existing outputs are never replaced |
146
+
147
+ For repeated seeds or phenotype controls on one supplied lesion outline, load the
148
+ model once. Its `run` takes the same arguments without `weights_path`, the box
149
+ and the anatomy map, and returns what the one-shot call would:
150
+
151
+ ```python
152
+ from lesiondiffusion_mlx import load_model
153
+
154
+ with load_model() as model:
155
+ for seed in (1, 2, 3):
156
+ model.run(
157
+ image_path="ct.nii.gz", organ_mask_path="liver.nii.gz",
158
+ lesion_mask_path="lesion.nii.gz", output_dir=f"out/seed-{seed}",
159
+ organ="liver", lesion_type="tumor", placement="inside_parenchyma",
160
+ output_region="lesion", seed=seed,
161
+ )
162
+ ```
163
+
164
+ The CT, masks, weights, organ, inference mode, decoder mode, VQ mode and output
165
+ region stay fixed after the first draw; each draw builds fresh text conditioning
166
+ and sampler state.
167
+
168
+ To choose among lesion shapes before inpainting, `draw_lesion_masks` samples one
169
+ mask per seed in a fixed box and writes nothing. It takes the arguments of `run`
170
+ that LMNet uses, plus required `bbox_center_voxel` and `seeds`, and returns one
171
+ boolean array per seed on the standardized grid. Each equals the `mask` output of
172
+ `run` with that seed; pass a chosen mask to `run` as `lesion_mask_path`.
173
+
174
+ ```python
175
+ from lesiondiffusion_mlx import draw_lesion_masks
176
+
177
+ masks = draw_lesion_masks(
178
+ image_path="ct.nii.gz", organ_mask_path="liver.nii.gz", organ="liver",
179
+ lesion_type="tumor", bbox_size_mm=[30, 30, 20],
180
+ bbox_center_voxel=[80, 80, 64], seeds=[1, 2, 3],
181
+ )
182
+ ```
183
+
184
+ - **Stage steps:** `lmnet_diffusion_steps=200, linet_diffusion_steps=50` keeps
185
+ 200-step mask generation and uses 50-step CT inpainting. For the same seed the
186
+ mask is unchanged and the CT differs. Results record the requested and actual
187
+ steps of each stage.
188
+ - **Sampler:** `"dpmpp_2m"` is deterministic DPM-Solver++ 2M with exactly the
189
+ requested number of denoiser calls per attempt (1–999); mask QC can request a
190
+ second attempt. It changes both sampling trajectories. Source mode uses DDIM.
191
+ - **Decoder:** `"scaled_fp16"` keeps FP32 codebook selection and runs the decoder
192
+ in scaled half precision, which prevents the upsampling overflow and changes
193
+ decoded HU by half rounding. It needs the neural accelerators of an M5 or later
194
+ GPU and caps MLX's free-buffer cache at 4 GiB during generation. `"reference"`
195
+ decodes in FP32. Measurements are in the
196
+ [technical notes](https://github.com/MedMLX/lesiondiffusion-mlx/blob/main/docs/technical.md).
197
+
198
+ [LesionControl](https://github.com/MedMLX/lesiondiffusion-mlx/blob/main/research/lesioncontrol/README.md),
199
+ in `research/lesioncontrol` with its own environment, adds reference-conditioned
200
+ radiomics profiles, bounded control search and a learned context adapter.
201
+
202
+ **Phenotype text.** `shape`, `density`, `density_variation`, `enhancement`, `surface`,
203
+ `adjacent_relationship` and `specific_features` default to the upstream wording
204
+ (irregular, hypodense, heterogeneous, non-contrast CT, ill-defined margin). They
205
+ condition the generator but do not guarantee a particular HU contrast or appearance.
206
+
207
+ **Input geometry**
208
+
209
+ - The CT and masks must be finite, axis-aligned grids that match after they are
210
+ reoriented and resampled to RAS 1 mm; oblique or sheared grids are refused.
211
+ - They must fit the 64×152×152 mask crop and the 128×128×128 inpainting crop (Z, Y, X);
212
+ with `lesion_mask_path` only the inpainting crop applies.
213
+ - A supplied lesion mask must be a single connected component that overlaps the organ
214
+ mask, so split multifocal segmentations first.
215
+ - Mask files must be 3D real-valued NIfTI-1 or NIfTI-2 files. Spatial units of meter
216
+ or micron are converted to millimeters; any other unit code, a 2D, complex or
217
+ boolean mask, or another file format raises `InvalidInputError`.
218
+ - The box guides generation, but generated lesions can extend past the box or organ.
219
+
220
+ **Outputs.** `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
221
+ `organ_mask.nii.gz` (uint8) on the standardized grid. The decoder reconstructs the whole
222
+ CT, and that reconstruction does not reproduce the input exactly: away from the lesion
223
+ it shifts attenuation by several HU, by an amount that depends on the volume.
224
+ `output_region` controls how much of it reaches `synthetic_ct.nii.gz`:
225
+
226
+ | `output_region` | `synthetic_ct.nii.gz` holds |
227
+ | :--- | :--- |
228
+ | `"full"` (default) | The reconstruction, as upstream writes it, so every voxel can change |
229
+ | `"box"` | The reconstruction over the lesion box, feathered into the input over 6 mm. Tissue inside the box keeps the shift |
230
+ | `"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 |
231
+
232
+ `"box"` and `"lesion"` also write the full reconstruction as `raw_synthetic_ct.nii.gz`.
233
+ `run` returns `{"outputs": {...}, "artifacts": {...}, "details": {...}}`. The output
234
+ roles are `image`, `mask` and `organ_mask`, plus `raw_image` for `"box"` and `"lesion"`;
235
+ `artifacts` describes each file and `details` holds run metadata.
236
+ Invalid inputs raise `InvalidInputError`; missing
237
+ or mismatched weights raise `AssetNotReadyError`.
238
+
239
+ ### Inference modes
240
+
241
+ | `inference_mode` | Behavior |
242
+ | :--- | :--- |
243
+ | `"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 |
244
+ | `"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 |
245
+
246
+ MLX and Torch random streams differ, so a seed repeats results only within MLX.
247
+
248
+ ## Use with MedMLX
249
+
250
+ 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.
251
+
252
+ ```sh
253
+ uv tool install --python 3.13 "medmlx[generate,mcp]"
254
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
255
+ mkdir -p "$HOME/medmlx-work"
256
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
257
+ ```
258
+
259
+ 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`.
260
+
261
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
262
+
263
+ ## License
264
+
265
+ [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.4.0/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.4.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -0,0 +1,217 @@
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.4.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 | M5 Max, 160×160×128, 1 mm RAS crop, 200 diffusion steps |
27
+ | `lesiondiffusion`, conditioned mode (default) | 1.7 GB | 7.58 GB | M1 Max (64 GB), 160×160×128, 1 mm RAS crop, 200 diffusion steps |
28
+ | `lesiondiffusion`, source mode | 1.7 GB | 3.46 GB | M5 Max, 160×160×128, 1 mm RAS crop, 200 diffusion steps |
29
+ | `lesiondiffusion`, conditioned mode (default) | 1.7 GB | 92.4 GB | M1 Max (64 GB), 440×440×248, 1 mm RAS, 200 diffusion steps |
30
+ | `lesiondiffusion`, conditioned with `vq_mode="slab"` | 1.7 GB | 2.81 GB | M1 Max (64 GB), 440×440×248, 1 mm RAS from a 512×512×99 abdominal CT, 20 diffusion steps |
31
+
32
+ In the default mode, memory grows with the standardized 1 mm volume, because the
33
+ whole volume is encoded and decoded. For a large CT, either crop the CT and organ
34
+ mask together on the same grid, or pass `vq_mode="slab"` to reconstruct the full
35
+ volume with less MLX memory. The slab path needs temporary disk space on `TMPDIR`
36
+ or the system temp volume: allow 56 GB free for a 440×440×248 grid.
37
+
38
+ The [technical notes](https://github.com/MedMLX/lesiondiffusion-mlx/blob/main/docs/technical.md)
39
+ give the precision of each network in these measurements.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ uv venv --python 3.13
45
+ source .venv/bin/activate
46
+ uv pip install "lesiondiffusion-mlx>=0.4.0"
47
+ ```
48
+
49
+ ## Run
50
+
51
+ ```python
52
+ from lesiondiffusion_mlx import run
53
+
54
+ result = run(
55
+ image_path="ct_1mm_ras.nii.gz",
56
+ organ_mask_path="liver_mask.nii.gz",
57
+ output_dir="out",
58
+ organ="liver",
59
+ lesion_type="tumor",
60
+ bbox_size_mm=[30, 30, 20],
61
+ placement="inside_parenchyma",
62
+ output_region="lesion",
63
+ )
64
+ print(result["outputs"]["image"])
65
+ ```
66
+
67
+ The synthetic CT is written on the standardized RAS 1 mm grid. `output_region="lesion"`
68
+ limits changes to the neighborhood of the lesion; the default `"full"` reconstructs the
69
+ whole volume (see below).
70
+
71
+ Weights download from `MedMLX/lesiondiffusion-mlx` on first use; `medmlx setup lesiondiffusion`
72
+ downloads them ahead of time. To use your own copy, pass a folder containing
73
+ `model.safetensors` and `tokenizer.json` as `weights_path`.
74
+
75
+ ### Inputs and outputs
76
+
77
+ | Argument | Meaning |
78
+ | --- | --- |
79
+ | `image_path` | One 3D CT in NIfTI (`.nii` or `.nii.gz`), in Hounsfield units |
80
+ | `organ_mask_path` | Binary organ mask (background 0, organ 1) on the CT grid |
81
+ | `output_dir` | Directory for the outputs; created if missing |
82
+ | `organ` | A key of `lesiondiffusion_mlx.medmlx.SOURCE_ORGAN_LABELS`, such as `liver` |
83
+ | `lesion_type` | Free text such as `"tumor"` |
84
+ | `bbox_size_mm` | Lesion box extent (X, Y, Z) in mm; required unless `lesion_mask_path` is given |
85
+ | `placement` | `inside_parenchyma`, `protruding_from_parenchyma`, `within_lumen` or `wall_thickening` |
86
+ | `lesion_mask_path` | Optional lesion shape (background 0, lesion 1) to inpaint instead of generating one |
87
+ | `anatomy_mask_path` | Optional 104-label surrounding-organ map that conditions mask generation |
88
+ | `bbox_center_voxel` | Optional `[I, J, K]` box center on the standardized grid; placement is automatic otherwise |
89
+ | `diffusion_steps`, `seed` | Sampling controls; the upstream defaults are 200 and 23 |
90
+ | `lmnet_diffusion_steps`, `linet_diffusion_steps` | Optional stage overrides; each defaults to `diffusion_steps` |
91
+ | `sampler` | `"ddim"` (default) or `"dpmpp_2m"` in conditioned mode |
92
+ | `decoder_mode` | `"reference"` (default) or `"scaled_fp16"` with conditioned mode and enabled NAX |
93
+ | `vq_mode` | `"whole"` (default) or `"slab"` in conditioned mode with the reference decoder. Slab mode uses temporary files for VQ activations and supports all output regions |
94
+ | `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
95
+ | `output_region` | `"full"` (default), `"box"` or `"lesion"`; see below |
96
+ | `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
97
+ | `overwrite` | `False` by default; existing outputs are never replaced |
98
+
99
+ For repeated seeds or phenotype controls on one supplied lesion outline, load the
100
+ model once. Its `run` takes the same arguments without `weights_path`, the box
101
+ and the anatomy map, and returns what the one-shot call would:
102
+
103
+ ```python
104
+ from lesiondiffusion_mlx import load_model
105
+
106
+ with load_model() as model:
107
+ for seed in (1, 2, 3):
108
+ model.run(
109
+ image_path="ct.nii.gz", organ_mask_path="liver.nii.gz",
110
+ lesion_mask_path="lesion.nii.gz", output_dir=f"out/seed-{seed}",
111
+ organ="liver", lesion_type="tumor", placement="inside_parenchyma",
112
+ output_region="lesion", seed=seed,
113
+ )
114
+ ```
115
+
116
+ The CT, masks, weights, organ, inference mode, decoder mode, VQ mode and output
117
+ region stay fixed after the first draw; each draw builds fresh text conditioning
118
+ and sampler state.
119
+
120
+ To choose among lesion shapes before inpainting, `draw_lesion_masks` samples one
121
+ mask per seed in a fixed box and writes nothing. It takes the arguments of `run`
122
+ that LMNet uses, plus required `bbox_center_voxel` and `seeds`, and returns one
123
+ boolean array per seed on the standardized grid. Each equals the `mask` output of
124
+ `run` with that seed; pass a chosen mask to `run` as `lesion_mask_path`.
125
+
126
+ ```python
127
+ from lesiondiffusion_mlx import draw_lesion_masks
128
+
129
+ masks = draw_lesion_masks(
130
+ image_path="ct.nii.gz", organ_mask_path="liver.nii.gz", organ="liver",
131
+ lesion_type="tumor", bbox_size_mm=[30, 30, 20],
132
+ bbox_center_voxel=[80, 80, 64], seeds=[1, 2, 3],
133
+ )
134
+ ```
135
+
136
+ - **Stage steps:** `lmnet_diffusion_steps=200, linet_diffusion_steps=50` keeps
137
+ 200-step mask generation and uses 50-step CT inpainting. For the same seed the
138
+ mask is unchanged and the CT differs. Results record the requested and actual
139
+ steps of each stage.
140
+ - **Sampler:** `"dpmpp_2m"` is deterministic DPM-Solver++ 2M with exactly the
141
+ requested number of denoiser calls per attempt (1–999); mask QC can request a
142
+ second attempt. It changes both sampling trajectories. Source mode uses DDIM.
143
+ - **Decoder:** `"scaled_fp16"` keeps FP32 codebook selection and runs the decoder
144
+ in scaled half precision, which prevents the upsampling overflow and changes
145
+ decoded HU by half rounding. It needs the neural accelerators of an M5 or later
146
+ GPU and caps MLX's free-buffer cache at 4 GiB during generation. `"reference"`
147
+ decodes in FP32. Measurements are in the
148
+ [technical notes](https://github.com/MedMLX/lesiondiffusion-mlx/blob/main/docs/technical.md).
149
+
150
+ [LesionControl](https://github.com/MedMLX/lesiondiffusion-mlx/blob/main/research/lesioncontrol/README.md),
151
+ in `research/lesioncontrol` with its own environment, adds reference-conditioned
152
+ radiomics profiles, bounded control search and a learned context adapter.
153
+
154
+ **Phenotype text.** `shape`, `density`, `density_variation`, `enhancement`, `surface`,
155
+ `adjacent_relationship` and `specific_features` default to the upstream wording
156
+ (irregular, hypodense, heterogeneous, non-contrast CT, ill-defined margin). They
157
+ condition the generator but do not guarantee a particular HU contrast or appearance.
158
+
159
+ **Input geometry**
160
+
161
+ - The CT and masks must be finite, axis-aligned grids that match after they are
162
+ reoriented and resampled to RAS 1 mm; oblique or sheared grids are refused.
163
+ - They must fit the 64×152×152 mask crop and the 128×128×128 inpainting crop (Z, Y, X);
164
+ with `lesion_mask_path` only the inpainting crop applies.
165
+ - A supplied lesion mask must be a single connected component that overlaps the organ
166
+ mask, so split multifocal segmentations first.
167
+ - Mask files must be 3D real-valued NIfTI-1 or NIfTI-2 files. Spatial units of meter
168
+ or micron are converted to millimeters; any other unit code, a 2D, complex or
169
+ boolean mask, or another file format raises `InvalidInputError`.
170
+ - The box guides generation, but generated lesions can extend past the box or organ.
171
+
172
+ **Outputs.** `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
173
+ `organ_mask.nii.gz` (uint8) on the standardized grid. The decoder reconstructs the whole
174
+ CT, and that reconstruction does not reproduce the input exactly: away from the lesion
175
+ it shifts attenuation by several HU, by an amount that depends on the volume.
176
+ `output_region` controls how much of it reaches `synthetic_ct.nii.gz`:
177
+
178
+ | `output_region` | `synthetic_ct.nii.gz` holds |
179
+ | :--- | :--- |
180
+ | `"full"` (default) | The reconstruction, as upstream writes it, so every voxel can change |
181
+ | `"box"` | The reconstruction over the lesion box, feathered into the input over 6 mm. Tissue inside the box keeps the shift |
182
+ | `"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 |
183
+
184
+ `"box"` and `"lesion"` also write the full reconstruction as `raw_synthetic_ct.nii.gz`.
185
+ `run` returns `{"outputs": {...}, "artifacts": {...}, "details": {...}}`. The output
186
+ roles are `image`, `mask` and `organ_mask`, plus `raw_image` for `"box"` and `"lesion"`;
187
+ `artifacts` describes each file and `details` holds run metadata.
188
+ Invalid inputs raise `InvalidInputError`; missing
189
+ or mismatched weights raise `AssetNotReadyError`.
190
+
191
+ ### Inference modes
192
+
193
+ | `inference_mode` | Behavior |
194
+ | :--- | :--- |
195
+ | `"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 |
196
+ | `"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 |
197
+
198
+ MLX and Torch random streams differ, so a seed repeats results only within MLX.
199
+
200
+ ## Use with MedMLX
201
+
202
+ 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.
203
+
204
+ ```sh
205
+ uv tool install --python 3.13 "medmlx[generate,mcp]"
206
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
207
+ mkdir -p "$HOME/medmlx-work"
208
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
209
+ ```
210
+
211
+ 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`.
212
+
213
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
214
+
215
+ ## License
216
+
217
+ [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.4.0/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.4.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.4.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[nifti]>=0.3.2,<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.4.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,9 @@ 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 draw_lesion_masks as draw_lesion_masks
13
+ from lesiondiffusion_mlx.medmlx import load_model as load_model
14
+ from lesiondiffusion_mlx.medmlx import run as run
12
15
  from lesiondiffusion_mlx.mlx_model import (
13
16
  LINET_CONFIG as LINET_CONFIG,
14
17
  )
@@ -32,7 +35,7 @@ if TYPE_CHECKING:
32
35
  )
33
36
  from lesiondiffusion_mlx.mlx_sampling import DdimSampler as DdimSampler
34
37
 
35
- __version__ = "0.2.8"
38
+ __version__ = "0.4.0"
36
39
 
37
40
  __all__ = [
38
41
  "LINET_CONFIG",
@@ -43,7 +46,10 @@ __all__ = [
43
46
  "SourceLayers",
44
47
  "UnetConfig",
45
48
  "VqAutoencoder",
49
+ "draw_lesion_masks",
46
50
  "lesion_diffusion_timesteps",
51
+ "load_model",
52
+ "run",
47
53
  ]
48
54
 
49
55
 
@@ -52,7 +58,9 @@ def __getattr__(name: str) -> object:
52
58
  if name not in __all__:
53
59
  raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
54
60
  module = (
55
- "_schedules"
61
+ "medmlx"
62
+ if name in {"run", "load_model", "draw_lesion_masks"}
63
+ else "_schedules"
56
64
  if name == "lesion_diffusion_timesteps"
57
65
  else "mlx_sampling"
58
66
  if name == "DdimSampler"