diffct-mlx 1.0.1__tar.gz → 1.0.3__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.
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/.gitignore +3 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/PKG-INFO +64 -6
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/README.md +63 -5
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/__about__.py +1 -1
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/kernels/__init__.py +4 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/kernels/cone_beam.py +418 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/projectors.py +232 -8
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/LICENSE +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/__init__.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/constants.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/geometry.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/kernels/fan_beam.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/kernels/parallel_beam.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/phantoms/__init__.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/phantoms/shepp_logan.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/real_measured_data_helper.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/__init__.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/_analytic.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/_core.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/asd_pocs.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/awtv_pocs.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/cases.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/dart.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/fbp.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/fdk.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/sart.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/sirt.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/reconstruction_algorithms/tv_pocs.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/regularizers.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/tv_gradients.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/diffct_mlx/utils.py +0 -0
- {diffct_mlx-1.0.1 → diffct_mlx-1.0.3}/pyproject.toml +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: diffct_mlx
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.3
|
|
4
4
|
Summary: Differentiable CT reconstruction for Apple Silicon using MLX and custom Metal kernels
|
|
5
5
|
Project-URL: Homepage, https://github.com/Linda-SophieSchneider/diffct_arbit
|
|
6
6
|
Project-URL: Repository, https://github.com/Linda-SophieSchneider/diffct_arbit
|
|
@@ -31,7 +31,7 @@ Description-Content-Type: text/markdown
|
|
|
31
31
|
# diffct_mlx: Differentiable CT for Apple Silicon
|
|
32
32
|
|
|
33
33
|
[](https://opensource.org/licenses/Apache-2.0)
|
|
34
|
-
[](https://doi.org/10.20944/preprints202605.1446.v1)
|
|
35
35
|
|
|
36
36
|
A high-performance, differentiable computed tomography (CT) reconstruction library built with [MLX](https://github.com/ml-explore/mlx) and custom Metal kernels, optimized for Apple Silicon (M-series) chips.
|
|
37
37
|
|
|
@@ -43,6 +43,7 @@ This is the Apple Silicon port of [diffct](https://github.com/sypsyp97/diffct),
|
|
|
43
43
|
- **Differentiable:** End-to-end gradient propagation using `mx.custom_function` with custom VJPs
|
|
44
44
|
- **Siddon Ray-Tracing:** Bilinear (2D) and trilinear (3D) interpolation for accurate projection
|
|
45
45
|
- **Atomic Backprojection:** Thread-safe gradient accumulation using Metal atomic operations
|
|
46
|
+
- **Sparse Cone Backprojection:** Sample-only cone-beam footprint backprojection via `indices=...`
|
|
46
47
|
|
|
47
48
|
## Supported Geometries
|
|
48
49
|
|
|
@@ -191,6 +192,56 @@ reco = diffct_mlx.cone_backward(
|
|
|
191
192
|
)
|
|
192
193
|
```
|
|
193
194
|
|
|
195
|
+
### Sparse Cone-Backprojection Sampling
|
|
196
|
+
|
|
197
|
+
`cone_backward_footprint` supports sample-only evaluation for cone-beam filtered
|
|
198
|
+
backprojection. This is useful when you need values at a subset of voxels
|
|
199
|
+
instead of the full volume, for example for sparse slice probing or cache
|
|
200
|
+
construction workflows.
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
import numpy as np
|
|
204
|
+
import mlx.core as mx
|
|
205
|
+
import diffct_mlx
|
|
206
|
+
from diffct_mlx.reconstruction_algorithms._analytic import ramp_filter_3d
|
|
207
|
+
|
|
208
|
+
volume = mx.ones((32, 32, 32), dtype=mx.float32)
|
|
209
|
+
src, det_c, det_u, det_v = diffct_mlx.circular_trajectory_3d(
|
|
210
|
+
n_views=60, sid=120.0, sdd=200.0
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
sino = diffct_mlx.cone_forward_footprint(
|
|
214
|
+
volume, src, det_c, det_u, det_v,
|
|
215
|
+
det_u=48, det_v=48, du=1.0, dv=1.0, voxel_spacing=1.0,
|
|
216
|
+
)
|
|
217
|
+
sino_filt = ramp_filter_3d(sino)
|
|
218
|
+
|
|
219
|
+
mid = volume.shape[0] // 2
|
|
220
|
+
yy, xx = np.meshgrid(
|
|
221
|
+
np.arange(volume.shape[1]),
|
|
222
|
+
np.arange(volume.shape[2]),
|
|
223
|
+
indexing="ij",
|
|
224
|
+
)
|
|
225
|
+
indices = (
|
|
226
|
+
mid * volume.shape[1] * volume.shape[2]
|
|
227
|
+
+ yy.reshape(-1) * volume.shape[2]
|
|
228
|
+
+ xx.reshape(-1)
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
slice_samples = diffct_mlx.cone_backward_footprint(
|
|
232
|
+
sino_filt, src, det_c, det_u, det_v,
|
|
233
|
+
D=32, H=32, W=32, du=1.0, dv=1.0, voxel_spacing=1.0,
|
|
234
|
+
indices=indices,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
# Returns a 1D vector in the same order as `indices`.
|
|
238
|
+
centre_slice = slice_samples.reshape(32, 32)
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Sparse mode preserves the dense footprint backprojector's values exactly at the
|
|
242
|
+
requested locations. Indices must be unique flat indices into the row-major
|
|
243
|
+
`(D, H, W)` volume layout.
|
|
244
|
+
|
|
194
245
|
## API Reference
|
|
195
246
|
|
|
196
247
|
### Projectors
|
|
@@ -203,6 +254,8 @@ reco = diffct_mlx.cone_backward(
|
|
|
203
254
|
| `fan_backward(sinogram, src_pos, det_center, det_u_vec, ...)` | 2D fan beam backprojection |
|
|
204
255
|
| `cone_forward(volume, src_pos, det_center, det_u_vec, det_v_vec, ...)` | 3D cone beam forward projection |
|
|
205
256
|
| `cone_backward(sinogram, src_pos, det_center, det_u_vec, det_v_vec, ...)` | 3D cone beam backprojection |
|
|
257
|
+
| `cone_forward_footprint(volume, src_pos, det_center, det_u_vec, det_v_vec, ...)` | 3D matched-footprint cone forward projection |
|
|
258
|
+
| `cone_backward_footprint(sinogram, src_pos, det_center, det_u_vec, det_v_vec, ..., indices=None)` | 3D matched-footprint cone backprojection, optionally sparse |
|
|
206
259
|
|
|
207
260
|
### Iterative Reconstruction Algorithms
|
|
208
261
|
|
|
@@ -293,10 +346,15 @@ diffct_mlx/
|
|
|
293
346
|
If you use this library in your research, please cite:
|
|
294
347
|
|
|
295
348
|
```bibtex
|
|
296
|
-
@
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
year
|
|
349
|
+
@article{202605.1446,
|
|
350
|
+
doi = {10.20944/preprints202605.1446.v1},
|
|
351
|
+
url = {https://doi.org/10.20944/preprints202605.1446.v1},
|
|
352
|
+
year = 2026,
|
|
353
|
+
month = {May},
|
|
354
|
+
publisher = {Preprints},
|
|
355
|
+
author = {Yipeng Sun and Linda-Sophie Schneider and Chengze ye and Andreas Maier},
|
|
356
|
+
title = {diffct: Differentiable CT Operators from Circular Orbits to Arbitrary Trajectories},
|
|
357
|
+
journal = {Preprints}
|
|
300
358
|
}
|
|
301
359
|
```
|
|
302
360
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# diffct_mlx: Differentiable CT for Apple Silicon
|
|
2
2
|
|
|
3
3
|
[](https://opensource.org/licenses/Apache-2.0)
|
|
4
|
-
[](https://doi.org/10.20944/preprints202605.1446.v1)
|
|
5
5
|
|
|
6
6
|
A high-performance, differentiable computed tomography (CT) reconstruction library built with [MLX](https://github.com/ml-explore/mlx) and custom Metal kernels, optimized for Apple Silicon (M-series) chips.
|
|
7
7
|
|
|
@@ -13,6 +13,7 @@ This is the Apple Silicon port of [diffct](https://github.com/sypsyp97/diffct),
|
|
|
13
13
|
- **Differentiable:** End-to-end gradient propagation using `mx.custom_function` with custom VJPs
|
|
14
14
|
- **Siddon Ray-Tracing:** Bilinear (2D) and trilinear (3D) interpolation for accurate projection
|
|
15
15
|
- **Atomic Backprojection:** Thread-safe gradient accumulation using Metal atomic operations
|
|
16
|
+
- **Sparse Cone Backprojection:** Sample-only cone-beam footprint backprojection via `indices=...`
|
|
16
17
|
|
|
17
18
|
## Supported Geometries
|
|
18
19
|
|
|
@@ -161,6 +162,56 @@ reco = diffct_mlx.cone_backward(
|
|
|
161
162
|
)
|
|
162
163
|
```
|
|
163
164
|
|
|
165
|
+
### Sparse Cone-Backprojection Sampling
|
|
166
|
+
|
|
167
|
+
`cone_backward_footprint` supports sample-only evaluation for cone-beam filtered
|
|
168
|
+
backprojection. This is useful when you need values at a subset of voxels
|
|
169
|
+
instead of the full volume, for example for sparse slice probing or cache
|
|
170
|
+
construction workflows.
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
import numpy as np
|
|
174
|
+
import mlx.core as mx
|
|
175
|
+
import diffct_mlx
|
|
176
|
+
from diffct_mlx.reconstruction_algorithms._analytic import ramp_filter_3d
|
|
177
|
+
|
|
178
|
+
volume = mx.ones((32, 32, 32), dtype=mx.float32)
|
|
179
|
+
src, det_c, det_u, det_v = diffct_mlx.circular_trajectory_3d(
|
|
180
|
+
n_views=60, sid=120.0, sdd=200.0
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
sino = diffct_mlx.cone_forward_footprint(
|
|
184
|
+
volume, src, det_c, det_u, det_v,
|
|
185
|
+
det_u=48, det_v=48, du=1.0, dv=1.0, voxel_spacing=1.0,
|
|
186
|
+
)
|
|
187
|
+
sino_filt = ramp_filter_3d(sino)
|
|
188
|
+
|
|
189
|
+
mid = volume.shape[0] // 2
|
|
190
|
+
yy, xx = np.meshgrid(
|
|
191
|
+
np.arange(volume.shape[1]),
|
|
192
|
+
np.arange(volume.shape[2]),
|
|
193
|
+
indexing="ij",
|
|
194
|
+
)
|
|
195
|
+
indices = (
|
|
196
|
+
mid * volume.shape[1] * volume.shape[2]
|
|
197
|
+
+ yy.reshape(-1) * volume.shape[2]
|
|
198
|
+
+ xx.reshape(-1)
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
slice_samples = diffct_mlx.cone_backward_footprint(
|
|
202
|
+
sino_filt, src, det_c, det_u, det_v,
|
|
203
|
+
D=32, H=32, W=32, du=1.0, dv=1.0, voxel_spacing=1.0,
|
|
204
|
+
indices=indices,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
# Returns a 1D vector in the same order as `indices`.
|
|
208
|
+
centre_slice = slice_samples.reshape(32, 32)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Sparse mode preserves the dense footprint backprojector's values exactly at the
|
|
212
|
+
requested locations. Indices must be unique flat indices into the row-major
|
|
213
|
+
`(D, H, W)` volume layout.
|
|
214
|
+
|
|
164
215
|
## API Reference
|
|
165
216
|
|
|
166
217
|
### Projectors
|
|
@@ -173,6 +224,8 @@ reco = diffct_mlx.cone_backward(
|
|
|
173
224
|
| `fan_backward(sinogram, src_pos, det_center, det_u_vec, ...)` | 2D fan beam backprojection |
|
|
174
225
|
| `cone_forward(volume, src_pos, det_center, det_u_vec, det_v_vec, ...)` | 3D cone beam forward projection |
|
|
175
226
|
| `cone_backward(sinogram, src_pos, det_center, det_u_vec, det_v_vec, ...)` | 3D cone beam backprojection |
|
|
227
|
+
| `cone_forward_footprint(volume, src_pos, det_center, det_u_vec, det_v_vec, ...)` | 3D matched-footprint cone forward projection |
|
|
228
|
+
| `cone_backward_footprint(sinogram, src_pos, det_center, det_u_vec, det_v_vec, ..., indices=None)` | 3D matched-footprint cone backprojection, optionally sparse |
|
|
176
229
|
|
|
177
230
|
### Iterative Reconstruction Algorithms
|
|
178
231
|
|
|
@@ -263,10 +316,15 @@ diffct_mlx/
|
|
|
263
316
|
If you use this library in your research, please cite:
|
|
264
317
|
|
|
265
318
|
```bibtex
|
|
266
|
-
@
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
year
|
|
319
|
+
@article{202605.1446,
|
|
320
|
+
doi = {10.20944/preprints202605.1446.v1},
|
|
321
|
+
url = {https://doi.org/10.20944/preprints202605.1446.v1},
|
|
322
|
+
year = 2026,
|
|
323
|
+
month = {May},
|
|
324
|
+
publisher = {Preprints},
|
|
325
|
+
author = {Yipeng Sun and Linda-Sophie Schneider and Chengze ye and Andreas Maier},
|
|
326
|
+
title = {diffct: Differentiable CT Operators from Circular Orbits to Arbitrary Trajectories},
|
|
327
|
+
journal = {Preprints}
|
|
270
328
|
}
|
|
271
329
|
```
|
|
272
330
|
|
|
@@ -21,6 +21,8 @@ from .cone_beam import (
|
|
|
21
21
|
cone_3d_backward_kernel,
|
|
22
22
|
cone_3d_footprint_forward_kernel,
|
|
23
23
|
cone_3d_footprint_backward_kernel,
|
|
24
|
+
cone_3d_footprint_backward_sparse_kernel,
|
|
25
|
+
cone_3d_geometry_grad_kernel,
|
|
24
26
|
)
|
|
25
27
|
|
|
26
28
|
__all__ = [
|
|
@@ -36,4 +38,6 @@ __all__ = [
|
|
|
36
38
|
'cone_3d_backward_kernel',
|
|
37
39
|
'cone_3d_footprint_forward_kernel',
|
|
38
40
|
'cone_3d_footprint_backward_kernel',
|
|
41
|
+
'cone_3d_footprint_backward_sparse_kernel',
|
|
42
|
+
'cone_3d_geometry_grad_kernel',
|
|
39
43
|
]
|
|
@@ -706,3 +706,421 @@ cone_3d_footprint_backward_kernel = mx.fast.metal_kernel(
|
|
|
706
706
|
output_names=["grad_vol"],
|
|
707
707
|
source=_CONE_3D_FOOTPRINT_BACKWARD_SOURCE,
|
|
708
708
|
)
|
|
709
|
+
|
|
710
|
+
_CONE_3D_FOOTPRINT_BACKWARD_SPARSE_SOURCE = """
|
|
711
|
+
uint isample = thread_position_in_grid.x;
|
|
712
|
+
|
|
713
|
+
int n_samples = sparse_params[0];
|
|
714
|
+
int n_views = params[0];
|
|
715
|
+
int n_u = params[1];
|
|
716
|
+
int n_v = params[2];
|
|
717
|
+
int Nx = params[3];
|
|
718
|
+
int Ny = params[4];
|
|
719
|
+
int Nz = params[5];
|
|
720
|
+
|
|
721
|
+
float du = fparams[0];
|
|
722
|
+
float dv = fparams[1];
|
|
723
|
+
float cx = fparams[2];
|
|
724
|
+
float cy = fparams[3];
|
|
725
|
+
float cz = fparams[4];
|
|
726
|
+
float voxel_spacing = fparams[5];
|
|
727
|
+
|
|
728
|
+
if ((int)isample >= n_samples) return;
|
|
729
|
+
|
|
730
|
+
int flat_idx = indices[(int)isample];
|
|
731
|
+
int ix = flat_idx % Nx;
|
|
732
|
+
int iy = (flat_idx / Nx) % Ny;
|
|
733
|
+
int iz = flat_idx / (Nx * Ny);
|
|
734
|
+
|
|
735
|
+
float eps = """ + _EPSILON_STR + """;
|
|
736
|
+
float center_u = ((float)n_u - 1.0f) * 0.5f;
|
|
737
|
+
float center_v = ((float)n_v - 1.0f) * 0.5f;
|
|
738
|
+
|
|
739
|
+
float px = (((float)ix + 0.5f) - cx) * voxel_spacing;
|
|
740
|
+
float py = (((float)iy + 0.5f) - cy) * voxel_spacing;
|
|
741
|
+
float pz = (((float)iz + 0.5f) - cz) * voxel_spacing;
|
|
742
|
+
|
|
743
|
+
float accum = 0.0f;
|
|
744
|
+
|
|
745
|
+
for (int iview = 0; iview < n_views; ++iview) {
|
|
746
|
+
float src_x = src_pos[iview * 3 + 0];
|
|
747
|
+
float src_y = src_pos[iview * 3 + 1];
|
|
748
|
+
float src_z = src_pos[iview * 3 + 2];
|
|
749
|
+
|
|
750
|
+
float det_cx = det_center_arr[iview * 3 + 0];
|
|
751
|
+
float det_cy = det_center_arr[iview * 3 + 1];
|
|
752
|
+
float det_cz = det_center_arr[iview * 3 + 2];
|
|
753
|
+
|
|
754
|
+
float u_vec_x = det_u_vec_arr[iview * 3 + 0];
|
|
755
|
+
float u_vec_y = det_u_vec_arr[iview * 3 + 1];
|
|
756
|
+
float u_vec_z = det_u_vec_arr[iview * 3 + 2];
|
|
757
|
+
|
|
758
|
+
float v_vec_x = det_v_vec_arr[iview * 3 + 0];
|
|
759
|
+
float v_vec_y = det_v_vec_arr[iview * 3 + 1];
|
|
760
|
+
float v_vec_z = det_v_vec_arr[iview * 3 + 2];
|
|
761
|
+
|
|
762
|
+
float n_x = u_vec_y * v_vec_z - u_vec_z * v_vec_y;
|
|
763
|
+
float n_y = u_vec_z * v_vec_x - u_vec_x * v_vec_z;
|
|
764
|
+
float n_z = u_vec_x * v_vec_y - u_vec_y * v_vec_x;
|
|
765
|
+
|
|
766
|
+
float plane_dx = det_cx - src_x;
|
|
767
|
+
float plane_dy = det_cy - src_y;
|
|
768
|
+
float plane_dz = det_cz - src_z;
|
|
769
|
+
float plane_dist = plane_dx * n_x + plane_dy * n_y + plane_dz * n_z;
|
|
770
|
+
if (metal::abs(plane_dist) <= eps) continue;
|
|
771
|
+
|
|
772
|
+
float rx = px - src_x;
|
|
773
|
+
float ry = py - src_y;
|
|
774
|
+
float rz = pz - src_z;
|
|
775
|
+
float denom = rx * n_x + ry * n_y + rz * n_z;
|
|
776
|
+
if (metal::abs(denom) <= eps) continue;
|
|
777
|
+
|
|
778
|
+
float t = plane_dist / denom;
|
|
779
|
+
if (t <= 0.0f) continue;
|
|
780
|
+
|
|
781
|
+
float qx = src_x + t * rx;
|
|
782
|
+
float qy = src_y + t * ry;
|
|
783
|
+
float qz = src_z + t * rz;
|
|
784
|
+
|
|
785
|
+
float rel_x = qx - det_cx;
|
|
786
|
+
float rel_y = qy - det_cy;
|
|
787
|
+
float rel_z = qz - det_cz;
|
|
788
|
+
float u0 = rel_x * u_vec_x + rel_y * u_vec_y + rel_z * u_vec_z;
|
|
789
|
+
float v0 = rel_x * v_vec_x + rel_y * v_vec_y + rel_z * v_vec_z;
|
|
790
|
+
|
|
791
|
+
float ru = rx * u_vec_x + ry * u_vec_y + rz * u_vec_z;
|
|
792
|
+
float rv = rx * v_vec_x + ry * v_vec_y + rz * v_vec_z;
|
|
793
|
+
float inv_denom = 1.0f / denom;
|
|
794
|
+
|
|
795
|
+
float grad_ux = t * u_vec_x - t * ru * inv_denom * n_x;
|
|
796
|
+
float grad_uy = t * u_vec_y - t * ru * inv_denom * n_y;
|
|
797
|
+
float grad_uz = t * u_vec_z - t * ru * inv_denom * n_z;
|
|
798
|
+
|
|
799
|
+
float grad_vx = t * v_vec_x - t * rv * inv_denom * n_x;
|
|
800
|
+
float grad_vy = t * v_vec_y - t * rv * inv_denom * n_y;
|
|
801
|
+
float grad_vz = t * v_vec_z - t * rv * inv_denom * n_z;
|
|
802
|
+
|
|
803
|
+
float half_u = 0.5f * voxel_spacing * (
|
|
804
|
+
metal::abs(grad_ux) + metal::abs(grad_uy) + metal::abs(grad_uz)
|
|
805
|
+
);
|
|
806
|
+
float half_v = 0.5f * voxel_spacing * (
|
|
807
|
+
metal::abs(grad_vx) + metal::abs(grad_vy) + metal::abs(grad_vz)
|
|
808
|
+
);
|
|
809
|
+
half_u = metal::max(half_u, 0.5f * du);
|
|
810
|
+
half_v = metal::max(half_v, 0.5f * dv);
|
|
811
|
+
|
|
812
|
+
float width_u = metal::max(2.0f * half_u, du);
|
|
813
|
+
float width_v = metal::max(2.0f * half_v, dv);
|
|
814
|
+
|
|
815
|
+
float support_u = half_u + 0.5f * du;
|
|
816
|
+
float support_v = half_v + 0.5f * dv;
|
|
817
|
+
|
|
818
|
+
int iu_min = (int)metal::floor((u0 - support_u) / du + center_u);
|
|
819
|
+
int iu_max = (int)metal::ceil((u0 + support_u) / du + center_u);
|
|
820
|
+
int iv_min = (int)metal::floor((v0 - support_v) / dv + center_v);
|
|
821
|
+
int iv_max = (int)metal::ceil((v0 + support_v) / dv + center_v);
|
|
822
|
+
|
|
823
|
+
iu_min = metal::max(0, iu_min);
|
|
824
|
+
iv_min = metal::max(0, iv_min);
|
|
825
|
+
iu_max = metal::min(n_u - 1, iu_max);
|
|
826
|
+
iv_max = metal::min(n_v - 1, iv_max);
|
|
827
|
+
|
|
828
|
+
float fp_u_lo = u0 - half_u;
|
|
829
|
+
float fp_u_hi = u0 + half_u;
|
|
830
|
+
float fp_v_lo = v0 - half_v;
|
|
831
|
+
float fp_v_hi = v0 + half_v;
|
|
832
|
+
|
|
833
|
+
for (int iu = iu_min; iu <= iu_max; ++iu) {
|
|
834
|
+
float pixel_u = ((float)iu - center_u) * du;
|
|
835
|
+
float pixel_u_lo = pixel_u - 0.5f * du;
|
|
836
|
+
float pixel_u_hi = pixel_u + 0.5f * du;
|
|
837
|
+
float overlap_u = metal::min(pixel_u_hi, fp_u_hi) - metal::max(pixel_u_lo, fp_u_lo);
|
|
838
|
+
if (overlap_u <= eps) continue;
|
|
839
|
+
float wu = overlap_u / width_u;
|
|
840
|
+
|
|
841
|
+
for (int iv = iv_min; iv <= iv_max; ++iv) {
|
|
842
|
+
float pixel_v = ((float)iv - center_v) * dv;
|
|
843
|
+
float pixel_v_lo = pixel_v - 0.5f * dv;
|
|
844
|
+
float pixel_v_hi = pixel_v + 0.5f * dv;
|
|
845
|
+
float overlap_v = metal::min(pixel_v_hi, fp_v_hi) - metal::max(pixel_v_lo, fp_v_lo);
|
|
846
|
+
if (overlap_v <= eps) continue;
|
|
847
|
+
float wv = overlap_v / width_v;
|
|
848
|
+
accum += sino[iview * n_u * n_v + iu * n_v + iv] * wu * wv * voxel_spacing;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
grad_sparse[(int)isample] = accum;
|
|
854
|
+
"""
|
|
855
|
+
|
|
856
|
+
cone_3d_footprint_backward_sparse_kernel = mx.fast.metal_kernel(
|
|
857
|
+
name="cone_3d_footprint_backward_sparse",
|
|
858
|
+
input_names=[
|
|
859
|
+
"sino",
|
|
860
|
+
"src_pos",
|
|
861
|
+
"det_center_arr",
|
|
862
|
+
"det_u_vec_arr",
|
|
863
|
+
"det_v_vec_arr",
|
|
864
|
+
"indices",
|
|
865
|
+
"sparse_params",
|
|
866
|
+
"params",
|
|
867
|
+
"fparams",
|
|
868
|
+
],
|
|
869
|
+
output_names=["grad_sparse"],
|
|
870
|
+
source=_CONE_3D_FOOTPRINT_BACKWARD_SPARSE_SOURCE,
|
|
871
|
+
)
|
|
872
|
+
|
|
873
|
+
# ============================================================================
|
|
874
|
+
# 3D Cone Beam Analytical Geometry Gradient Kernel
|
|
875
|
+
#
|
|
876
|
+
# Computes VJP of cone_forward w.r.t. src_pos, det_center, det_u_vec,
|
|
877
|
+
# det_v_vec analytically via the Reynolds-transport gradient of the
|
|
878
|
+
# Siddon ray integral.
|
|
879
|
+
#
|
|
880
|
+
# Derivation (voxel-space parametrisation, λ = t/L where L = ray length):
|
|
881
|
+
# a_p = voxel_spacing * Σ_seg μ(x(t_mid)) * seg_len
|
|
882
|
+
# ∂a_p/∂s_mm = −d̂ · A/L + G1 (d̂ = unit ray dir, A = Σ μ*seg_len)
|
|
883
|
+
# ∂a_p/∂p_mm = +d̂ · A/L + G2 (p = detector pixel world position)
|
|
884
|
+
# G1 = Σ seg_len * (1−λ_mid) * ∇μ_vox(x_mid)
|
|
885
|
+
# G2 = Σ seg_len * λ_mid * ∇μ_vox(x_mid)
|
|
886
|
+
# Chain rule then yields det_center / det_u_vec / det_v_vec gradients from
|
|
887
|
+
# ∂a_p/∂p_mm via p = det_center + u_off_mm*u_vec + v_off_mm*v_vec.
|
|
888
|
+
# ============================================================================
|
|
889
|
+
|
|
890
|
+
_CONE_3D_GEOMETRY_GRAD_SOURCE = """
|
|
891
|
+
uint iview = thread_position_in_grid.x;
|
|
892
|
+
uint iu = thread_position_in_grid.y;
|
|
893
|
+
uint iv = thread_position_in_grid.z;
|
|
894
|
+
|
|
895
|
+
int n_views = params[0];
|
|
896
|
+
int n_u = params[1];
|
|
897
|
+
int n_v = params[2];
|
|
898
|
+
int Nx = params[3];
|
|
899
|
+
int Ny = params[4];
|
|
900
|
+
int Nz = params[5];
|
|
901
|
+
|
|
902
|
+
float du = fparams[0];
|
|
903
|
+
float dv = fparams[1];
|
|
904
|
+
float cx = fparams[2];
|
|
905
|
+
float cy = fparams[3];
|
|
906
|
+
float cz = fparams[4];
|
|
907
|
+
float voxel_spacing = fparams[5];
|
|
908
|
+
|
|
909
|
+
if ((int)iview >= n_views || (int)iu >= n_u || (int)iv >= n_v) return;
|
|
910
|
+
|
|
911
|
+
float g = cotangent[iview * n_u * n_v + iu * n_v + iv];
|
|
912
|
+
if (g == 0.0f) return;
|
|
913
|
+
|
|
914
|
+
float eps = """ + _EPSILON_STR + """;
|
|
915
|
+
|
|
916
|
+
// === GEOMETRY SETUP (identical to forward kernel) ===
|
|
917
|
+
float src_x = src_pos[iview * 3 + 0] / voxel_spacing;
|
|
918
|
+
float src_y = src_pos[iview * 3 + 1] / voxel_spacing;
|
|
919
|
+
float src_z = src_pos[iview * 3 + 2] / voxel_spacing;
|
|
920
|
+
|
|
921
|
+
float det_cx = det_center[iview * 3 + 0] / voxel_spacing;
|
|
922
|
+
float det_cy = det_center[iview * 3 + 1] / voxel_spacing;
|
|
923
|
+
float det_cz = det_center[iview * 3 + 2] / voxel_spacing;
|
|
924
|
+
|
|
925
|
+
float u_vec_x = det_u_vec_arr[iview * 3 + 0];
|
|
926
|
+
float u_vec_y = det_u_vec_arr[iview * 3 + 1];
|
|
927
|
+
float u_vec_z = det_u_vec_arr[iview * 3 + 2];
|
|
928
|
+
|
|
929
|
+
float v_vec_x = det_v_vec_arr[iview * 3 + 0];
|
|
930
|
+
float v_vec_y = det_v_vec_arr[iview * 3 + 1];
|
|
931
|
+
float v_vec_z = det_v_vec_arr[iview * 3 + 2];
|
|
932
|
+
|
|
933
|
+
// Detector pixel offsets: voxel-space for ray, mm for chain-rule
|
|
934
|
+
float center_u = ((float)n_u - 1.0f) * 0.5f;
|
|
935
|
+
float center_v = ((float)n_v - 1.0f) * 0.5f;
|
|
936
|
+
float u_off_vox = ((float)iu - center_u) * du / voxel_spacing;
|
|
937
|
+
float v_off_vox = ((float)iv - center_v) * dv / voxel_spacing;
|
|
938
|
+
float u_off_mm = ((float)iu - center_u) * du;
|
|
939
|
+
float v_off_mm = ((float)iv - center_v) * dv;
|
|
940
|
+
|
|
941
|
+
float det_x = det_cx + u_off_vox * u_vec_x + v_off_vox * v_vec_x;
|
|
942
|
+
float det_y = det_cy + u_off_vox * u_vec_y + v_off_vox * v_vec_y;
|
|
943
|
+
float det_z = det_cz + u_off_vox * u_vec_z + v_off_vox * v_vec_z;
|
|
944
|
+
|
|
945
|
+
// === RAY DIRECTION ===
|
|
946
|
+
float dir_x = det_x - src_x;
|
|
947
|
+
float dir_y = det_y - src_y;
|
|
948
|
+
float dir_z = det_z - src_z;
|
|
949
|
+
float length = metal::sqrt(dir_x*dir_x + dir_y*dir_y + dir_z*dir_z);
|
|
950
|
+
if (length < eps) return;
|
|
951
|
+
float inv_len = 1.0f / length;
|
|
952
|
+
dir_x *= inv_len;
|
|
953
|
+
dir_y *= inv_len;
|
|
954
|
+
dir_z *= inv_len;
|
|
955
|
+
|
|
956
|
+
// === RAY-VOLUME INTERSECTION ===
|
|
957
|
+
float t_min = -""" + _INF_STR + """;
|
|
958
|
+
float t_max = """ + _INF_STR + """;
|
|
959
|
+
|
|
960
|
+
if (metal::abs(dir_x) > eps) {
|
|
961
|
+
float tx1 = (-cx - src_x) / dir_x;
|
|
962
|
+
float tx2 = ( cx - src_x) / dir_x;
|
|
963
|
+
t_min = metal::max(t_min, metal::min(tx1, tx2));
|
|
964
|
+
t_max = metal::min(t_max, metal::max(tx1, tx2));
|
|
965
|
+
} else if (src_x < -cx || src_x > cx) { return; }
|
|
966
|
+
|
|
967
|
+
if (metal::abs(dir_y) > eps) {
|
|
968
|
+
float ty1 = (-cy - src_y) / dir_y;
|
|
969
|
+
float ty2 = ( cy - src_y) / dir_y;
|
|
970
|
+
t_min = metal::max(t_min, metal::min(ty1, ty2));
|
|
971
|
+
t_max = metal::min(t_max, metal::max(ty1, ty2));
|
|
972
|
+
} else if (src_y < -cy || src_y > cy) { return; }
|
|
973
|
+
|
|
974
|
+
if (metal::abs(dir_z) > eps) {
|
|
975
|
+
float tz1 = (-cz - src_z) / dir_z;
|
|
976
|
+
float tz2 = ( cz - src_z) / dir_z;
|
|
977
|
+
t_min = metal::max(t_min, metal::min(tz1, tz2));
|
|
978
|
+
t_max = metal::min(t_max, metal::max(tz1, tz2));
|
|
979
|
+
} else if (src_z < -cz || src_z > cz) { return; }
|
|
980
|
+
|
|
981
|
+
if (t_min >= t_max) return;
|
|
982
|
+
|
|
983
|
+
// === SIDDON TRAVERSAL WITH G1/G2 ACCUMULATORS ===
|
|
984
|
+
float A = 0.0f;
|
|
985
|
+
float G1x = 0.0f, G1y = 0.0f, G1z = 0.0f;
|
|
986
|
+
float G2x = 0.0f, G2y = 0.0f, G2z = 0.0f;
|
|
987
|
+
|
|
988
|
+
float t = t_min;
|
|
989
|
+
int ix = (int)metal::floor(src_x + t * dir_x + cx);
|
|
990
|
+
int iy = (int)metal::floor(src_y + t * dir_y + cy);
|
|
991
|
+
int iz = (int)metal::floor(src_z + t * dir_z + cz);
|
|
992
|
+
|
|
993
|
+
int step_x = (dir_x >= 0.0f) ? 1 : -1;
|
|
994
|
+
int step_y = (dir_y >= 0.0f) ? 1 : -1;
|
|
995
|
+
int step_z = (dir_z >= 0.0f) ? 1 : -1;
|
|
996
|
+
|
|
997
|
+
float inv_dir_x = (metal::abs(dir_x) > eps) ? (1.0f / dir_x) : 0.0f;
|
|
998
|
+
float inv_dir_y = (metal::abs(dir_y) > eps) ? (1.0f / dir_y) : 0.0f;
|
|
999
|
+
float inv_dir_z = (metal::abs(dir_z) > eps) ? (1.0f / dir_z) : 0.0f;
|
|
1000
|
+
float dt_x = (metal::abs(dir_x) > eps) ? metal::abs(inv_dir_x) : """ + _INF_STR + """;
|
|
1001
|
+
float dt_y = (metal::abs(dir_y) > eps) ? metal::abs(inv_dir_y) : """ + _INF_STR + """;
|
|
1002
|
+
float dt_z = (metal::abs(dir_z) > eps) ? metal::abs(inv_dir_z) : """ + _INF_STR + """;
|
|
1003
|
+
|
|
1004
|
+
float txn = (metal::abs(dir_x) > eps) ? ((float)(ix + (step_x > 0 ? 1 : 0)) - cx - src_x) * inv_dir_x : """ + _INF_STR + """;
|
|
1005
|
+
float tyn = (metal::abs(dir_y) > eps) ? ((float)(iy + (step_y > 0 ? 1 : 0)) - cy - src_y) * inv_dir_y : """ + _INF_STR + """;
|
|
1006
|
+
float tzn = (metal::abs(dir_z) > eps) ? ((float)(iz + (step_z > 0 ? 1 : 0)) - cz - src_z) * inv_dir_z : """ + _INF_STR + """;
|
|
1007
|
+
|
|
1008
|
+
int yz_stride = Ny * Nz;
|
|
1009
|
+
|
|
1010
|
+
while (t < t_max) {
|
|
1011
|
+
if (ix >= 0 && ix < Nx && iy >= 0 && iy < Ny && iz >= 0 && iz < Nz) {
|
|
1012
|
+
float t_next = metal::min(metal::min(metal::min(txn, tyn), tzn), t_max);
|
|
1013
|
+
float seg_len = t_next - t;
|
|
1014
|
+
|
|
1015
|
+
if (seg_len > eps) {
|
|
1016
|
+
float t_mid = t + seg_len * 0.5f;
|
|
1017
|
+
float mid_x = src_x + t_mid * dir_x + cx;
|
|
1018
|
+
float mid_y = src_y + t_mid * dir_y + cy;
|
|
1019
|
+
float mid_z = src_z + t_mid * dir_z + cz;
|
|
1020
|
+
|
|
1021
|
+
int ix0 = (int)metal::floor(mid_x);
|
|
1022
|
+
int iy0 = (int)metal::floor(mid_y);
|
|
1023
|
+
int iz0 = (int)metal::floor(mid_z);
|
|
1024
|
+
float dx = mid_x - (float)ix0;
|
|
1025
|
+
float dy = mid_y - (float)iy0;
|
|
1026
|
+
float dz = mid_z - (float)iz0;
|
|
1027
|
+
|
|
1028
|
+
ix0 = metal::max(0, metal::min(ix0, Nx - 2));
|
|
1029
|
+
iy0 = metal::max(0, metal::min(iy0, Ny - 2));
|
|
1030
|
+
iz0 = metal::max(0, metal::min(iz0, Nz - 2));
|
|
1031
|
+
|
|
1032
|
+
float omdx = 1.0f - dx;
|
|
1033
|
+
float omdy = 1.0f - dy;
|
|
1034
|
+
float omdz = 1.0f - dz;
|
|
1035
|
+
|
|
1036
|
+
int base = ix0 * yz_stride + iy0 * Nz + iz0;
|
|
1037
|
+
|
|
1038
|
+
// Trilinear voxel values (same as forward kernel)
|
|
1039
|
+
float v000 = vol[base];
|
|
1040
|
+
float v100 = vol[base + yz_stride];
|
|
1041
|
+
float v010 = vol[base + Nz];
|
|
1042
|
+
float v001 = vol[base + 1];
|
|
1043
|
+
float v110 = vol[base + yz_stride + Nz];
|
|
1044
|
+
float v101 = vol[base + yz_stride + 1];
|
|
1045
|
+
float v011 = vol[base + Nz + 1];
|
|
1046
|
+
float v111 = vol[base + yz_stride + Nz + 1];
|
|
1047
|
+
|
|
1048
|
+
float val = v000 * omdx*omdy*omdz + v100 * dx*omdy*omdz
|
|
1049
|
+
+ v010 * omdx*dy*omdz + v001 * omdx*omdy*dz
|
|
1050
|
+
+ v110 * dx*dy*omdz + v101 * dx*omdy*dz
|
|
1051
|
+
+ v011 * omdx*dy*dz + v111 * dx*dy*dz;
|
|
1052
|
+
|
|
1053
|
+
A += val * seg_len;
|
|
1054
|
+
|
|
1055
|
+
// Trilinear gradient of μ in kernel (voxel-index) space
|
|
1056
|
+
float dmu_x = omdy*omdz*(v100-v000) + dy*omdz*(v110-v010)
|
|
1057
|
+
+ omdy*dz*(v101-v001) + dy*dz*(v111-v011);
|
|
1058
|
+
float dmu_y = omdx*omdz*(v010-v000) + dx*omdz*(v110-v100)
|
|
1059
|
+
+ omdx*dz*(v011-v001) + dx*dz*(v111-v101);
|
|
1060
|
+
float dmu_z = omdx*omdy*(v001-v000) + dx*omdy*(v101-v100)
|
|
1061
|
+
+ omdx*dy*(v011-v010) + dx*dy*(v111-v110);
|
|
1062
|
+
|
|
1063
|
+
// λ = t_mid / L; weights for source-end and detector-end
|
|
1064
|
+
float lam = t_mid * inv_len;
|
|
1065
|
+
float w1 = seg_len * (1.0f - lam);
|
|
1066
|
+
float w2 = seg_len * lam;
|
|
1067
|
+
|
|
1068
|
+
G1x += w1 * dmu_x; G1y += w1 * dmu_y; G1z += w1 * dmu_z;
|
|
1069
|
+
G2x += w2 * dmu_x; G2y += w2 * dmu_y; G2z += w2 * dmu_z;
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
if (txn <= tyn && txn <= tzn) {
|
|
1074
|
+
t = txn; ix += step_x; txn += dt_x;
|
|
1075
|
+
} else if (tyn <= txn && tyn <= tzn) {
|
|
1076
|
+
t = tyn; iy += step_y; tyn += dt_y;
|
|
1077
|
+
} else {
|
|
1078
|
+
t = tzn; iz += step_z; tzn += dt_z;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// === ASSEMBLE GEOMETRY GRADIENTS ===
|
|
1083
|
+
//
|
|
1084
|
+
// ∂a_p/∂s_mm = −d̂ · A/L + G1 (source position, world mm)
|
|
1085
|
+
// ∂a_p/∂p_mm = +d̂ · A/L + G2 (detector pixel, world mm)
|
|
1086
|
+
//
|
|
1087
|
+
// d̂ = (dir_x, dir_y, dir_z) — same unit vector in voxel and world space
|
|
1088
|
+
// (voxel_spacing cancels: d̂_vox = d̂_mm for uniform scaling)
|
|
1089
|
+
float A_over_L = A * inv_len;
|
|
1090
|
+
|
|
1091
|
+
float grad_sx = g * (-dir_x * A_over_L + G1x);
|
|
1092
|
+
float grad_sy = g * (-dir_y * A_over_L + G1y);
|
|
1093
|
+
float grad_sz = g * (-dir_z * A_over_L + G1z);
|
|
1094
|
+
|
|
1095
|
+
float grad_px = g * ( dir_x * A_over_L + G2x);
|
|
1096
|
+
float grad_py = g * ( dir_y * A_over_L + G2y);
|
|
1097
|
+
float grad_pz = g * ( dir_z * A_over_L + G2z);
|
|
1098
|
+
|
|
1099
|
+
// grad_src_pos (per view)
|
|
1100
|
+
atomic_fetch_add_explicit(&grad_src_pos[iview*3+0], grad_sx, memory_order_relaxed);
|
|
1101
|
+
atomic_fetch_add_explicit(&grad_src_pos[iview*3+1], grad_sy, memory_order_relaxed);
|
|
1102
|
+
atomic_fetch_add_explicit(&grad_src_pos[iview*3+2], grad_sz, memory_order_relaxed);
|
|
1103
|
+
|
|
1104
|
+
// grad_det_center = grad_p (∂p_mm/∂det_center_mm = I)
|
|
1105
|
+
atomic_fetch_add_explicit(&grad_det_center[iview*3+0], grad_px, memory_order_relaxed);
|
|
1106
|
+
atomic_fetch_add_explicit(&grad_det_center[iview*3+1], grad_py, memory_order_relaxed);
|
|
1107
|
+
atomic_fetch_add_explicit(&grad_det_center[iview*3+2], grad_pz, memory_order_relaxed);
|
|
1108
|
+
|
|
1109
|
+
// grad_det_u_vec = u_off_mm * grad_p (∂p_mm/∂u_vec = u_off_mm·I)
|
|
1110
|
+
atomic_fetch_add_explicit(&grad_det_u_vec[iview*3+0], u_off_mm * grad_px, memory_order_relaxed);
|
|
1111
|
+
atomic_fetch_add_explicit(&grad_det_u_vec[iview*3+1], u_off_mm * grad_py, memory_order_relaxed);
|
|
1112
|
+
atomic_fetch_add_explicit(&grad_det_u_vec[iview*3+2], u_off_mm * grad_pz, memory_order_relaxed);
|
|
1113
|
+
|
|
1114
|
+
// grad_det_v_vec = v_off_mm * grad_p (∂p_mm/∂v_vec = v_off_mm·I)
|
|
1115
|
+
atomic_fetch_add_explicit(&grad_det_v_vec[iview*3+0], v_off_mm * grad_px, memory_order_relaxed);
|
|
1116
|
+
atomic_fetch_add_explicit(&grad_det_v_vec[iview*3+1], v_off_mm * grad_py, memory_order_relaxed);
|
|
1117
|
+
atomic_fetch_add_explicit(&grad_det_v_vec[iview*3+2], v_off_mm * grad_pz, memory_order_relaxed);
|
|
1118
|
+
"""
|
|
1119
|
+
|
|
1120
|
+
cone_3d_geometry_grad_kernel = mx.fast.metal_kernel(
|
|
1121
|
+
name="cone_3d_geometry_grad",
|
|
1122
|
+
input_names=["vol", "cotangent", "src_pos", "det_center", "det_u_vec_arr", "det_v_vec_arr", "params", "fparams"],
|
|
1123
|
+
output_names=["grad_src_pos", "grad_det_center", "grad_det_u_vec", "grad_det_v_vec"],
|
|
1124
|
+
source=_CONE_3D_GEOMETRY_GRAD_SOURCE,
|
|
1125
|
+
atomic_outputs=True,
|
|
1126
|
+
)
|
|
@@ -5,6 +5,7 @@ functions using custom Metal kernels on Apple Silicon, with VJP (vector-Jacobian
|
|
|
5
5
|
product) support for gradient computation via ``mx.custom_function``.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
+
import os
|
|
8
9
|
from functools import lru_cache
|
|
9
10
|
|
|
10
11
|
import numpy as np
|
|
@@ -25,14 +26,52 @@ from .kernels import (
|
|
|
25
26
|
cone_3d_backward_kernel,
|
|
26
27
|
cone_3d_footprint_forward_kernel,
|
|
27
28
|
cone_3d_footprint_backward_kernel,
|
|
29
|
+
cone_3d_footprint_backward_sparse_kernel,
|
|
30
|
+
cone_3d_geometry_grad_kernel,
|
|
28
31
|
)
|
|
29
32
|
|
|
33
|
+
# Set DIFFCT_GEOMETRY_VJP=1 to use the analytical geometry gradient kernel
|
|
34
|
+
# instead of the finite-difference fallback for cone_forward.
|
|
35
|
+
_GEOMETRY_VJP_ENABLED: bool = os.getenv("DIFFCT_GEOMETRY_VJP", "0") == "1"
|
|
36
|
+
|
|
30
37
|
|
|
31
38
|
def _as_mx_float_array(value):
|
|
32
39
|
"""Accept NumPy or MLX arrays and return an MLX float array."""
|
|
33
40
|
return mx.array(value, dtype=_MX_DTYPE)
|
|
34
41
|
|
|
35
42
|
|
|
43
|
+
def _normalize_sparse_indices(indices, D, H, W):
|
|
44
|
+
"""Validate sparse backprojection indices and return an ``int32`` vector."""
|
|
45
|
+
if indices is None:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
indices = np.asarray(indices)
|
|
49
|
+
if indices.ndim != 1:
|
|
50
|
+
raise ValueError("indices must be a 1D array of flat voxel indices.")
|
|
51
|
+
if not np.issubdtype(indices.dtype, np.integer):
|
|
52
|
+
raise TypeError("indices must contain integer values.")
|
|
53
|
+
|
|
54
|
+
total_voxels = int(D) * int(H) * int(W)
|
|
55
|
+
if total_voxels > np.iinfo(np.int32).max:
|
|
56
|
+
raise ValueError("Sparse backprojection currently supports at most int32-addressable volumes.")
|
|
57
|
+
|
|
58
|
+
if np.any(indices < 0):
|
|
59
|
+
raise ValueError("indices contains negative values.")
|
|
60
|
+
if np.any(indices >= total_voxels):
|
|
61
|
+
raise ValueError("indices contains out of bounds values.")
|
|
62
|
+
if np.unique(indices).size != indices.size:
|
|
63
|
+
raise ValueError("indices contains duplicate values.")
|
|
64
|
+
|
|
65
|
+
return indices.astype(np.int32, copy=False)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _scatter_sparse_cotangent(cotangent, indices, D, H, W):
|
|
69
|
+
"""Expand a sparse cotangent vector into the dense ``(D, H, W)`` volume layout."""
|
|
70
|
+
dense = np.zeros(int(D) * int(H) * int(W), dtype=np.float32)
|
|
71
|
+
dense[indices] = np.asarray(cotangent, dtype=np.float32).reshape(-1)
|
|
72
|
+
return mx.array(dense.reshape(int(D), int(H), int(W)), dtype=_MX_DTYPE)
|
|
73
|
+
|
|
74
|
+
|
|
36
75
|
@lru_cache(maxsize=32)
|
|
37
76
|
def _projector_params_2d(
|
|
38
77
|
n_ang: int,
|
|
@@ -700,6 +739,68 @@ def fan_backward_footprint_vjp(primals, cotangent, _):
|
|
|
700
739
|
# 3D Cone Beam
|
|
701
740
|
# ============================================================================
|
|
702
741
|
|
|
742
|
+
#: Perturbation step (in the same length unit as src_pos, typically mm) used
|
|
743
|
+
#: for the finite-difference source-position VJP. A value of ~0.5 mm gives
|
|
744
|
+
#: good accuracy for source-to-isocenter distances in the 100–1000 mm range.
|
|
745
|
+
_FD_EPS_SRC: float = 0.5
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _src_pos_grad_fd(
|
|
749
|
+
volume, src_pos, det_center, det_u_vec, det_v_vec,
|
|
750
|
+
det_u, det_v, du, dv, voxel_spacing,
|
|
751
|
+
cotangent,
|
|
752
|
+
eps: float = _FD_EPS_SRC,
|
|
753
|
+
) -> "mx.array":
|
|
754
|
+
"""Finite-difference VJP for *src_pos* in cone-beam forward projection.
|
|
755
|
+
|
|
756
|
+
Uses 6 forward passes (±ε per spatial axis) to approximate
|
|
757
|
+
``cotangent^T · ∂F/∂src_pos``. Because each view's projection depends
|
|
758
|
+
only on that view's source position, all views can be perturbed
|
|
759
|
+
simultaneously with the same Δ, giving the correct per-view gradient
|
|
760
|
+
without any extra passes per additional view.
|
|
761
|
+
|
|
762
|
+
Parameters
|
|
763
|
+
----------
|
|
764
|
+
cotangent : mx.array, shape ``(n_views, det_u, det_v)``
|
|
765
|
+
Upstream gradient from the objective.
|
|
766
|
+
eps : float
|
|
767
|
+
Finite-difference step size in the same units as *src_pos*.
|
|
768
|
+
|
|
769
|
+
Returns
|
|
770
|
+
-------
|
|
771
|
+
grad_src_pos : mx.array, shape ``(n_views, 3)``
|
|
772
|
+
"""
|
|
773
|
+
# Convert all inputs to plain MLX arrays to detach them from any autograd
|
|
774
|
+
# tape that may be active in the calling context (second-order
|
|
775
|
+
# differentiation is not desired here).
|
|
776
|
+
volume = _as_mx_float_array(volume)
|
|
777
|
+
src_pos = _as_mx_float_array(src_pos)
|
|
778
|
+
det_center = _as_mx_float_array(det_center)
|
|
779
|
+
det_u_vec = _as_mx_float_array(det_u_vec)
|
|
780
|
+
det_v_vec = _as_mx_float_array(det_v_vec)
|
|
781
|
+
cotangent = _as_mx_float_array(cotangent)
|
|
782
|
+
|
|
783
|
+
grads = []
|
|
784
|
+
for j in range(3):
|
|
785
|
+
delta_list = [[0.0, 0.0, 0.0]]
|
|
786
|
+
delta_list[0][j] = eps
|
|
787
|
+
delta = mx.array(delta_list, dtype=src_pos.dtype) # (1, 3) — broadcast
|
|
788
|
+
|
|
789
|
+
f_plus = _cone_forward_impl(
|
|
790
|
+
volume, src_pos + delta, det_center, det_u_vec, det_v_vec,
|
|
791
|
+
det_u, det_v, du, dv, voxel_spacing,
|
|
792
|
+
)
|
|
793
|
+
f_minus = _cone_forward_impl(
|
|
794
|
+
volume, src_pos - delta, det_center, det_u_vec, det_v_vec,
|
|
795
|
+
det_u, det_v, du, dv, voxel_spacing,
|
|
796
|
+
)
|
|
797
|
+
# Directional derivative w.r.t. src_pos[:, j]; shape (n_views, det_u, det_v)
|
|
798
|
+
df_dxj = (f_plus - f_minus) / (2.0 * eps)
|
|
799
|
+
# Chain rule: sum cotangent * df_dxj over the detector pixels per view
|
|
800
|
+
grads.append(mx.sum(cotangent * df_dxj, axis=(1, 2))) # (n_views,)
|
|
801
|
+
|
|
802
|
+
return mx.stack(grads, axis=-1) # (n_views, 3)
|
|
803
|
+
|
|
703
804
|
def _cone_forward_impl(volume, src_pos, det_center, det_u_vec, det_v_vec,
|
|
704
805
|
det_u, det_v, du, dv, voxel_spacing=1.0):
|
|
705
806
|
"""Raw cone beam forward projection."""
|
|
@@ -797,6 +898,54 @@ def _cone_backward_impl(sinogram, src_pos, det_center, det_u_vec, det_v_vec,
|
|
|
797
898
|
return mx.array(vol)
|
|
798
899
|
|
|
799
900
|
|
|
901
|
+
def _cone_geometry_grad_impl(
|
|
902
|
+
volume, cotangent, src_pos, det_center, det_u_vec, det_v_vec,
|
|
903
|
+
det_u, det_v, du, dv, voxel_spacing=1.0
|
|
904
|
+
):
|
|
905
|
+
"""Analytical VJP of cone_forward w.r.t. src_pos, det_center, det_u_vec, det_v_vec.
|
|
906
|
+
|
|
907
|
+
Returns
|
|
908
|
+
-------
|
|
909
|
+
grad_src_pos : ``(n_views, 3)``
|
|
910
|
+
grad_det_center : ``(n_views, 3)``
|
|
911
|
+
grad_det_u_vec : ``(n_views, 3)``
|
|
912
|
+
grad_det_v_vec : ``(n_views, 3)``
|
|
913
|
+
"""
|
|
914
|
+
volume = _as_mx_float_array(volume)
|
|
915
|
+
cotangent = _as_mx_float_array(cotangent)
|
|
916
|
+
src_pos = _as_mx_float_array(src_pos)
|
|
917
|
+
det_center = _as_mx_float_array(det_center)
|
|
918
|
+
det_u_vec = _as_mx_float_array(det_u_vec)
|
|
919
|
+
det_v_vec = _as_mx_float_array(det_v_vec)
|
|
920
|
+
|
|
921
|
+
D, H, W = volume.shape
|
|
922
|
+
n_views = src_pos.shape[0]
|
|
923
|
+
n_u, n_v = int(det_u), int(det_v)
|
|
924
|
+
|
|
925
|
+
# Same WHD permutation as the forward kernel
|
|
926
|
+
volume_perm = mx.array(mx.transpose(volume, axes=(2, 1, 0)))
|
|
927
|
+
Nx, Ny, Nz = W, H, D
|
|
928
|
+
|
|
929
|
+
params, fparams = _projector_params_3d(
|
|
930
|
+
n_views, n_u, n_v, Nx, Ny, Nz,
|
|
931
|
+
float(du), float(dv),
|
|
932
|
+
float(Nx * 0.5), float(Ny * 0.5), float(Nz * 0.5),
|
|
933
|
+
float(voxel_spacing),
|
|
934
|
+
)
|
|
935
|
+
|
|
936
|
+
grid, tg = _grid_3d(n_views, n_u, n_v)
|
|
937
|
+
|
|
938
|
+
outputs = cone_3d_geometry_grad_kernel(
|
|
939
|
+
inputs=[volume_perm, cotangent, src_pos, det_center, det_u_vec, det_v_vec, params, fparams],
|
|
940
|
+
output_shapes=[(n_views, 3), (n_views, 3), (n_views, 3), (n_views, 3)],
|
|
941
|
+
output_dtypes=[_MX_DTYPE, _MX_DTYPE, _MX_DTYPE, _MX_DTYPE],
|
|
942
|
+
grid=grid,
|
|
943
|
+
threadgroup=tg,
|
|
944
|
+
init_value=0,
|
|
945
|
+
)
|
|
946
|
+
return outputs[0], outputs[1], outputs[2], outputs[3]
|
|
947
|
+
|
|
948
|
+
|
|
800
949
|
def _cone_forward_footprint_impl(volume, src_pos, det_center, det_u_vec, det_v_vec,
|
|
801
950
|
det_u, det_v, du, dv, voxel_spacing=1.0):
|
|
802
951
|
"""Approximate separable-footprint cone-beam forward projector."""
|
|
@@ -846,7 +995,7 @@ def _cone_forward_footprint_impl(volume, src_pos, det_center, det_u_vec, det_v_v
|
|
|
846
995
|
|
|
847
996
|
|
|
848
997
|
def _cone_backward_footprint_impl(sinogram, src_pos, det_center, det_u_vec, det_v_vec,
|
|
849
|
-
D, H, W, du, dv, voxel_spacing=1.0):
|
|
998
|
+
D, H, W, du, dv, voxel_spacing=1.0, indices=None):
|
|
850
999
|
"""Adjoint of the approximate separable-footprint cone-beam forward projector."""
|
|
851
1000
|
sinogram = _as_mx_float_array(sinogram)
|
|
852
1001
|
src_pos = _as_mx_float_array(src_pos)
|
|
@@ -856,6 +1005,7 @@ def _cone_backward_footprint_impl(sinogram, src_pos, det_center, det_u_vec, det_
|
|
|
856
1005
|
|
|
857
1006
|
n_views, n_u, n_v = sinogram.shape
|
|
858
1007
|
Nx, Ny, Nz = int(W), int(H), int(D)
|
|
1008
|
+
sparse_indices = _normalize_sparse_indices(indices, D, H, W)
|
|
859
1009
|
|
|
860
1010
|
cx = float(Nx * 0.5)
|
|
861
1011
|
cy = float(Ny * 0.5)
|
|
@@ -876,6 +1026,33 @@ def _cone_backward_footprint_impl(sinogram, src_pos, det_center, det_u_vec, det_
|
|
|
876
1026
|
float(voxel_spacing),
|
|
877
1027
|
)
|
|
878
1028
|
|
|
1029
|
+
if sparse_indices is not None:
|
|
1030
|
+
if sparse_indices.size == 0:
|
|
1031
|
+
return mx.zeros((0,), dtype=sinogram.dtype)
|
|
1032
|
+
|
|
1033
|
+
sparse_indices_mx = mx.array(sparse_indices, dtype=mx.int32)
|
|
1034
|
+
sparse_params = mx.array([int(sparse_indices.size)], dtype=mx.int32)
|
|
1035
|
+
grid, tg = _grid_3d(int(sparse_indices.size), 1, 1)
|
|
1036
|
+
|
|
1037
|
+
outputs = cone_3d_footprint_backward_sparse_kernel(
|
|
1038
|
+
inputs=[
|
|
1039
|
+
sinogram,
|
|
1040
|
+
src_pos,
|
|
1041
|
+
det_center,
|
|
1042
|
+
det_u_vec,
|
|
1043
|
+
det_v_vec,
|
|
1044
|
+
sparse_indices_mx,
|
|
1045
|
+
sparse_params,
|
|
1046
|
+
params,
|
|
1047
|
+
fparams,
|
|
1048
|
+
],
|
|
1049
|
+
output_shapes=[(int(sparse_indices.size),)],
|
|
1050
|
+
output_dtypes=[_MX_DTYPE],
|
|
1051
|
+
grid=grid,
|
|
1052
|
+
threadgroup=tg,
|
|
1053
|
+
)
|
|
1054
|
+
return outputs[0]
|
|
1055
|
+
|
|
879
1056
|
grid, tg = _grid_3d(Nx, Ny, Nz)
|
|
880
1057
|
|
|
881
1058
|
outputs = cone_3d_footprint_backward_kernel(
|
|
@@ -926,6 +1103,8 @@ def cone_forward(volume, src_pos, det_center, det_u_vec, det_v_vec,
|
|
|
926
1103
|
@cone_forward.vjp
|
|
927
1104
|
def cone_forward_vjp(primals, cotangent, _):
|
|
928
1105
|
volume, src_pos, det_center, det_u_vec, det_v_vec = primals[:5]
|
|
1106
|
+
det_u_int = int(primals[5]) if len(primals) > 5 else 128
|
|
1107
|
+
det_v_int = int(primals[6]) if len(primals) > 6 else 128
|
|
929
1108
|
du = primals[7] if len(primals) > 7 else 1.0
|
|
930
1109
|
dv = primals[8] if len(primals) > 8 else 1.0
|
|
931
1110
|
voxel_spacing = primals[9] if len(primals) > 9 else 1.0
|
|
@@ -935,9 +1114,26 @@ def cone_forward_vjp(primals, cotangent, _):
|
|
|
935
1114
|
cotangent, src_pos, det_center, det_u_vec, det_v_vec,
|
|
936
1115
|
D, H, W, du, dv, voxel_spacing
|
|
937
1116
|
)
|
|
1117
|
+
|
|
1118
|
+
if _GEOMETRY_VJP_ENABLED:
|
|
1119
|
+
grad_src_pos, grad_det_center, grad_det_u_vec, grad_det_v_vec = \
|
|
1120
|
+
_cone_geometry_grad_impl(
|
|
1121
|
+
volume, cotangent, src_pos, det_center, det_u_vec, det_v_vec,
|
|
1122
|
+
det_u_int, det_v_int, du, dv, voxel_spacing,
|
|
1123
|
+
)
|
|
1124
|
+
else:
|
|
1125
|
+
grad_src_pos = _src_pos_grad_fd(
|
|
1126
|
+
volume, src_pos, det_center, det_u_vec, det_v_vec,
|
|
1127
|
+
det_u_int, det_v_int, du, dv, voxel_spacing,
|
|
1128
|
+
cotangent,
|
|
1129
|
+
)
|
|
1130
|
+
grad_det_center = mx.zeros_like(det_center)
|
|
1131
|
+
grad_det_u_vec = mx.zeros_like(det_u_vec)
|
|
1132
|
+
grad_det_v_vec = mx.zeros_like(det_v_vec)
|
|
1133
|
+
|
|
938
1134
|
return (grad_volume,
|
|
939
|
-
|
|
940
|
-
|
|
1135
|
+
grad_src_pos, grad_det_center,
|
|
1136
|
+
grad_det_u_vec, grad_det_v_vec,
|
|
941
1137
|
None, None, None, None, None)
|
|
942
1138
|
|
|
943
1139
|
|
|
@@ -1014,6 +1210,8 @@ def cone_forward_footprint(volume, src_pos, det_center, det_u_vec, det_v_vec,
|
|
|
1014
1210
|
@cone_forward_footprint.vjp
|
|
1015
1211
|
def cone_forward_footprint_vjp(primals, cotangent, _):
|
|
1016
1212
|
volume, src_pos, det_center, det_u_vec, det_v_vec = primals[:5]
|
|
1213
|
+
det_u_int = int(primals[5]) if len(primals) > 5 else 128
|
|
1214
|
+
det_v_int = int(primals[6]) if len(primals) > 6 else 128
|
|
1017
1215
|
du = primals[7] if len(primals) > 7 else 1.0
|
|
1018
1216
|
dv = primals[8] if len(primals) > 8 else 1.0
|
|
1019
1217
|
voxel_spacing = primals[9] if len(primals) > 9 else 1.0
|
|
@@ -1032,16 +1230,27 @@ def cone_forward_footprint_vjp(primals, cotangent, _):
|
|
|
1032
1230
|
dv,
|
|
1033
1231
|
voxel_spacing,
|
|
1034
1232
|
)
|
|
1233
|
+
grad_src_pos = _src_pos_grad_fd(
|
|
1234
|
+
volume, src_pos, det_center, det_u_vec, det_v_vec,
|
|
1235
|
+
det_u_int, det_v_int, du, dv, voxel_spacing,
|
|
1236
|
+
cotangent,
|
|
1237
|
+
)
|
|
1035
1238
|
return (grad_volume,
|
|
1036
|
-
|
|
1239
|
+
grad_src_pos, mx.zeros_like(det_center),
|
|
1037
1240
|
mx.zeros_like(det_u_vec), mx.zeros_like(det_v_vec),
|
|
1038
1241
|
None, None, None, None, None)
|
|
1039
1242
|
|
|
1040
1243
|
|
|
1041
1244
|
@mx.custom_function
|
|
1042
1245
|
def cone_backward_footprint(sinogram, src_pos, det_center, det_u_vec, det_v_vec,
|
|
1043
|
-
D=128, H=128, W=128, du=1.0, dv=1.0, voxel_spacing=1.0
|
|
1044
|
-
|
|
1246
|
+
D=128, H=128, W=128, du=1.0, dv=1.0, voxel_spacing=1.0,
|
|
1247
|
+
indices=None):
|
|
1248
|
+
"""Adjoint of the matched voxel-footprint cone-beam forward projector.
|
|
1249
|
+
|
|
1250
|
+
When ``indices`` is provided, the operator evaluates only those flattened
|
|
1251
|
+
``(D, H, W)`` voxel locations and returns a 1D vector in the caller's
|
|
1252
|
+
requested order instead of the full dense volume.
|
|
1253
|
+
"""
|
|
1045
1254
|
return _cone_backward_footprint_impl(
|
|
1046
1255
|
sinogram,
|
|
1047
1256
|
src_pos,
|
|
@@ -1054,20 +1263,35 @@ def cone_backward_footprint(sinogram, src_pos, det_center, det_u_vec, det_v_vec,
|
|
|
1054
1263
|
du,
|
|
1055
1264
|
dv,
|
|
1056
1265
|
voxel_spacing,
|
|
1266
|
+
indices,
|
|
1057
1267
|
)
|
|
1058
1268
|
|
|
1059
1269
|
|
|
1060
1270
|
@cone_backward_footprint.vjp
|
|
1061
1271
|
def cone_backward_footprint_vjp(primals, cotangent, _):
|
|
1062
1272
|
sinogram, src_pos, det_center, det_u_vec, det_v_vec = primals[:5]
|
|
1273
|
+
D = int(primals[5]) if len(primals) > 5 else 128
|
|
1274
|
+
H = int(primals[6]) if len(primals) > 6 else 128
|
|
1275
|
+
W = int(primals[7]) if len(primals) > 7 else 128
|
|
1063
1276
|
det_u = int(sinogram.shape[1])
|
|
1064
1277
|
det_v = int(sinogram.shape[2])
|
|
1065
1278
|
du = primals[8] if len(primals) > 8 else 1.0
|
|
1066
1279
|
dv = primals[9] if len(primals) > 9 else 1.0
|
|
1067
1280
|
voxel_spacing = primals[10] if len(primals) > 10 else 1.0
|
|
1281
|
+
indices = primals[11] if len(primals) > 11 else None
|
|
1282
|
+
|
|
1283
|
+
dense_cotangent = cotangent
|
|
1284
|
+
if indices is not None:
|
|
1285
|
+
dense_cotangent = _scatter_sparse_cotangent(
|
|
1286
|
+
cotangent,
|
|
1287
|
+
_normalize_sparse_indices(indices, D, H, W),
|
|
1288
|
+
D,
|
|
1289
|
+
H,
|
|
1290
|
+
W,
|
|
1291
|
+
)
|
|
1068
1292
|
|
|
1069
1293
|
grad_sinogram = _cone_forward_footprint_impl(
|
|
1070
|
-
|
|
1294
|
+
dense_cotangent,
|
|
1071
1295
|
src_pos,
|
|
1072
1296
|
det_center,
|
|
1073
1297
|
det_u_vec,
|
|
@@ -1081,4 +1305,4 @@ def cone_backward_footprint_vjp(primals, cotangent, _):
|
|
|
1081
1305
|
return (grad_sinogram,
|
|
1082
1306
|
mx.zeros_like(src_pos), mx.zeros_like(det_center),
|
|
1083
1307
|
mx.zeros_like(det_u_vec), mx.zeros_like(det_v_vec),
|
|
1084
|
-
None, None, None, None, None, None)
|
|
1308
|
+
None, None, None, None, None, None, None)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|