lesiondiffusion-mlx 0.2.7__tar.gz → 0.2.8__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 (22) hide show
  1. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/PKG-INFO +37 -28
  2. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/README.md +34 -25
  3. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/pyproject.toml +3 -3
  4. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/__init__.py +1 -1
  5. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/medmlx.py +201 -47
  6. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/.gitignore +0 -0
  7. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/LICENSE +0 -0
  8. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/THIRD_PARTY_NOTICES.md +0 -0
  9. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/_arrays.py +0 -0
  10. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/_attention.py +0 -0
  11. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/_nax_conv.py +0 -0
  12. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/_nifti.py +0 -0
  13. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/_reference.py +0 -0
  14. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/_schedules.py +0 -0
  15. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/_source_half.py +0 -0
  16. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/_spatial.py +0 -0
  17. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/_typing.py +0 -0
  18. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/mlx_model.py +0 -0
  19. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/mlx_pipeline.py +0 -0
  20. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/mlx_sampling.py +0 -0
  21. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/src/lesiondiffusion_mlx/py.typed +0 -0
  22. {lesiondiffusion_mlx-0.2.7 → lesiondiffusion_mlx-0.2.8}/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.2.7
3
+ Version: 0.2.8
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.2.7/README.md
6
+ Project-URL: Documentation, https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.8/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.2.6
27
+ Requires-Dist: medmlx-core<0.3,>=0.2.6
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,14 +54,14 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
54
54
 
55
55
  [![PyPI](https://img.shields.io/pypi/v/lesiondiffusion-mlx)](https://pypi.org/project/lesiondiffusion-mlx/)
56
56
  [![Python](https://img.shields.io/pypi/pyversions/lesiondiffusion-mlx)](https://pypi.org/project/lesiondiffusion-mlx/)
57
- [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/LICENSE)
57
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.8/LICENSE)
58
58
  [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
59
59
  [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
60
60
  [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
61
61
 
62
62
  [Model weights](https://huggingface.co/MedMLX/lesiondiffusion-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
63
63
 
64
- <img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.7/docs/showcase.png" alt="CT with a synthetic lesion placed inside an organ mask" width="100%">
64
+ <img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.8/docs/showcase.png" alt="CT with a synthetic lesion placed inside an organ mask" width="100%">
65
65
 
66
66
  </div>
67
67
 
@@ -69,15 +69,17 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
69
69
  | :--- | :--- |
70
70
  | **Input** | CT + aligned binary organ mask |
71
71
  | **Output** | Synthetic CT and lesion mask |
72
- | **Hardware** | Apple Silicon with Metal; **3.46 GB** peak MLX memory for `lesiondiffusion` in source mode and **3.29 GB** in the default conditioned mode on a 160×160×128, 1 mm RAS crop. |
72
+ | **Hardware** | Apple Silicon with Metal; **5.19 GB** peak MLX memory for `lesiondiffusion` in the default conditioned mode and **3.46 GB** in source mode on a 160×160×128, 1 mm RAS crop. |
73
73
 
74
74
  Both measurements used an AMOS case 0008 crop and 200 diffusion steps: FP32 LMNet and
75
- text encoders, FP16 LINet and VQ. They do not measure larger volumes. Peak MLX memory
76
- excludes host preprocessing and other applications.
75
+ text encoders, FP16 LINet and VQ encoder, and an FP32 VQ decoder in conditioned mode
76
+ (FP16 in source mode). `output_region="lesion"` decodes twice in sequence without
77
+ raising the peak. They do not measure larger volumes. Peak MLX memory excludes host
78
+ preprocessing and other applications.
77
79
 
78
80
  ## Use with MedMLX
79
81
 
80
- The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this model. It installs this runtime, downloads its weights on first use, and lets an AI agent describe, check and run `lesiondiffusion` for you.
82
+ 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.
81
83
 
82
84
  ```sh
83
85
  uv tool install --python 3.13 "medmlx[generate,mcp]"
@@ -95,7 +97,7 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
95
97
  ```bash
96
98
  uv venv --python 3.13
97
99
  source .venv/bin/activate
98
- uv pip install "lesiondiffusion-mlx>=0.2.7"
100
+ uv pip install "lesiondiffusion-mlx>=0.2.8"
99
101
  ```
100
102
 
101
103
  ## Run
@@ -115,12 +117,9 @@ result = run(
115
117
  print(result["outputs"]["synthetic_image"])
116
118
  ```
117
119
 
118
- Omitting `weights_path` downloads `MedMLX/lesiondiffusion-mlx` into the shared MedMLX
119
- cache on first use; interrupted downloads resume and later runs work offline. With
120
- MedMLX installed, `medmlx setup lesiondiffusion` downloads it ahead of time. To use your
120
+ Weights download from `MedMLX/lesiondiffusion-mlx` on first use. Use `medmlx setup lesiondiffusion` to download ahead of time. To use your
121
121
  own copy, pass a folder containing `model.safetensors` and `tokenizer.json` as
122
- `weights_path`. Conversion receipts are not required. `details.weights_revision` records
123
- the downloaded commit, or `null` for a folder without a MedMLX download record.
122
+ `weights_path`. Conversion receipts are not required.
124
123
 
125
124
  ### Inputs and outputs
126
125
 
@@ -138,7 +137,7 @@ the downloaded commit, or `null` for a folder without a MedMLX download record.
138
137
  | `bbox_center_voxel` | Optional `[I, J, K]` box center on the standardized grid; placement is automatic otherwise |
139
138
  | `diffusion_steps`, `seed` | Sampling controls; the upstream defaults are 200 and 23 |
140
139
  | `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
141
- | `output_region` | `"full"` (default) or `"box"` |
140
+ | `output_region` | `"full"` (default), `"box"` or `"lesion"`; see below |
142
141
  | `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
143
142
  | `overwrite` | `False` by default; existing outputs are never replaced |
144
143
 
@@ -158,24 +157,34 @@ the box or organ.
158
157
 
159
158
  The outputs are `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
160
159
  `organ_mask.nii.gz` (uint8) on the standardized grid. The decoder reconstructs the
161
- whole CT, so voxels outside the lesion can change. `output_region="box"` keeps the
162
- generated CT only over the lesion box, feathers it into the input over 6 mm and also
163
- writes the full reconstruction as `raw_synthetic_ct.nii.gz`. `run` returns
164
- `{"outputs": {...}, "details": {...}}` with the generation settings, quality checks,
165
- stage timing and weights revision. Invalid inputs raise `InvalidInputError`; missing
160
+ whole CT, and that reconstruction does not reproduce the input exactly: away from the
161
+ lesion it shifts attenuation by several HU, by an amount that depends on the volume.
162
+ `output_region` controls how much of it reaches `synthetic_ct.nii.gz`:
163
+
164
+ - `"full"` writes the reconstruction as upstream does, so every voxel can change.
165
+ - `"box"` keeps the reconstruction over the lesion box and feathers it into the input
166
+ over 6 mm. Tissue inside the box keeps the shift.
167
+ - `"lesion"` also decodes the unchanged input and adds only the difference between
168
+ the two decodes to the input CT, within 33 voxels of the lesion along each axis.
169
+ The shift cancels, and voxels farther away are the input unchanged. Use it when
170
+ the surrounding anatomy should keep its measured values.
171
+
172
+ `"box"` and `"lesion"` also write the full reconstruction as `raw_synthetic_ct.nii.gz`.
173
+ `run` returns `{"outputs": {...}, "details": {...}}`, with run metadata in `details`.
174
+ Invalid inputs raise `InvalidInputError`; missing
166
175
  or mismatched weights raise `AssetNotReadyError`. Synthetic output is not ground truth.
167
176
 
168
177
  ### Inference modes
169
178
 
170
179
  `"conditioned"`, the default, enables the inpainting network's trained text context,
171
180
  which the pinned upstream configuration turns off, and runs FP16 convolution, fused
172
- attention and compiled denoisers natively. `"source"` follows the upstream inference
173
- configuration and arithmetic for reproduction; its results can differ from
174
- conditioned output. MLX and Torch random streams differ, so a seed repeats results
175
- only within MLX. Inference needs Apple Silicon with Metal and has no CPU fallback.
181
+ attention and compiled denoisers natively. It decodes in FP32, because the decoder's
182
+ activations can exceed the FP16 range on some volumes. `"source"` follows the
183
+ upstream inference configuration and arithmetic for reproduction, including FP16
184
+ decoding; when that overflows, the run raises an error instead of writing a CT. Its
185
+ results can differ from conditioned output. MLX and Torch random streams differ, so a seed repeats results
186
+ only within MLX. Inference requires Apple Silicon with Metal.
176
187
 
177
188
  ## License
178
189
 
179
- [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
180
-
181
- For research and education. Outputs require human review.
190
+ [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.8/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.8/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -6,14 +6,14 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
6
6
 
7
7
  [![PyPI](https://img.shields.io/pypi/v/lesiondiffusion-mlx)](https://pypi.org/project/lesiondiffusion-mlx/)
8
8
  [![Python](https://img.shields.io/pypi/pyversions/lesiondiffusion-mlx)](https://pypi.org/project/lesiondiffusion-mlx/)
9
- [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/LICENSE)
9
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.8/LICENSE)
10
10
  [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
11
11
  [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
12
12
  [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
13
13
 
14
14
  [Model weights](https://huggingface.co/MedMLX/lesiondiffusion-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
15
15
 
16
- <img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.7/docs/showcase.png" alt="CT with a synthetic lesion placed inside an organ mask" width="100%">
16
+ <img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.8/docs/showcase.png" alt="CT with a synthetic lesion placed inside an organ mask" width="100%">
17
17
 
18
18
  </div>
19
19
 
@@ -21,15 +21,17 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
21
21
  | :--- | :--- |
22
22
  | **Input** | CT + aligned binary organ mask |
23
23
  | **Output** | Synthetic CT and lesion mask |
24
- | **Hardware** | Apple Silicon with Metal; **3.46 GB** peak MLX memory for `lesiondiffusion` in source mode and **3.29 GB** in the default conditioned mode on a 160×160×128, 1 mm RAS crop. |
24
+ | **Hardware** | Apple Silicon with Metal; **5.19 GB** peak MLX memory for `lesiondiffusion` in the default conditioned mode and **3.46 GB** in source mode on a 160×160×128, 1 mm RAS crop. |
25
25
 
26
26
  Both measurements used an AMOS case 0008 crop and 200 diffusion steps: FP32 LMNet and
27
- text encoders, FP16 LINet and VQ. They do not measure larger volumes. Peak MLX memory
28
- excludes host preprocessing and other applications.
27
+ text encoders, FP16 LINet and VQ encoder, and an FP32 VQ decoder in conditioned mode
28
+ (FP16 in source mode). `output_region="lesion"` decodes twice in sequence without
29
+ raising the peak. They do not measure larger volumes. Peak MLX memory excludes host
30
+ preprocessing and other applications.
29
31
 
30
32
  ## Use with MedMLX
31
33
 
32
- The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this model. It installs this runtime, downloads its weights on first use, and lets an AI agent describe, check and run `lesiondiffusion` for you.
34
+ 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.
33
35
 
34
36
  ```sh
35
37
  uv tool install --python 3.13 "medmlx[generate,mcp]"
@@ -47,7 +49,7 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
47
49
  ```bash
48
50
  uv venv --python 3.13
49
51
  source .venv/bin/activate
50
- uv pip install "lesiondiffusion-mlx>=0.2.7"
52
+ uv pip install "lesiondiffusion-mlx>=0.2.8"
51
53
  ```
52
54
 
53
55
  ## Run
@@ -67,12 +69,9 @@ result = run(
67
69
  print(result["outputs"]["synthetic_image"])
68
70
  ```
69
71
 
70
- Omitting `weights_path` downloads `MedMLX/lesiondiffusion-mlx` into the shared MedMLX
71
- cache on first use; interrupted downloads resume and later runs work offline. With
72
- MedMLX installed, `medmlx setup lesiondiffusion` downloads it ahead of time. To use your
72
+ Weights download from `MedMLX/lesiondiffusion-mlx` on first use. Use `medmlx setup lesiondiffusion` to download ahead of time. To use your
73
73
  own copy, pass a folder containing `model.safetensors` and `tokenizer.json` as
74
- `weights_path`. Conversion receipts are not required. `details.weights_revision` records
75
- the downloaded commit, or `null` for a folder without a MedMLX download record.
74
+ `weights_path`. Conversion receipts are not required.
76
75
 
77
76
  ### Inputs and outputs
78
77
 
@@ -90,7 +89,7 @@ the downloaded commit, or `null` for a folder without a MedMLX download record.
90
89
  | `bbox_center_voxel` | Optional `[I, J, K]` box center on the standardized grid; placement is automatic otherwise |
91
90
  | `diffusion_steps`, `seed` | Sampling controls; the upstream defaults are 200 and 23 |
92
91
  | `inference_mode` | `"conditioned"` (default) or `"source"`; see below |
93
- | `output_region` | `"full"` (default) or `"box"` |
92
+ | `output_region` | `"full"` (default), `"box"` or `"lesion"`; see below |
94
93
  | `weights_path` | Optional folder containing `model.safetensors` and `tokenizer.json` |
95
94
  | `overwrite` | `False` by default; existing outputs are never replaced |
96
95
 
@@ -110,24 +109,34 @@ the box or organ.
110
109
 
111
110
  The outputs are `synthetic_ct.nii.gz` (float32 HU), `lesion_mask.nii.gz` and
112
111
  `organ_mask.nii.gz` (uint8) on the standardized grid. The decoder reconstructs the
113
- whole CT, so voxels outside the lesion can change. `output_region="box"` keeps the
114
- generated CT only over the lesion box, feathers it into the input over 6 mm and also
115
- writes the full reconstruction as `raw_synthetic_ct.nii.gz`. `run` returns
116
- `{"outputs": {...}, "details": {...}}` with the generation settings, quality checks,
117
- stage timing and weights revision. Invalid inputs raise `InvalidInputError`; missing
112
+ whole CT, and that reconstruction does not reproduce the input exactly: away from the
113
+ lesion it shifts attenuation by several HU, by an amount that depends on the volume.
114
+ `output_region` controls how much of it reaches `synthetic_ct.nii.gz`:
115
+
116
+ - `"full"` writes the reconstruction as upstream does, so every voxel can change.
117
+ - `"box"` keeps the reconstruction over the lesion box and feathers it into the input
118
+ over 6 mm. Tissue inside the box keeps the shift.
119
+ - `"lesion"` also decodes the unchanged input and adds only the difference between
120
+ the two decodes to the input CT, within 33 voxels of the lesion along each axis.
121
+ The shift cancels, and voxels farther away are the input unchanged. Use it when
122
+ the surrounding anatomy should keep its measured values.
123
+
124
+ `"box"` and `"lesion"` also write the full reconstruction as `raw_synthetic_ct.nii.gz`.
125
+ `run` returns `{"outputs": {...}, "details": {...}}`, with run metadata in `details`.
126
+ Invalid inputs raise `InvalidInputError`; missing
118
127
  or mismatched weights raise `AssetNotReadyError`. Synthetic output is not ground truth.
119
128
 
120
129
  ### Inference modes
121
130
 
122
131
  `"conditioned"`, the default, enables the inpainting network's trained text context,
123
132
  which the pinned upstream configuration turns off, and runs FP16 convolution, fused
124
- attention and compiled denoisers natively. `"source"` follows the upstream inference
125
- configuration and arithmetic for reproduction; its results can differ from
126
- conditioned output. MLX and Torch random streams differ, so a seed repeats results
127
- only within MLX. Inference needs Apple Silicon with Metal and has no CPU fallback.
133
+ attention and compiled denoisers natively. It decodes in FP32, because the decoder's
134
+ activations can exceed the FP16 range on some volumes. `"source"` follows the
135
+ upstream inference configuration and arithmetic for reproduction, including FP16
136
+ decoding; when that overflows, the run raises an error instead of writing a CT. Its
137
+ results can differ from conditioned output. MLX and Torch random streams differ, so a seed repeats results
138
+ only within MLX. Inference requires Apple Silicon with Metal.
128
139
 
129
140
  ## License
130
141
 
131
- [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
132
-
133
- For research and education. Outputs require human review.
142
+ [Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.8/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.8/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.7"
7
+ version = "0.2.8"
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",
40
+ "medmlx-core>=0.2.6,<0.3",
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.7/README.md"
51
+ Documentation = "https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.8/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"
@@ -32,7 +32,7 @@ if TYPE_CHECKING:
32
32
  )
33
33
  from lesiondiffusion_mlx.mlx_sampling import DdimSampler as DdimSampler
34
34
 
35
- __version__ = "0.2.7"
35
+ __version__ = "0.2.8"
36
36
 
37
37
  __all__ = [
38
38
  "LINET_CONFIG",
@@ -67,6 +67,14 @@ DEFAULT_OUTPUT_REGION: Final = "full"
67
67
  # Cosine feather width (mm) for ``output_region="box"``: the generated box is kept,
68
68
  # blended into the input CT over this margin; farther voxels retain its float32 cast.
69
69
  LOCALIZATION_MARGIN_MM: Final = 6.0
70
+ # Per-axis receptive field of the VQ decoder around inpainted latent cells, in voxels
71
+ # of the 1 mm standardized grid. An inpainted cell covers its lesion voxel and the next
72
+ # one (+1). Thirteen 3x3x3 convolutions on the half-resolution latent reach 13 cells
73
+ # (+26 voxels), and six 3x3x3 convolutions after upsampling reach 6 more voxels.
74
+ # GroupNorm statistics span the whole volume, so a lesion also shifts farther voxels,
75
+ # by under 0.05 HU on average in a generated abdomen. ``output_region="lesion"``
76
+ # applies the change within this reach and keeps the input beyond it.
77
+ DECODER_REACH_VOXELS: Final = 33
70
78
  SOURCE_REF: Final[str] = _REFERENCE["revision"]
71
79
  WEIGHT_STAGES: Final = ("lmnet", "linet", "vq", "lmnet_text", "linet_text")
72
80
  SOURCE_INFERENCE_STAGES: Final = tuple(name for name in WEIGHT_STAGES if name != "linet_text")
@@ -108,9 +116,9 @@ MODEL: Final[dict[str, str | float]] = {
108
116
  "Insert one phenotype-controlled synthetic lesion into a CT, given a binary organ "
109
117
  "mask, or inpaint a supplied binary lesion mask. Outputs use a RAS 1 mm grid."
110
118
  ),
111
- # README: source mode (the larger of the two modes), 200 steps, 160x160x128
112
- # RAS 1 mm AMOS case 0008 crop.
113
- "peak_memory_gb": 3.46,
119
+ # README: conditioned mode (the larger of the two modes, with its FP32 VQ decoder),
120
+ # 200 steps, 160x160x128 RAS 1 mm AMOS case 0008 crop.
121
+ "peak_memory_gb": 5.19,
114
122
  }
115
123
 
116
124
 
@@ -158,7 +166,8 @@ class GenerationSpec(TypedDict):
158
166
  ``anatomy_mask`` is present only when an anatomy map was supplied,
159
167
  ``lesion_mask`` only when a lesion mask was supplied (its file, voxel counts and
160
168
  the box derived from it; see ``prepare_lesion_mask``), and ``compositing`` only
161
- for ``output_region="box"`` (see ``localize_output``).
169
+ for ``output_region="box"`` or ``"lesion"`` (see ``localize_output`` and
170
+ ``apply_lesion_change``).
162
171
  """
163
172
 
164
173
  schema_version: str
@@ -203,7 +212,8 @@ class RunResult(TypedDict):
203
212
  """Return value of ``run``.
204
213
 
205
214
  ``outputs`` maps a role to a POSIX file path: ``synthetic_image``, ``target_mask``
206
- and ``organ_mask``, plus ``raw_synthetic_image`` when ``output_region="box"``.
215
+ and ``organ_mask``, plus ``raw_synthetic_image`` when ``output_region`` is
216
+ ``"box"`` or ``"lesion"``.
207
217
  """
208
218
 
209
219
  outputs: dict[str, str]
@@ -225,7 +235,7 @@ class LesionDiffusionOptions:
225
235
  the cavity phrase in the text. ``shape`` through ``specific_features`` are free
226
236
  text for the upstream report. ``seed`` (0 to 2**32 - 1) seeds MT19937 box placement
227
237
  and MLX sampling. ``inference_mode`` is ``"conditioned"`` or ``"source"`` and
228
- ``output_region`` is ``"full"`` or ``"box"``; see ``run``.
238
+ ``output_region`` is ``"full"``, ``"box"`` or ``"lesion"``; see ``run``.
229
239
 
230
240
  Raises:
231
241
  InvalidInputError: From construction, for any value outside these contracts.
@@ -252,8 +262,8 @@ class LesionDiffusionOptions:
252
262
  """Validate inference, geometry, and lesion-generation options."""
253
263
  if self.inference_mode not in {"conditioned", "source"}:
254
264
  raise InvalidInputError("LesionDiffusion inference_mode must be conditioned or source")
255
- if self.output_region not in {"full", "box"}:
256
- raise InvalidInputError("LesionDiffusion output_region must be full or box")
265
+ if self.output_region not in {"full", "box", "lesion"}:
266
+ raise InvalidInputError("LesionDiffusion output_region must be full, box or lesion")
257
267
  if self.organ not in SOURCE_ORGAN_LABELS:
258
268
  raise InvalidInputError(f"Unknown upstream organ: {self.organ}")
259
269
  if not self.lesion_type.strip():
@@ -405,18 +415,24 @@ def run(
405
415
  seed: Seeds box placement and native MLX sampling. MLX's RNG differs from
406
416
  Torch's, so a seed repeats within MLX only.
407
417
  inference_mode: ``"conditioned"`` uses native MLX FP16 convolution and the
408
- trained LINet text path, with resampling at output-affine coordinates.
409
- ``"source"`` reproduces upstream's disabled image text path, Torch CPU
410
- reduction order and legacy ``zoom`` resampling coordinates.
418
+ trained LINet text path, with resampling at output-affine coordinates, and
419
+ decodes the VQ latent in FP32. ``"source"`` reproduces upstream's disabled
420
+ image text path, Torch CPU reduction order, legacy ``zoom`` resampling
421
+ coordinates and FP16 VQ decoding, which overflows to non-finite values on
422
+ some inputs and then raises ``ModelExecutionError``.
411
423
  output_region: ``"full"`` writes upstream's full-volume reconstruction, whose HU
412
- are clipped to [-1000, 1000] and can differ from the input outside the
413
- lesion. ``"box"`` keeps the generated CT over the box, widened to the
414
- lesion's bounding box when the lesion extends past it, feathers that region
415
- into the input CT over ``LOCALIZATION_MARGIN_MM``, and writes the full
416
- reconstruction as ``raw_synthetic_image``. Outside the blend region it
424
+ are clipped to [-1000, 1000] and differ from the input everywhere: the VQ
425
+ autoencoder does not reproduce its input exactly, and its offset depends on
426
+ the encoded volume. ``"box"`` keeps the generated CT over the box, widened
427
+ to the lesion's bounding box when the lesion extends past it, feathers that
428
+ region into the input CT over ``LOCALIZATION_MARGIN_MM``, and writes the
429
+ full reconstruction as ``raw_synthetic_image``. Outside the blend region it
417
430
  retains the standardized input cast to float32, which can round
418
431
  higher-precision input. The lesion mask is not clipped; every lesion voxel
419
- lies in the kept region.
432
+ lies in the kept region. ``"lesion"`` decodes the unmodified input latent
433
+ as well and adds only the lesion's change to the input CT (see
434
+ ``apply_lesion_change``), so the autoencoder's offset does not reach the
435
+ output. It also writes ``raw_synthetic_image``.
420
436
  overwrite: Replace existing output files instead of refusing. A failure before
421
437
  the final file moves leaves no new outputs; a failure during those moves
422
438
  can leave partial outputs that require ``overwrite`` for a retry.
@@ -558,7 +574,7 @@ def _execute_run(
558
574
  attributes = cast(dict[str, object], cast(list[object], report[str(model_label)])[2])
559
575
  mx = cast("Mlx", import_mlx())
560
576
  stages: dict[str, dict[str, object]] = {}
561
- image, mask, facts = run_native_pipeline(
577
+ image, reconstruction, mask, facts = run_native_pipeline(
562
578
  source_ct_ras=geometry.source_data,
563
579
  organ_mask_ras=geometry.organ_mask,
564
580
  bbox_mask_ras=geometry.bbox_mask,
@@ -576,6 +592,7 @@ def _execute_run(
576
592
  image_data=image,
577
593
  lesion_data=mask,
578
594
  output_region=options.output_region,
595
+ input_reconstruction=reconstruction,
579
596
  )
580
597
  spec: GenerationSpec = {
581
598
  "schema_version": "medmlx.lesiondiffusion.generation.v1",
@@ -665,7 +682,7 @@ def run_native_pipeline(
665
682
  on_stage_completed: Callable[[str, dict[str, object]], None],
666
683
  anatomy_mask_ras: HostArray | None = None,
667
684
  lesion_mask_ras: BoolArray | None = None,
668
- ) -> tuple[HostArray, HostArray, NativeRuntime]:
685
+ ) -> tuple[HostArray, HostArray | None, HostArray, NativeRuntime]:
669
686
  """Run LMNet, then LINet and the VQ decoder, with the released EMA weights.
670
687
 
671
688
  Volumes are in standardized RAS ``(X, Y, Z)`` order on the even-padded grid and are
@@ -694,8 +711,10 @@ def run_native_pipeline(
694
711
  ``prepare_lesion_mask``; when given, LMNet is skipped.
695
712
 
696
713
  Returns:
697
- ``(generated_ct, label_map, facts)``. ``generated_ct`` is the full
698
- VQ-reconstructed CT, float32 HU clipped to [-1000, 1000]. ``label_map`` is
714
+ ``(generated_ct, input_reconstruction, label_map, facts)``. ``generated_ct`` is
715
+ the full VQ-reconstructed CT, float32 HU clipped to [-1000, 1000].
716
+ ``input_reconstruction`` decodes the unmodified input latent the same way, for
717
+ ``output_region="lesion"`` only, and is ``None`` otherwise. ``label_map`` is
699
718
  uint8 with 2 for lesion, 1 for the remaining organ voxels and 0 elsewhere.
700
719
  ``facts`` records the runtime settings.
701
720
 
@@ -733,14 +752,19 @@ def run_native_pipeline(
733
752
  lm_stage: dict[str, object] = {"status": "skipped", "reason": "supplied_lesion_mask"}
734
753
  on_stage_completed("lmnet", lm_stage)
735
754
  lin_attributes = _linet_attributes(attributes, options)
736
- generated_ras, lin_stage = _run_linet(
755
+ generated_ras, reconstruction_ras, lin_stage = _run_linet(
737
756
  image, lesion, options, lin_attributes, directory, tokenizer_path, mx
738
757
  )
739
758
  on_stage_completed("linet", lin_stage)
740
759
  lesion_ras = source_to_ras(np.where(lesion, 2, organ.astype(np.uint8)))
741
760
  details: NativeRuntime = {
742
761
  "device": str(mx.default_device()),
743
- "dtype": {"lmnet": "float32", "linet": "float16", "vq": "float16"},
762
+ "dtype": {
763
+ "lmnet": "float32",
764
+ "linet": "float16",
765
+ "vq_encoder": "float16",
766
+ "vq_decoder": "float16" if options.inference_mode == "source" else "float32",
767
+ },
744
768
  "inference_mode": options.inference_mode,
745
769
  "convolution_arithmetic": (
746
770
  "torch_cpu_source_reduction" if options.inference_mode == "source" else "mlx_native"
@@ -766,7 +790,7 @@ def run_native_pipeline(
766
790
  "MLX native RNG; same seed is reproducible within MLX, not identical to Torch RNG"
767
791
  ),
768
792
  }
769
- return generated_ras, lesion_ras, details
793
+ return generated_ras, reconstruction_ras, lesion_ras, details
770
794
 
771
795
 
772
796
  def _linet_attributes(
@@ -899,8 +923,12 @@ def _run_linet(
899
923
  directory: Path,
900
924
  tokenizer_path: Path,
901
925
  mx: Mlx,
902
- ) -> tuple[HostArray, dict[str, object]]:
903
- """Generate the lesion image using the selected mask and attributes."""
926
+ ) -> tuple[HostArray, HostArray | None, dict[str, object]]:
927
+ """Generate the lesion image using the selected mask and attributes.
928
+
929
+ Returns the generated CT and, for ``output_region="lesion"``, the decode of the
930
+ unmodified input latent; both are RAS float32 HU on the input's grid.
931
+ """
904
932
  lin_started = time.perf_counter()
905
933
  source_arithmetic = options.inference_mode == "source"
906
934
  linet = LdmUnet(
@@ -915,14 +943,28 @@ def _run_linet(
915
943
  mx,
916
944
  source_arithmetic=source_arithmetic,
917
945
  )
946
+ # Source mode keeps upstream's FP16 decoder. Conditioned mode decodes in FP32
947
+ # because the activation after the decoder's upsampling convolution can exceed
948
+ # the FP16 maximum of 65504 (about 7.5e4 on a generated abdomen), and the
949
+ # following GroupNorm turns the resulting infinity into NaN.
950
+ decode_dtype = mx.float16 if source_arithmetic else mx.float32
951
+ decoder = (
952
+ vq
953
+ if source_arithmetic
954
+ else VqAutoencoder(
955
+ load_stage(directory, "vq", mx, dtype=mx.float32), mx, source_arithmetic=False
956
+ )
957
+ )
918
958
  nax_convolutions = len(linet.nax_weights) + len(vq.nax_weights)
959
+ if decoder is not vq:
960
+ nax_convolutions += len(decoder.nax_weights)
919
961
  condition: Array | None = None
920
962
  if not source_arithmetic:
921
963
  text = BiomedTextEncoder(load_stage(directory, "linet_text", mx, dtype=mx.float32), mx)
922
964
  condition = encode_attributes(lin_attributes, text, tokenizer_path, mx)
923
965
  del text
924
966
  # Force the lazy weight loads here so load_and_condition_s measures them.
925
- mx.eval(*linet.weights.values(), *vq.weights.values())
967
+ mx.eval(*linet.weights.values(), *vq.weights.values(), *decoder.weights.values())
926
968
  load_elapsed = time.perf_counter() - lin_started
927
969
  encode_started = time.perf_counter()
928
970
  native_image = piecewise_ct(cast(ArrayConstructor, mx.array)(image[None, None]), mx).astype(
@@ -943,7 +985,10 @@ def _run_linet(
943
985
  denoiser = linet.__call__ if source_arithmetic else mx.compile(linet.__call__)
944
986
  mx.eval(mask)
945
987
  sampling_started = time.perf_counter()
946
- generated = sampler(denoiser, condition, latent[selection], mask=mask[selection])
988
+ # Kept for the input reconstruction; the sampler leaves the rest of the latent as is.
989
+ input_window = latent[selection]
990
+ mx.eval(input_window)
991
+ generated = sampler(denoiser, condition, input_window, mask=mask[selection])
947
992
  latent[selection] = generated.astype(mx.float16)
948
993
  mx.eval(latent)
949
994
  if not bool(mx.all(mx.isfinite(latent)).item()):
@@ -954,22 +999,19 @@ def _run_linet(
954
999
  gc.collect()
955
1000
  mx.clear_cache()
956
1001
  decode_started = time.perf_counter()
957
- decoded = vq.decode(latent)
958
- mx.eval(decoded)
959
- if not bool(mx.all(mx.isfinite(decoded)).item()):
960
- raise ModelExecutionError(
961
- "Native VQ decoder produced non-finite voxels before CT remapping"
962
- )
963
- decoded = piecewise_ct(decoded.astype(mx.float32), mx, inverse=True)
964
- mx.eval(decoded)
965
- if not bool(mx.all(mx.isfinite(decoded)).item()):
966
- raise ModelExecutionError("Native LINet/VQ produced non-finite CT voxels")
967
- generated_ras = source_to_ras(np.array(decoded)[0, 0]).astype(np.float32)
1002
+ generated_ras = _decode_ct(decoder, latent, decode_dtype, mx)
1003
+ reconstruction_ras: HostArray | None = None
1004
+ if options.output_region == "lesion":
1005
+ mx.clear_cache()
1006
+ latent[selection] = input_window
1007
+ reconstruction_ras = _decode_ct(decoder, latent, decode_dtype, mx)
968
1008
  decode_elapsed = time.perf_counter() - decode_started
969
1009
  lin_stage: dict[str, object] = {
970
1010
  "status": "completed",
971
1011
  "device": str(mx.default_device()),
972
1012
  "dtype": "float16",
1013
+ "decode_dtype": "float16" if source_arithmetic else "float32",
1014
+ "input_reconstruction_decoded": reconstruction_ras is not None,
973
1015
  "crop_shape": list(LINET_CROP),
974
1016
  "latent_shape": list(latent.shape),
975
1017
  "output_shape": list(image.shape),
@@ -984,7 +1026,29 @@ def _run_linet(
984
1026
  "decode_and_export_s": decode_elapsed,
985
1027
  "synchronized_elapsed_s": time.perf_counter() - lin_started,
986
1028
  }
987
- return generated_ras, lin_stage
1029
+ return generated_ras, reconstruction_ras, lin_stage
1030
+
1031
+
1032
+ def _decode_ct(decoder: VqAutoencoder, latent: Array, dtype: Dtype, mx: Mlx) -> FloatArray:
1033
+ """Decode a source-layout latent to a RAS CT in HU (float32, clipped to +-1000).
1034
+
1035
+ Raises:
1036
+ ModelExecutionError: If the decoder or the HU remapping yields non-finite voxels.
1037
+ """
1038
+ decoded = decoder.decode(latent.astype(dtype))
1039
+ mx.eval(decoded)
1040
+ if not bool(mx.all(mx.isfinite(decoded)).item()):
1041
+ overflow = (
1042
+ " (FP16 overflow; conditioned mode decodes in FP32)" if dtype == mx.float16 else ""
1043
+ )
1044
+ raise ModelExecutionError(
1045
+ f"Native VQ decoder produced non-finite voxels before CT remapping{overflow}"
1046
+ )
1047
+ decoded = piecewise_ct(decoded.astype(mx.float32), mx, inverse=True)
1048
+ mx.eval(decoded)
1049
+ if not bool(mx.all(mx.isfinite(decoded)).item()):
1050
+ raise ModelExecutionError("Native LINet/VQ produced non-finite CT voxels")
1051
+ return source_to_ras(np.array(decoded)[0, 0]).astype(np.float32)
988
1052
 
989
1053
 
990
1054
  def _linet_latent_window(lesion: BoolArray) -> tuple[slice, slice, slice]:
@@ -1855,6 +1919,7 @@ def materialize_arrays(
1855
1919
  image_data: HostArray,
1856
1920
  lesion_data: HostArray,
1857
1921
  output_region: str = DEFAULT_OUTPUT_REGION,
1922
+ input_reconstruction: HostArray | None = None,
1858
1923
  ) -> tuple[OutputValidation, dict[str, object] | None]:
1859
1924
  """Validate the generated arrays and write every output NIfTI file.
1860
1925
 
@@ -1873,21 +1938,27 @@ def materialize_arrays(
1873
1938
  geometry: Standardized inputs; ``output_reference`` defines the written grid.
1874
1939
  image_data: Generated CT (HU) on the even-padded grid.
1875
1940
  lesion_data: Label map on the same grid; 2 marks the lesion.
1876
- output_region: ``"full"`` or ``"box"``; see ``run``.
1941
+ output_region: ``"full"``, ``"box"`` or ``"lesion"``; see ``run``.
1942
+ input_reconstruction: Decode of the unmodified input latent on the same grid;
1943
+ required for, and only used by, ``output_region="lesion"``.
1877
1944
 
1878
1945
  Returns:
1879
- ``(output_validation, compositing)``; ``compositing`` is ``None`` unless
1880
- ``output_region="box"``.
1946
+ ``(output_validation, compositing)``; ``compositing`` is ``None`` for
1947
+ ``output_region="full"``.
1881
1948
 
1882
1949
  Raises:
1883
- ModelExecutionError: If shapes differ from the grid, values are non-finite, or
1884
- the label map has no lesion.
1950
+ ModelExecutionError: If shapes differ from the grid, values are non-finite, the
1951
+ label map has no lesion, or ``"lesion"`` lacks the input reconstruction.
1885
1952
  """
1886
1953
  if (
1887
1954
  image_data.shape != geometry.reference.shape
1888
1955
  or lesion_data.shape != geometry.reference.shape
1889
1956
  ):
1890
1957
  raise ModelExecutionError("LesionDiffusion generated arrays differ from the input grid")
1958
+ if output_region == "lesion" and (
1959
+ input_reconstruction is None or input_reconstruction.shape != image_data.shape
1960
+ ):
1961
+ raise ModelExecutionError("LesionDiffusion lesion output needs the input reconstruction")
1891
1962
  if not np.all(np.isfinite(image_data)) or not np.all(np.isfinite(lesion_data)):
1892
1963
  raise ModelExecutionError("LesionDiffusion generated arrays contain non-finite voxels")
1893
1964
  lesion = (lesion_data[_input_grid(geometry.output_reference)] == 2).astype(np.uint8)
@@ -1930,6 +2001,14 @@ def materialize_arrays(
1930
2001
  "stop_voxel_exclusive": [int(part.stop) for part in box],
1931
2002
  }
1932
2003
  images = [(localized, "synthetic_image"), (image_data, "raw_synthetic_image")]
2004
+ elif output_region == "lesion":
2005
+ localized, compositing = apply_lesion_change(
2006
+ original=geometry.source_data,
2007
+ generated=cast(NumericArray, image_data),
2008
+ reconstruction=cast(NumericArray, input_reconstruction),
2009
+ lesion=lesion_data == 2,
2010
+ )
2011
+ images = [(localized, "synthetic_image"), (image_data, "raw_synthetic_image")]
1933
2012
  organ = np.where(geometry.organ_mask, geometry.organ_label, 0).astype(np.uint8)
1934
2013
  writes: list[tuple[HostArray, str, type[np.generic]]] = [
1935
2014
  *((data, role, np.float32) for data, role in images),
@@ -1984,13 +2063,13 @@ def _input_grid(reference: NiftiImage) -> tuple[slice, ...]:
1984
2063
 
1985
2064
 
1986
2065
  def output_paths(output: Path, output_region: str = DEFAULT_OUTPUT_REGION) -> dict[str, Path]:
1987
- """Map each output role to its file; ``box`` mode adds ``raw_synthetic_image``."""
2066
+ """Map each output role to its file; ``box`` and ``lesion`` add ``raw_synthetic_image``."""
1988
2067
  paths = {
1989
2068
  "synthetic_image": output / _SYNTHETIC_CT,
1990
2069
  "target_mask": output / _LESION_MASK,
1991
2070
  "organ_mask": output / _ORGAN_MASK,
1992
2071
  }
1993
- if output_region == "box":
2072
+ if output_region in {"box", "lesion"}:
1994
2073
  paths["raw_synthetic_image"] = output / _RAW_SYNTHETIC_CT
1995
2074
  return paths
1996
2075
 
@@ -2081,6 +2160,81 @@ def localize_output(
2081
2160
  }
2082
2161
 
2083
2162
 
2163
+ def apply_lesion_change(
2164
+ *,
2165
+ original: NumericArray,
2166
+ generated: NumericArray,
2167
+ reconstruction: NumericArray,
2168
+ lesion: BoolArray,
2169
+ reach_voxels: int = DECODER_REACH_VOXELS,
2170
+ ) -> tuple[FloatArray, dict[str, object]]:
2171
+ """Add the lesion's change to the original CT around the lesion.
2172
+
2173
+ The change is ``generated - reconstruction``: the decode of the inpainted latent
2174
+ minus the decode of the unmodified input latent. Both decodes carry the VQ
2175
+ autoencoder's own reconstruction error, an HU offset whose size and sign depend on
2176
+ the encoded volume, so their difference keeps what inpainting changed and drops
2177
+ that offset. The change is added to the original CT within ``reach_voxels`` of a
2178
+ lesion voxel along every axis, the decoder's receptive field; every other voxel is
2179
+ the original CT converted to float32. Inside the lesion the result keeps the input
2180
+ detail the autoencoder does not reproduce, including its noise grain.
2181
+
2182
+ Args:
2183
+ original: Standardized input CT (HU) on the even-padded grid.
2184
+ generated: Decode of the inpainted latent on the same grid.
2185
+ reconstruction: Decode of the unmodified input latent on the same grid.
2186
+ lesion: Boolean lesion mask on the same grid.
2187
+ reach_voxels: Per-axis reach of the change from a lesion voxel.
2188
+
2189
+ Returns:
2190
+ ``(localized_ct, facts)``: a float32 array and a record of the policy, including
2191
+ the mean reconstruction offset (HU) removed outside the lesion.
2192
+
2193
+ Raises:
2194
+ ModelExecutionError: If the arrays differ in shape or the lesion is empty.
2195
+ """
2196
+ from scipy.ndimage import maximum_filter
2197
+
2198
+ if not original.shape == generated.shape == reconstruction.shape == lesion.shape:
2199
+ raise ModelExecutionError("LesionDiffusion lesion change arrays differ in shape")
2200
+ points = np.argwhere(lesion)
2201
+ if points.size == 0:
2202
+ raise ModelExecutionError("LesionDiffusion lesion change needs a non-empty lesion")
2203
+ low = np.maximum(points.min(axis=0) - reach_voxels, 0)
2204
+ high = np.minimum(points.max(axis=0) + reach_voxels + 1, np.asarray(original.shape[:3]))
2205
+ region = cast(
2206
+ tuple[slice, slice, slice],
2207
+ tuple(slice(int(a), int(b)) for a, b in zip(low, high, strict=True)),
2208
+ )
2209
+ # A cubic maximum filter marks every voxel within reach of a lesion voxel per axis.
2210
+ reached = maximum_filter(lesion[region].astype(np.uint8), size=2 * reach_voxels + 1) > 0
2211
+ change = np.asarray(generated[region], dtype=np.float32) - np.asarray(
2212
+ reconstruction[region], dtype=np.float32
2213
+ )
2214
+ localized = np.asarray(original, dtype=np.float32).copy()
2215
+ window = localized[region]
2216
+ window[reached] += change[reached]
2217
+ # Decodes are clipped to +-1000 HU, so the offset is measured inside that range only.
2218
+ input_window = np.asarray(original[region], dtype=np.float64)
2219
+ surroundings = reached & ~lesion[region] & (np.abs(input_window) < 1000)
2220
+ offset = (
2221
+ np.asarray(reconstruction[region], dtype=np.float64)[surroundings]
2222
+ - input_window[surroundings]
2223
+ )
2224
+ return localized, {
2225
+ "policy": "original_plus_generated_minus_input_reconstruction",
2226
+ "reach_voxels": reach_voxels,
2227
+ "reach_metric": "per_axis_voxel_distance_from_nearest_lesion_voxel",
2228
+ "changed_region": {
2229
+ "start_voxel": [int(value) for value in low],
2230
+ "stop_voxel_exclusive": [int(value) for value in high],
2231
+ "voxel_count": int(np.count_nonzero(reached)),
2232
+ },
2233
+ "input_reconstruction_offset_hu": round(float(offset.mean()), 3) if offset.size else None,
2234
+ "outside_changed_region": "original_ct_cast_float32",
2235
+ }
2236
+
2237
+
2084
2238
  def _with_comma(value: str) -> str:
2085
2239
  # Upstream report phrases are comma-terminated.
2086
2240
  """Normalize an upstream report phrase to end with one comma."""