lesiondiffusion-mlx 0.3.0__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.
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/PKG-INFO +62 -42
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/README.md +59 -39
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/pyproject.toml +3 -3
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/__init__.py +4 -2
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_attention.py +12 -9
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_attention_half.py +7 -6
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_dpm.py +8 -7
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_nax_conv.py +10 -8
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_nifti.py +9 -1
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_scaled_vq.py +4 -2
- lesiondiffusion_mlx-0.4.0/src/lesiondiffusion_mlx/_slab_vq.py +305 -0
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_source_half.py +11 -9
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_spatial.py +6 -4
- lesiondiffusion_mlx-0.4.0/src/lesiondiffusion_mlx/_typing.py +29 -0
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_vq.py +5 -3
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/medmlx.py +328 -82
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/mlx_model.py +62 -29
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/mlx_pipeline.py +7 -9
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/mlx_sampling.py +6 -5
- lesiondiffusion_mlx-0.3.0/src/lesiondiffusion_mlx/_typing.py +0 -138
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/.gitignore +0 -0
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/LICENSE +0 -0
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/THIRD_PARTY_NOTICES.md +0 -0
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_arrays.py +0 -0
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_reference.py +0 -0
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_schedules.py +0 -0
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/py.typed +0 -0
- {lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/reference.json +0 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: lesiondiffusion-mlx
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype
|
|
5
5
|
Project-URL: Homepage, https://medmlx.org
|
|
6
|
-
Project-URL: Documentation, https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.
|
|
6
|
+
Project-URL: Documentation, https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.4.0/README.md
|
|
7
7
|
Project-URL: Repository, https://github.com/MedMLX/lesiondiffusion-mlx
|
|
8
8
|
Project-URL: Issues, https://github.com/MedMLX/lesiondiffusion-mlx/issues
|
|
9
9
|
Project-URL: Weights, https://huggingface.co/MedMLX/lesiondiffusion-mlx
|
|
@@ -24,7 +24,7 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
|
24
24
|
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
25
25
|
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
26
26
|
Requires-Python: <3.14,>=3.13
|
|
27
|
-
Requires-Dist: medmlx-core<0.4,>=0.3
|
|
27
|
+
Requires-Dist: medmlx-core[nifti]<0.4,>=0.3.2
|
|
28
28
|
Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
|
|
29
29
|
Requires-Dist: nibabel<6,>=5.3
|
|
30
30
|
Requires-Dist: numpy<3,>=2.2
|
|
@@ -54,7 +54,7 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
|
|
|
54
54
|
|
|
55
55
|
[](https://pypi.org/project/lesiondiffusion-mlx/)
|
|
56
56
|
[](https://pypi.org/project/lesiondiffusion-mlx/)
|
|
57
|
-
[](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.
|
|
57
|
+
[](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.4.0/LICENSE)
|
|
58
58
|
[](https://github.com/ml-explore/mlx)
|
|
59
59
|
[](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
|
|
60
60
|
[](https://github.com/MedMLX/medmlx)
|
|
@@ -71,10 +71,19 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
|
|
|
71
71
|
|
|
72
72
|
| Model | Weights download | Peak MLX memory | Measured on |
|
|
73
73
|
| :--- | ---: | ---: | :--- |
|
|
74
|
-
| `lesiondiffusion`, conditioned mode (default) | 1.7 GB | 5.19 GB | 160×160×128, 1 mm RAS crop, 200 diffusion steps |
|
|
75
|
-
| `lesiondiffusion`,
|
|
76
|
-
|
|
77
|
-
|
|
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)
|
|
78
87
|
give the precision of each network in these measurements.
|
|
79
88
|
|
|
80
89
|
## Install
|
|
@@ -82,7 +91,7 @@ give the precision of each network in these measurements.
|
|
|
82
91
|
```bash
|
|
83
92
|
uv venv --python 3.13
|
|
84
93
|
source .venv/bin/activate
|
|
85
|
-
uv pip install "lesiondiffusion-mlx>=0.
|
|
94
|
+
uv pip install "lesiondiffusion-mlx>=0.4.0"
|
|
86
95
|
```
|
|
87
96
|
|
|
88
97
|
## Run
|
|
@@ -109,8 +118,7 @@ whole volume (see below).
|
|
|
109
118
|
|
|
110
119
|
Weights download from `MedMLX/lesiondiffusion-mlx` on first use; `medmlx setup lesiondiffusion`
|
|
111
120
|
downloads them ahead of time. To use your own copy, pass a folder containing
|
|
112
|
-
`model.safetensors` and `tokenizer.json` as `weights_path`.
|
|
113
|
-
required.
|
|
121
|
+
`model.safetensors` and `tokenizer.json` as `weights_path`.
|
|
114
122
|
|
|
115
123
|
### Inputs and outputs
|
|
116
124
|
|
|
@@ -130,6 +138,7 @@ required.
|
|
|
130
138
|
| `lmnet_diffusion_steps`, `linet_diffusion_steps` | Optional stage overrides; each defaults to `diffusion_steps` |
|
|
131
139
|
| `sampler` | `"ddim"` (default) or `"dpmpp_2m"` in conditioned mode |
|
|
132
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 |
|
|
133
142
|
| `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
|
|
134
143
|
| `output_region` | `"full"` (default), `"box"` or `"lesion"`; see below |
|
|
135
144
|
| `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
|
|
@@ -152,34 +161,43 @@ with load_model() as model:
|
|
|
152
161
|
)
|
|
153
162
|
```
|
|
154
163
|
|
|
155
|
-
The
|
|
156
|
-
|
|
157
|
-
sampler state.
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
and
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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.
|
|
183
201
|
|
|
184
202
|
**Phenotype text.** `shape`, `density`, `density_variation`, `enhancement`, `surface`,
|
|
185
203
|
`adjacent_relationship` and `specific_features` default to the upstream wording
|
|
@@ -194,6 +212,9 @@ condition the generator but do not guarantee a particular HU contrast or appeara
|
|
|
194
212
|
with `lesion_mask_path` only the inpainting crop applies.
|
|
195
213
|
- A supplied lesion mask must be a single connected component that overlaps the organ
|
|
196
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`.
|
|
197
218
|
- The box guides generation, but generated lesions can extend past the box or organ.
|
|
198
219
|
|
|
199
220
|
**Outputs.** `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
|
|
@@ -213,7 +234,7 @@ it shifts attenuation by several HU, by an amount that depends on the volume.
|
|
|
213
234
|
roles are `image`, `mask` and `organ_mask`, plus `raw_image` for `"box"` and `"lesion"`;
|
|
214
235
|
`artifacts` describes each file and `details` holds run metadata.
|
|
215
236
|
Invalid inputs raise `InvalidInputError`; missing
|
|
216
|
-
or mismatched weights raise `AssetNotReadyError`.
|
|
237
|
+
or mismatched weights raise `AssetNotReadyError`.
|
|
217
238
|
|
|
218
239
|
### Inference modes
|
|
219
240
|
|
|
@@ -223,7 +244,6 @@ or mismatched weights raise `AssetNotReadyError`. Synthetic output is not ground
|
|
|
223
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 |
|
|
224
245
|
|
|
225
246
|
MLX and Torch random streams differ, so a seed repeats results only within MLX.
|
|
226
|
-
Inference requires Apple Silicon with Metal.
|
|
227
247
|
|
|
228
248
|
## Use with MedMLX
|
|
229
249
|
|
|
@@ -242,4 +262,4 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
|
|
|
242
262
|
|
|
243
263
|
## License
|
|
244
264
|
|
|
245
|
-
[Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.
|
|
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.
|
|
@@ -6,7 +6,7 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
|
|
|
6
6
|
|
|
7
7
|
[](https://pypi.org/project/lesiondiffusion-mlx/)
|
|
8
8
|
[](https://pypi.org/project/lesiondiffusion-mlx/)
|
|
9
|
-
[](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.
|
|
9
|
+
[](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.4.0/LICENSE)
|
|
10
10
|
[](https://github.com/ml-explore/mlx)
|
|
11
11
|
[](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
|
|
12
12
|
[](https://github.com/MedMLX/medmlx)
|
|
@@ -23,10 +23,19 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
|
|
|
23
23
|
|
|
24
24
|
| Model | Weights download | Peak MLX memory | Measured on |
|
|
25
25
|
| :--- | ---: | ---: | :--- |
|
|
26
|
-
| `lesiondiffusion`, conditioned mode (default) | 1.7 GB | 5.19 GB | 160×160×128, 1 mm RAS crop, 200 diffusion steps |
|
|
27
|
-
| `lesiondiffusion`,
|
|
28
|
-
|
|
29
|
-
|
|
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)
|
|
30
39
|
give the precision of each network in these measurements.
|
|
31
40
|
|
|
32
41
|
## Install
|
|
@@ -34,7 +43,7 @@ give the precision of each network in these measurements.
|
|
|
34
43
|
```bash
|
|
35
44
|
uv venv --python 3.13
|
|
36
45
|
source .venv/bin/activate
|
|
37
|
-
uv pip install "lesiondiffusion-mlx>=0.
|
|
46
|
+
uv pip install "lesiondiffusion-mlx>=0.4.0"
|
|
38
47
|
```
|
|
39
48
|
|
|
40
49
|
## Run
|
|
@@ -61,8 +70,7 @@ whole volume (see below).
|
|
|
61
70
|
|
|
62
71
|
Weights download from `MedMLX/lesiondiffusion-mlx` on first use; `medmlx setup lesiondiffusion`
|
|
63
72
|
downloads them ahead of time. To use your own copy, pass a folder containing
|
|
64
|
-
`model.safetensors` and `tokenizer.json` as `weights_path`.
|
|
65
|
-
required.
|
|
73
|
+
`model.safetensors` and `tokenizer.json` as `weights_path`.
|
|
66
74
|
|
|
67
75
|
### Inputs and outputs
|
|
68
76
|
|
|
@@ -82,6 +90,7 @@ required.
|
|
|
82
90
|
| `lmnet_diffusion_steps`, `linet_diffusion_steps` | Optional stage overrides; each defaults to `diffusion_steps` |
|
|
83
91
|
| `sampler` | `"ddim"` (default) or `"dpmpp_2m"` in conditioned mode |
|
|
84
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 |
|
|
85
94
|
| `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
|
|
86
95
|
| `output_region` | `"full"` (default), `"box"` or `"lesion"`; see below |
|
|
87
96
|
| `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
|
|
@@ -104,34 +113,43 @@ with load_model() as model:
|
|
|
104
113
|
)
|
|
105
114
|
```
|
|
106
115
|
|
|
107
|
-
The
|
|
108
|
-
|
|
109
|
-
sampler state.
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
and
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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.
|
|
135
153
|
|
|
136
154
|
**Phenotype text.** `shape`, `density`, `density_variation`, `enhancement`, `surface`,
|
|
137
155
|
`adjacent_relationship` and `specific_features` default to the upstream wording
|
|
@@ -146,6 +164,9 @@ condition the generator but do not guarantee a particular HU contrast or appeara
|
|
|
146
164
|
with `lesion_mask_path` only the inpainting crop applies.
|
|
147
165
|
- A supplied lesion mask must be a single connected component that overlaps the organ
|
|
148
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`.
|
|
149
170
|
- The box guides generation, but generated lesions can extend past the box or organ.
|
|
150
171
|
|
|
151
172
|
**Outputs.** `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
|
|
@@ -165,7 +186,7 @@ it shifts attenuation by several HU, by an amount that depends on the volume.
|
|
|
165
186
|
roles are `image`, `mask` and `organ_mask`, plus `raw_image` for `"box"` and `"lesion"`;
|
|
166
187
|
`artifacts` describes each file and `details` holds run metadata.
|
|
167
188
|
Invalid inputs raise `InvalidInputError`; missing
|
|
168
|
-
or mismatched weights raise `AssetNotReadyError`.
|
|
189
|
+
or mismatched weights raise `AssetNotReadyError`.
|
|
169
190
|
|
|
170
191
|
### Inference modes
|
|
171
192
|
|
|
@@ -175,7 +196,6 @@ or mismatched weights raise `AssetNotReadyError`. Synthetic output is not ground
|
|
|
175
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 |
|
|
176
197
|
|
|
177
198
|
MLX and Torch random streams differ, so a seed repeats results only within MLX.
|
|
178
|
-
Inference requires Apple Silicon with Metal.
|
|
179
199
|
|
|
180
200
|
## Use with MedMLX
|
|
181
201
|
|
|
@@ -194,4 +214,4 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
|
|
|
194
214
|
|
|
195
215
|
## License
|
|
196
216
|
|
|
197
|
-
[Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.
|
|
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.
|
|
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.3,<0.4",
|
|
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.
|
|
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"
|
|
@@ -9,6 +9,7 @@ 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
|
|
12
13
|
from lesiondiffusion_mlx.medmlx import load_model as load_model
|
|
13
14
|
from lesiondiffusion_mlx.medmlx import run as run
|
|
14
15
|
from lesiondiffusion_mlx.mlx_model import (
|
|
@@ -34,7 +35,7 @@ if TYPE_CHECKING:
|
|
|
34
35
|
)
|
|
35
36
|
from lesiondiffusion_mlx.mlx_sampling import DdimSampler as DdimSampler
|
|
36
37
|
|
|
37
|
-
__version__ = "0.
|
|
38
|
+
__version__ = "0.4.0"
|
|
38
39
|
|
|
39
40
|
__all__ = [
|
|
40
41
|
"LINET_CONFIG",
|
|
@@ -45,6 +46,7 @@ __all__ = [
|
|
|
45
46
|
"SourceLayers",
|
|
46
47
|
"UnetConfig",
|
|
47
48
|
"VqAutoencoder",
|
|
49
|
+
"draw_lesion_masks",
|
|
48
50
|
"lesion_diffusion_timesteps",
|
|
49
51
|
"load_model",
|
|
50
52
|
"run",
|
|
@@ -57,7 +59,7 @@ def __getattr__(name: str) -> object:
|
|
|
57
59
|
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
58
60
|
module = (
|
|
59
61
|
"medmlx"
|
|
60
|
-
if name in {"run", "load_model"}
|
|
62
|
+
if name in {"run", "load_model", "draw_lesion_masks"}
|
|
61
63
|
else "_schedules"
|
|
62
64
|
if name == "lesion_diffusion_timesteps"
|
|
63
65
|
else "mlx_sampling"
|
{lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_attention.py
RENAMED
|
@@ -36,14 +36,15 @@ from __future__ import annotations
|
|
|
36
36
|
|
|
37
37
|
import math
|
|
38
38
|
from functools import lru_cache
|
|
39
|
-
from typing import TYPE_CHECKING
|
|
39
|
+
from typing import TYPE_CHECKING
|
|
40
40
|
|
|
41
41
|
from lesiondiffusion_mlx._attention_half import flash_attention_half
|
|
42
42
|
from lesiondiffusion_mlx._nax_conv import NAX_MMA_HEADER, nax_available
|
|
43
|
-
from lesiondiffusion_mlx._typing import ArrayConstructor
|
|
44
43
|
|
|
45
44
|
if TYPE_CHECKING:
|
|
46
|
-
from
|
|
45
|
+
from medmlx_core.typing import MetalKernel, MlxRuntime
|
|
46
|
+
|
|
47
|
+
from lesiondiffusion_mlx._typing import Array
|
|
47
48
|
|
|
48
49
|
_SIMDGROUPS = 4
|
|
49
50
|
_BLOCK = 32 # query rows per threadgroup and keys per staged block
|
|
@@ -280,7 +281,7 @@ for (short i = 0; i < 2; i++) {
|
|
|
280
281
|
"""
|
|
281
282
|
|
|
282
283
|
|
|
283
|
-
def flash_eligible(q: Array, k: Array, heads: int, mx:
|
|
284
|
+
def flash_eligible(q: Array, k: Array, heads: int, mx: MlxRuntime) -> bool:
|
|
284
285
|
"""Whether projections ``(B, L, heads * 32)`` fit the kernel.
|
|
285
286
|
|
|
286
287
|
Requires 32-wide heads and query/key lengths divisible by 32. FP32 supports
|
|
@@ -300,7 +301,7 @@ def flash_eligible(q: Array, k: Array, heads: int, mx: Mlx) -> bool:
|
|
|
300
301
|
|
|
301
302
|
|
|
302
303
|
@lru_cache(maxsize=1)
|
|
303
|
-
def _kernel(mx:
|
|
304
|
+
def _kernel(mx: MlxRuntime) -> MetalKernel:
|
|
304
305
|
"""Build the FP32 SIMD kernel once; used when the NAX kernel is unavailable."""
|
|
305
306
|
return mx.fast.metal_kernel(
|
|
306
307
|
name="lesion_flash_attention_fp32_d32",
|
|
@@ -311,7 +312,7 @@ def _kernel(mx: Mlx) -> MetalKernel:
|
|
|
311
312
|
|
|
312
313
|
|
|
313
314
|
@lru_cache(maxsize=1)
|
|
314
|
-
def _nax_kernel(mx:
|
|
315
|
+
def _nax_kernel(mx: MlxRuntime) -> MetalKernel:
|
|
315
316
|
"""Build the NAX kernel once; it takes hi/lo FP16 splits of q, k and v (see ``_split``)."""
|
|
316
317
|
return mx.fast.metal_kernel(
|
|
317
318
|
name="lesion_flash_attention_nax_split_d32",
|
|
@@ -322,13 +323,15 @@ def _nax_kernel(mx: Mlx) -> MetalKernel:
|
|
|
322
323
|
)
|
|
323
324
|
|
|
324
325
|
|
|
325
|
-
def _split(x: Array, mx:
|
|
326
|
+
def _split(x: Array, mx: MlxRuntime) -> tuple[Array, Array]:
|
|
326
327
|
"""FP32 ``x`` as FP16 ``hi = half(x)`` and ``lo = half((x - hi) * 2^11)``."""
|
|
327
328
|
hi = x.astype(mx.float16)
|
|
328
329
|
return hi, ((x - hi.astype(mx.float32)) * 2048.0).astype(mx.float16)
|
|
329
330
|
|
|
330
331
|
|
|
331
|
-
def flash_attention(
|
|
332
|
+
def flash_attention(
|
|
333
|
+
q: Array, k: Array, v: Array, *, heads: int, scale: float, mx: MlxRuntime
|
|
334
|
+
) -> Array:
|
|
332
335
|
"""Multi-head attention on head-interleaved projections.
|
|
333
336
|
|
|
334
337
|
Args:
|
|
@@ -366,7 +369,7 @@ def flash_attention(q: Array, k: Array, v: Array, *, heads: int, scale: float, m
|
|
|
366
369
|
output_dtypes=[mx.float32],
|
|
367
370
|
)[0]
|
|
368
371
|
return _kernel(mx)(
|
|
369
|
-
inputs=[q, k, v,
|
|
372
|
+
inputs=[q, k, v, mx.array([scale], dtype=mx.float32)],
|
|
370
373
|
template=[("L", length), ("LK", int(k.shape[1])), ("H", heads), ("NSG", _SIMDGROUPS)],
|
|
371
374
|
grid=(32 * _SIMDGROUPS * (length // _BLOCK), batch * heads, 1),
|
|
372
375
|
threadgroup=(32 * _SIMDGROUPS, 1, 1),
|
{lesiondiffusion_mlx-0.3.0 → lesiondiffusion_mlx-0.4.0}/src/lesiondiffusion_mlx/_attention_half.py
RENAMED
|
@@ -9,13 +9,14 @@ the projection layout, avoiding padded heads and head-layout copies.
|
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
11
|
from functools import lru_cache
|
|
12
|
-
from typing import TYPE_CHECKING
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
13
|
|
|
14
14
|
from lesiondiffusion_mlx._nax_conv import NAX_MMA_HEADER
|
|
15
|
-
from lesiondiffusion_mlx._typing import ArrayConstructor
|
|
16
15
|
|
|
17
16
|
if TYPE_CHECKING:
|
|
18
|
-
from
|
|
17
|
+
from medmlx_core.typing import MetalKernel, MlxRuntime
|
|
18
|
+
|
|
19
|
+
from lesiondiffusion_mlx._typing import Array
|
|
19
20
|
|
|
20
21
|
_SIMDGROUPS = 4
|
|
21
22
|
_ROWS = 16
|
|
@@ -115,7 +116,7 @@ for (short i = 0; i < 2; i++) {
|
|
|
115
116
|
|
|
116
117
|
|
|
117
118
|
@lru_cache(maxsize=1)
|
|
118
|
-
def _kernel(mx:
|
|
119
|
+
def _kernel(mx: MlxRuntime) -> MetalKernel:
|
|
119
120
|
"""Compile the direct-half NAX kernel once per runtime."""
|
|
120
121
|
return mx.fast.metal_kernel(
|
|
121
122
|
name="lesion_flash_attention_nax_half_d32",
|
|
@@ -127,7 +128,7 @@ def _kernel(mx: Mlx) -> MetalKernel:
|
|
|
127
128
|
|
|
128
129
|
|
|
129
130
|
def flash_attention_half(
|
|
130
|
-
q: Array, k: Array, v: Array, *, heads: int, scale: float, mx:
|
|
131
|
+
q: Array, k: Array, v: Array, *, heads: int, scale: float, mx: MlxRuntime
|
|
131
132
|
) -> Array:
|
|
132
133
|
"""Attend eligible FP16 projections and return their shape, layout and dtype.
|
|
133
134
|
|
|
@@ -138,7 +139,7 @@ def flash_attention_half(
|
|
|
138
139
|
batch, length = int(q.shape[0]), int(q.shape[1])
|
|
139
140
|
groups = -(-length // (_ROWS * _SIMDGROUPS))
|
|
140
141
|
return _kernel(mx)(
|
|
141
|
-
inputs=[q, k, v,
|
|
142
|
+
inputs=[q, k, v, mx.array([scale], dtype=mx.float32)],
|
|
142
143
|
template=[("L", length), ("LK", int(k.shape[1])), ("H", heads), ("NSG", _SIMDGROUPS)],
|
|
143
144
|
grid=(32 * _SIMDGROUPS * groups, batch * heads, 1),
|
|
144
145
|
threadgroup=(32 * _SIMDGROUPS, 1, 1),
|
|
@@ -9,13 +9,14 @@ trajectory, distinct from the stochastic source DDIM sampler.
|
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
11
|
from collections.abc import Callable
|
|
12
|
-
from typing import TYPE_CHECKING
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
13
|
|
|
14
14
|
from lesiondiffusion_mlx._schedules import dpm_solver_timesteps
|
|
15
|
-
from lesiondiffusion_mlx._typing import ArrayConstructor
|
|
16
15
|
|
|
17
16
|
if TYPE_CHECKING:
|
|
18
|
-
from
|
|
17
|
+
from medmlx_core.typing import MlxRuntime
|
|
18
|
+
|
|
19
|
+
from lesiondiffusion_mlx._typing import Array
|
|
19
20
|
|
|
20
21
|
|
|
21
22
|
class Dpmpp2mSampler:
|
|
@@ -27,11 +28,11 @@ class Dpmpp2mSampler:
|
|
|
27
28
|
per-step stochastic draw or eta parameter.
|
|
28
29
|
"""
|
|
29
30
|
|
|
30
|
-
def __init__(self, alphas_cumprod: Array, mx:
|
|
31
|
+
def __init__(self, alphas_cumprod: Array, mx: MlxRuntime, steps: int):
|
|
31
32
|
"""Prepare the reference linspace schedule and FP32 update coefficients."""
|
|
32
33
|
self.mx = mx
|
|
33
34
|
self.timesteps = dpm_solver_timesteps(steps, int(alphas_cumprod.shape[0]))
|
|
34
|
-
indices =
|
|
35
|
+
indices = mx.array(self.timesteps, dtype=mx.int32)
|
|
35
36
|
abar = alphas_cumprod[indices].astype(mx.float32)
|
|
36
37
|
# The reference first computes sigma/alpha, then reconstructs VP
|
|
37
38
|
# alpha and sigma from that ratio. Retain those rounding boundaries.
|
|
@@ -44,8 +45,8 @@ class Dpmpp2mSampler:
|
|
|
44
45
|
raise ValueError(
|
|
45
46
|
"DPM-Solver++ needs finite sampled alphas strictly between zero and one"
|
|
46
47
|
)
|
|
47
|
-
zero =
|
|
48
|
-
one =
|
|
48
|
+
zero = mx.array(0, dtype=mx.float32)
|
|
49
|
+
one = mx.array(1, dtype=mx.float32)
|
|
49
50
|
coefficients: list[Array] = []
|
|
50
51
|
for index in range(len(self.timesteps)):
|
|
51
52
|
if index == len(self.timesteps) - 1:
|