diffct-mlx 1.0.1__tar.gz → 1.0.2__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 (32) hide show
  1. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/.gitignore +3 -0
  2. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/PKG-INFO +11 -6
  3. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/README.md +10 -5
  4. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/__about__.py +1 -1
  5. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/kernels/__init__.py +2 -0
  6. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/kernels/cone_beam.py +255 -0
  7. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/projectors.py +145 -3
  8. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/LICENSE +0 -0
  9. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/__init__.py +0 -0
  10. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/constants.py +0 -0
  11. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/geometry.py +0 -0
  12. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/kernels/fan_beam.py +0 -0
  13. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/kernels/parallel_beam.py +0 -0
  14. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/phantoms/__init__.py +0 -0
  15. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/phantoms/shepp_logan.py +0 -0
  16. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/real_measured_data_helper.py +0 -0
  17. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/__init__.py +0 -0
  18. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/_analytic.py +0 -0
  19. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/_core.py +0 -0
  20. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/asd_pocs.py +0 -0
  21. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/awtv_pocs.py +0 -0
  22. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/cases.py +0 -0
  23. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/dart.py +0 -0
  24. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/fbp.py +0 -0
  25. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/fdk.py +0 -0
  26. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/sart.py +0 -0
  27. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/sirt.py +0 -0
  28. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/reconstruction_algorithms/tv_pocs.py +0 -0
  29. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/regularizers.py +0 -0
  30. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/tv_gradients.py +0 -0
  31. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/diffct_mlx/utils.py +0 -0
  32. {diffct_mlx-1.0.1 → diffct_mlx-1.0.2}/pyproject.toml +0 -0
@@ -17,6 +17,9 @@ __pycache__/
17
17
  # C extensions
18
18
  *.so
19
19
 
20
+ # Notes
21
+ notes/
22
+
20
23
  # Distribution / packaging
21
24
  .Python
22
25
  build/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: diffct_mlx
3
- Version: 1.0.1
3
+ Version: 1.0.2
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
  [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg?style=flat-square)](https://opensource.org/licenses/Apache-2.0)
34
- [![DOI](https://img.shields.io/badge/DOI-10.5281%2Fzenodo.14999333-blue.svg?style=flat-square)](https://doi.org/10.5281/zenodo.14999333)
34
+ [![DOI](https://img.shields.io/badge/DOI-10.20944%2Fpreprints202605.1446.v1-blue.svg?style=flat-square)](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
 
@@ -293,10 +293,15 @@ diffct_mlx/
293
293
  If you use this library in your research, please cite:
294
294
 
295
295
  ```bibtex
296
- @software{diffct2026,
297
- author = {Yipeng Sun, Linda-Sophie Schneider},
298
- title = {diffct_mlx: Differentiable CT for Apple Silicon},
299
- year = 2026,
296
+ @article{202605.1446,
297
+ doi = {10.20944/preprints202605.1446.v1},
298
+ url = {https://doi.org/10.20944/preprints202605.1446.v1},
299
+ year = 2026,
300
+ month = {May},
301
+ publisher = {Preprints},
302
+ author = {Yipeng Sun and Linda-Sophie Schneider and Chengze ye and Andreas Maier},
303
+ title = {diffct: Differentiable CT Operators from Circular Orbits to Arbitrary Trajectories},
304
+ journal = {Preprints}
300
305
  }
301
306
  ```
302
307
 
@@ -1,7 +1,7 @@
1
1
  # diffct_mlx: Differentiable CT for Apple Silicon
2
2
 
3
3
  [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg?style=flat-square)](https://opensource.org/licenses/Apache-2.0)
4
- [![DOI](https://img.shields.io/badge/DOI-10.5281%2Fzenodo.14999333-blue.svg?style=flat-square)](https://doi.org/10.5281/zenodo.14999333)
4
+ [![DOI](https://img.shields.io/badge/DOI-10.20944%2Fpreprints202605.1446.v1-blue.svg?style=flat-square)](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
 
@@ -263,10 +263,15 @@ diffct_mlx/
263
263
  If you use this library in your research, please cite:
264
264
 
265
265
  ```bibtex
266
- @software{diffct2026,
267
- author = {Yipeng Sun, Linda-Sophie Schneider},
268
- title = {diffct_mlx: Differentiable CT for Apple Silicon},
269
- year = 2026,
266
+ @article{202605.1446,
267
+ doi = {10.20944/preprints202605.1446.v1},
268
+ url = {https://doi.org/10.20944/preprints202605.1446.v1},
269
+ year = 2026,
270
+ month = {May},
271
+ publisher = {Preprints},
272
+ author = {Yipeng Sun and Linda-Sophie Schneider and Chengze ye and Andreas Maier},
273
+ title = {diffct: Differentiable CT Operators from Circular Orbits to Arbitrary Trajectories},
274
+ journal = {Preprints}
270
275
  }
271
276
  ```
272
277
 
@@ -1,3 +1,3 @@
1
1
  """Package metadata for diffct_mlx."""
2
2
 
3
- __version__ = "1.0.1"
3
+ __version__ = "1.0.2"
@@ -21,6 +21,7 @@ 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_geometry_grad_kernel,
24
25
  )
25
26
 
26
27
  __all__ = [
@@ -36,4 +37,5 @@ __all__ = [
36
37
  'cone_3d_backward_kernel',
37
38
  'cone_3d_footprint_forward_kernel',
38
39
  'cone_3d_footprint_backward_kernel',
40
+ 'cone_3d_geometry_grad_kernel',
39
41
  ]
@@ -706,3 +706,258 @@ 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
+ # ============================================================================
711
+ # 3D Cone Beam Analytical Geometry Gradient Kernel
712
+ #
713
+ # Computes VJP of cone_forward w.r.t. src_pos, det_center, det_u_vec,
714
+ # det_v_vec analytically via the Reynolds-transport gradient of the
715
+ # Siddon ray integral.
716
+ #
717
+ # Derivation (voxel-space parametrisation, λ = t/L where L = ray length):
718
+ # a_p = voxel_spacing * Σ_seg μ(x(t_mid)) * seg_len
719
+ # ∂a_p/∂s_mm = −d̂ · A/L + G1 (d̂ = unit ray dir, A = Σ μ*seg_len)
720
+ # ∂a_p/∂p_mm = +d̂ · A/L + G2 (p = detector pixel world position)
721
+ # G1 = Σ seg_len * (1−λ_mid) * ∇μ_vox(x_mid)
722
+ # G2 = Σ seg_len * λ_mid * ∇μ_vox(x_mid)
723
+ # Chain rule then yields det_center / det_u_vec / det_v_vec gradients from
724
+ # ∂a_p/∂p_mm via p = det_center + u_off_mm*u_vec + v_off_mm*v_vec.
725
+ # ============================================================================
726
+
727
+ _CONE_3D_GEOMETRY_GRAD_SOURCE = """
728
+ uint iview = thread_position_in_grid.x;
729
+ uint iu = thread_position_in_grid.y;
730
+ uint iv = thread_position_in_grid.z;
731
+
732
+ int n_views = params[0];
733
+ int n_u = params[1];
734
+ int n_v = params[2];
735
+ int Nx = params[3];
736
+ int Ny = params[4];
737
+ int Nz = params[5];
738
+
739
+ float du = fparams[0];
740
+ float dv = fparams[1];
741
+ float cx = fparams[2];
742
+ float cy = fparams[3];
743
+ float cz = fparams[4];
744
+ float voxel_spacing = fparams[5];
745
+
746
+ if ((int)iview >= n_views || (int)iu >= n_u || (int)iv >= n_v) return;
747
+
748
+ float g = cotangent[iview * n_u * n_v + iu * n_v + iv];
749
+ if (g == 0.0f) return;
750
+
751
+ float eps = """ + _EPSILON_STR + """;
752
+
753
+ // === GEOMETRY SETUP (identical to forward kernel) ===
754
+ float src_x = src_pos[iview * 3 + 0] / voxel_spacing;
755
+ float src_y = src_pos[iview * 3 + 1] / voxel_spacing;
756
+ float src_z = src_pos[iview * 3 + 2] / voxel_spacing;
757
+
758
+ float det_cx = det_center[iview * 3 + 0] / voxel_spacing;
759
+ float det_cy = det_center[iview * 3 + 1] / voxel_spacing;
760
+ float det_cz = det_center[iview * 3 + 2] / voxel_spacing;
761
+
762
+ float u_vec_x = det_u_vec_arr[iview * 3 + 0];
763
+ float u_vec_y = det_u_vec_arr[iview * 3 + 1];
764
+ float u_vec_z = det_u_vec_arr[iview * 3 + 2];
765
+
766
+ float v_vec_x = det_v_vec_arr[iview * 3 + 0];
767
+ float v_vec_y = det_v_vec_arr[iview * 3 + 1];
768
+ float v_vec_z = det_v_vec_arr[iview * 3 + 2];
769
+
770
+ // Detector pixel offsets: voxel-space for ray, mm for chain-rule
771
+ float center_u = ((float)n_u - 1.0f) * 0.5f;
772
+ float center_v = ((float)n_v - 1.0f) * 0.5f;
773
+ float u_off_vox = ((float)iu - center_u) * du / voxel_spacing;
774
+ float v_off_vox = ((float)iv - center_v) * dv / voxel_spacing;
775
+ float u_off_mm = ((float)iu - center_u) * du;
776
+ float v_off_mm = ((float)iv - center_v) * dv;
777
+
778
+ float det_x = det_cx + u_off_vox * u_vec_x + v_off_vox * v_vec_x;
779
+ float det_y = det_cy + u_off_vox * u_vec_y + v_off_vox * v_vec_y;
780
+ float det_z = det_cz + u_off_vox * u_vec_z + v_off_vox * v_vec_z;
781
+
782
+ // === RAY DIRECTION ===
783
+ float dir_x = det_x - src_x;
784
+ float dir_y = det_y - src_y;
785
+ float dir_z = det_z - src_z;
786
+ float length = metal::sqrt(dir_x*dir_x + dir_y*dir_y + dir_z*dir_z);
787
+ if (length < eps) return;
788
+ float inv_len = 1.0f / length;
789
+ dir_x *= inv_len;
790
+ dir_y *= inv_len;
791
+ dir_z *= inv_len;
792
+
793
+ // === RAY-VOLUME INTERSECTION ===
794
+ float t_min = -""" + _INF_STR + """;
795
+ float t_max = """ + _INF_STR + """;
796
+
797
+ if (metal::abs(dir_x) > eps) {
798
+ float tx1 = (-cx - src_x) / dir_x;
799
+ float tx2 = ( cx - src_x) / dir_x;
800
+ t_min = metal::max(t_min, metal::min(tx1, tx2));
801
+ t_max = metal::min(t_max, metal::max(tx1, tx2));
802
+ } else if (src_x < -cx || src_x > cx) { return; }
803
+
804
+ if (metal::abs(dir_y) > eps) {
805
+ float ty1 = (-cy - src_y) / dir_y;
806
+ float ty2 = ( cy - src_y) / dir_y;
807
+ t_min = metal::max(t_min, metal::min(ty1, ty2));
808
+ t_max = metal::min(t_max, metal::max(ty1, ty2));
809
+ } else if (src_y < -cy || src_y > cy) { return; }
810
+
811
+ if (metal::abs(dir_z) > eps) {
812
+ float tz1 = (-cz - src_z) / dir_z;
813
+ float tz2 = ( cz - src_z) / dir_z;
814
+ t_min = metal::max(t_min, metal::min(tz1, tz2));
815
+ t_max = metal::min(t_max, metal::max(tz1, tz2));
816
+ } else if (src_z < -cz || src_z > cz) { return; }
817
+
818
+ if (t_min >= t_max) return;
819
+
820
+ // === SIDDON TRAVERSAL WITH G1/G2 ACCUMULATORS ===
821
+ float A = 0.0f;
822
+ float G1x = 0.0f, G1y = 0.0f, G1z = 0.0f;
823
+ float G2x = 0.0f, G2y = 0.0f, G2z = 0.0f;
824
+
825
+ float t = t_min;
826
+ int ix = (int)metal::floor(src_x + t * dir_x + cx);
827
+ int iy = (int)metal::floor(src_y + t * dir_y + cy);
828
+ int iz = (int)metal::floor(src_z + t * dir_z + cz);
829
+
830
+ int step_x = (dir_x >= 0.0f) ? 1 : -1;
831
+ int step_y = (dir_y >= 0.0f) ? 1 : -1;
832
+ int step_z = (dir_z >= 0.0f) ? 1 : -1;
833
+
834
+ float inv_dir_x = (metal::abs(dir_x) > eps) ? (1.0f / dir_x) : 0.0f;
835
+ float inv_dir_y = (metal::abs(dir_y) > eps) ? (1.0f / dir_y) : 0.0f;
836
+ float inv_dir_z = (metal::abs(dir_z) > eps) ? (1.0f / dir_z) : 0.0f;
837
+ float dt_x = (metal::abs(dir_x) > eps) ? metal::abs(inv_dir_x) : """ + _INF_STR + """;
838
+ float dt_y = (metal::abs(dir_y) > eps) ? metal::abs(inv_dir_y) : """ + _INF_STR + """;
839
+ float dt_z = (metal::abs(dir_z) > eps) ? metal::abs(inv_dir_z) : """ + _INF_STR + """;
840
+
841
+ float txn = (metal::abs(dir_x) > eps) ? ((float)(ix + (step_x > 0 ? 1 : 0)) - cx - src_x) * inv_dir_x : """ + _INF_STR + """;
842
+ float tyn = (metal::abs(dir_y) > eps) ? ((float)(iy + (step_y > 0 ? 1 : 0)) - cy - src_y) * inv_dir_y : """ + _INF_STR + """;
843
+ float tzn = (metal::abs(dir_z) > eps) ? ((float)(iz + (step_z > 0 ? 1 : 0)) - cz - src_z) * inv_dir_z : """ + _INF_STR + """;
844
+
845
+ int yz_stride = Ny * Nz;
846
+
847
+ while (t < t_max) {
848
+ if (ix >= 0 && ix < Nx && iy >= 0 && iy < Ny && iz >= 0 && iz < Nz) {
849
+ float t_next = metal::min(metal::min(metal::min(txn, tyn), tzn), t_max);
850
+ float seg_len = t_next - t;
851
+
852
+ if (seg_len > eps) {
853
+ float t_mid = t + seg_len * 0.5f;
854
+ float mid_x = src_x + t_mid * dir_x + cx;
855
+ float mid_y = src_y + t_mid * dir_y + cy;
856
+ float mid_z = src_z + t_mid * dir_z + cz;
857
+
858
+ int ix0 = (int)metal::floor(mid_x);
859
+ int iy0 = (int)metal::floor(mid_y);
860
+ int iz0 = (int)metal::floor(mid_z);
861
+ float dx = mid_x - (float)ix0;
862
+ float dy = mid_y - (float)iy0;
863
+ float dz = mid_z - (float)iz0;
864
+
865
+ ix0 = metal::max(0, metal::min(ix0, Nx - 2));
866
+ iy0 = metal::max(0, metal::min(iy0, Ny - 2));
867
+ iz0 = metal::max(0, metal::min(iz0, Nz - 2));
868
+
869
+ float omdx = 1.0f - dx;
870
+ float omdy = 1.0f - dy;
871
+ float omdz = 1.0f - dz;
872
+
873
+ int base = ix0 * yz_stride + iy0 * Nz + iz0;
874
+
875
+ // Trilinear voxel values (same as forward kernel)
876
+ float v000 = vol[base];
877
+ float v100 = vol[base + yz_stride];
878
+ float v010 = vol[base + Nz];
879
+ float v001 = vol[base + 1];
880
+ float v110 = vol[base + yz_stride + Nz];
881
+ float v101 = vol[base + yz_stride + 1];
882
+ float v011 = vol[base + Nz + 1];
883
+ float v111 = vol[base + yz_stride + Nz + 1];
884
+
885
+ float val = v000 * omdx*omdy*omdz + v100 * dx*omdy*omdz
886
+ + v010 * omdx*dy*omdz + v001 * omdx*omdy*dz
887
+ + v110 * dx*dy*omdz + v101 * dx*omdy*dz
888
+ + v011 * omdx*dy*dz + v111 * dx*dy*dz;
889
+
890
+ A += val * seg_len;
891
+
892
+ // Trilinear gradient of μ in kernel (voxel-index) space
893
+ float dmu_x = omdy*omdz*(v100-v000) + dy*omdz*(v110-v010)
894
+ + omdy*dz*(v101-v001) + dy*dz*(v111-v011);
895
+ float dmu_y = omdx*omdz*(v010-v000) + dx*omdz*(v110-v100)
896
+ + omdx*dz*(v011-v001) + dx*dz*(v111-v101);
897
+ float dmu_z = omdx*omdy*(v001-v000) + dx*omdy*(v101-v100)
898
+ + omdx*dy*(v011-v010) + dx*dy*(v111-v110);
899
+
900
+ // λ = t_mid / L; weights for source-end and detector-end
901
+ float lam = t_mid * inv_len;
902
+ float w1 = seg_len * (1.0f - lam);
903
+ float w2 = seg_len * lam;
904
+
905
+ G1x += w1 * dmu_x; G1y += w1 * dmu_y; G1z += w1 * dmu_z;
906
+ G2x += w2 * dmu_x; G2y += w2 * dmu_y; G2z += w2 * dmu_z;
907
+ }
908
+ }
909
+
910
+ if (txn <= tyn && txn <= tzn) {
911
+ t = txn; ix += step_x; txn += dt_x;
912
+ } else if (tyn <= txn && tyn <= tzn) {
913
+ t = tyn; iy += step_y; tyn += dt_y;
914
+ } else {
915
+ t = tzn; iz += step_z; tzn += dt_z;
916
+ }
917
+ }
918
+
919
+ // === ASSEMBLE GEOMETRY GRADIENTS ===
920
+ //
921
+ // ∂a_p/∂s_mm = −d̂ · A/L + G1 (source position, world mm)
922
+ // ∂a_p/∂p_mm = +d̂ · A/L + G2 (detector pixel, world mm)
923
+ //
924
+ // d̂ = (dir_x, dir_y, dir_z) — same unit vector in voxel and world space
925
+ // (voxel_spacing cancels: d̂_vox = d̂_mm for uniform scaling)
926
+ float A_over_L = A * inv_len;
927
+
928
+ float grad_sx = g * (-dir_x * A_over_L + G1x);
929
+ float grad_sy = g * (-dir_y * A_over_L + G1y);
930
+ float grad_sz = g * (-dir_z * A_over_L + G1z);
931
+
932
+ float grad_px = g * ( dir_x * A_over_L + G2x);
933
+ float grad_py = g * ( dir_y * A_over_L + G2y);
934
+ float grad_pz = g * ( dir_z * A_over_L + G2z);
935
+
936
+ // grad_src_pos (per view)
937
+ atomic_fetch_add_explicit(&grad_src_pos[iview*3+0], grad_sx, memory_order_relaxed);
938
+ atomic_fetch_add_explicit(&grad_src_pos[iview*3+1], grad_sy, memory_order_relaxed);
939
+ atomic_fetch_add_explicit(&grad_src_pos[iview*3+2], grad_sz, memory_order_relaxed);
940
+
941
+ // grad_det_center = grad_p (∂p_mm/∂det_center_mm = I)
942
+ atomic_fetch_add_explicit(&grad_det_center[iview*3+0], grad_px, memory_order_relaxed);
943
+ atomic_fetch_add_explicit(&grad_det_center[iview*3+1], grad_py, memory_order_relaxed);
944
+ atomic_fetch_add_explicit(&grad_det_center[iview*3+2], grad_pz, memory_order_relaxed);
945
+
946
+ // grad_det_u_vec = u_off_mm * grad_p (∂p_mm/∂u_vec = u_off_mm·I)
947
+ atomic_fetch_add_explicit(&grad_det_u_vec[iview*3+0], u_off_mm * grad_px, memory_order_relaxed);
948
+ atomic_fetch_add_explicit(&grad_det_u_vec[iview*3+1], u_off_mm * grad_py, memory_order_relaxed);
949
+ atomic_fetch_add_explicit(&grad_det_u_vec[iview*3+2], u_off_mm * grad_pz, memory_order_relaxed);
950
+
951
+ // grad_det_v_vec = v_off_mm * grad_p (∂p_mm/∂v_vec = v_off_mm·I)
952
+ atomic_fetch_add_explicit(&grad_det_v_vec[iview*3+0], v_off_mm * grad_px, memory_order_relaxed);
953
+ atomic_fetch_add_explicit(&grad_det_v_vec[iview*3+1], v_off_mm * grad_py, memory_order_relaxed);
954
+ atomic_fetch_add_explicit(&grad_det_v_vec[iview*3+2], v_off_mm * grad_pz, memory_order_relaxed);
955
+ """
956
+
957
+ cone_3d_geometry_grad_kernel = mx.fast.metal_kernel(
958
+ name="cone_3d_geometry_grad",
959
+ input_names=["vol", "cotangent", "src_pos", "det_center", "det_u_vec_arr", "det_v_vec_arr", "params", "fparams"],
960
+ output_names=["grad_src_pos", "grad_det_center", "grad_det_u_vec", "grad_det_v_vec"],
961
+ source=_CONE_3D_GEOMETRY_GRAD_SOURCE,
962
+ atomic_outputs=True,
963
+ )
@@ -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,8 +26,13 @@ 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_geometry_grad_kernel,
28
30
  )
29
31
 
32
+ # Set DIFFCT_GEOMETRY_VJP=1 to use the analytical geometry gradient kernel
33
+ # instead of the finite-difference fallback for cone_forward.
34
+ _GEOMETRY_VJP_ENABLED: bool = os.getenv("DIFFCT_GEOMETRY_VJP", "0") == "1"
35
+
30
36
 
31
37
  def _as_mx_float_array(value):
32
38
  """Accept NumPy or MLX arrays and return an MLX float array."""
@@ -700,6 +706,68 @@ def fan_backward_footprint_vjp(primals, cotangent, _):
700
706
  # 3D Cone Beam
701
707
  # ============================================================================
702
708
 
709
+ #: Perturbation step (in the same length unit as src_pos, typically mm) used
710
+ #: for the finite-difference source-position VJP. A value of ~0.5 mm gives
711
+ #: good accuracy for source-to-isocenter distances in the 100–1000 mm range.
712
+ _FD_EPS_SRC: float = 0.5
713
+
714
+
715
+ def _src_pos_grad_fd(
716
+ volume, src_pos, det_center, det_u_vec, det_v_vec,
717
+ det_u, det_v, du, dv, voxel_spacing,
718
+ cotangent,
719
+ eps: float = _FD_EPS_SRC,
720
+ ) -> "mx.array":
721
+ """Finite-difference VJP for *src_pos* in cone-beam forward projection.
722
+
723
+ Uses 6 forward passes (±ε per spatial axis) to approximate
724
+ ``cotangent^T · ∂F/∂src_pos``. Because each view's projection depends
725
+ only on that view's source position, all views can be perturbed
726
+ simultaneously with the same Δ, giving the correct per-view gradient
727
+ without any extra passes per additional view.
728
+
729
+ Parameters
730
+ ----------
731
+ cotangent : mx.array, shape ``(n_views, det_u, det_v)``
732
+ Upstream gradient from the objective.
733
+ eps : float
734
+ Finite-difference step size in the same units as *src_pos*.
735
+
736
+ Returns
737
+ -------
738
+ grad_src_pos : mx.array, shape ``(n_views, 3)``
739
+ """
740
+ # Convert all inputs to plain MLX arrays to detach them from any autograd
741
+ # tape that may be active in the calling context (second-order
742
+ # differentiation is not desired here).
743
+ volume = _as_mx_float_array(volume)
744
+ src_pos = _as_mx_float_array(src_pos)
745
+ det_center = _as_mx_float_array(det_center)
746
+ det_u_vec = _as_mx_float_array(det_u_vec)
747
+ det_v_vec = _as_mx_float_array(det_v_vec)
748
+ cotangent = _as_mx_float_array(cotangent)
749
+
750
+ grads = []
751
+ for j in range(3):
752
+ delta_list = [[0.0, 0.0, 0.0]]
753
+ delta_list[0][j] = eps
754
+ delta = mx.array(delta_list, dtype=src_pos.dtype) # (1, 3) — broadcast
755
+
756
+ f_plus = _cone_forward_impl(
757
+ volume, src_pos + delta, det_center, det_u_vec, det_v_vec,
758
+ det_u, det_v, du, dv, voxel_spacing,
759
+ )
760
+ f_minus = _cone_forward_impl(
761
+ volume, src_pos - delta, det_center, det_u_vec, det_v_vec,
762
+ det_u, det_v, du, dv, voxel_spacing,
763
+ )
764
+ # Directional derivative w.r.t. src_pos[:, j]; shape (n_views, det_u, det_v)
765
+ df_dxj = (f_plus - f_minus) / (2.0 * eps)
766
+ # Chain rule: sum cotangent * df_dxj over the detector pixels per view
767
+ grads.append(mx.sum(cotangent * df_dxj, axis=(1, 2))) # (n_views,)
768
+
769
+ return mx.stack(grads, axis=-1) # (n_views, 3)
770
+
703
771
  def _cone_forward_impl(volume, src_pos, det_center, det_u_vec, det_v_vec,
704
772
  det_u, det_v, du, dv, voxel_spacing=1.0):
705
773
  """Raw cone beam forward projection."""
@@ -797,6 +865,54 @@ def _cone_backward_impl(sinogram, src_pos, det_center, det_u_vec, det_v_vec,
797
865
  return mx.array(vol)
798
866
 
799
867
 
868
+ def _cone_geometry_grad_impl(
869
+ volume, cotangent, src_pos, det_center, det_u_vec, det_v_vec,
870
+ det_u, det_v, du, dv, voxel_spacing=1.0
871
+ ):
872
+ """Analytical VJP of cone_forward w.r.t. src_pos, det_center, det_u_vec, det_v_vec.
873
+
874
+ Returns
875
+ -------
876
+ grad_src_pos : ``(n_views, 3)``
877
+ grad_det_center : ``(n_views, 3)``
878
+ grad_det_u_vec : ``(n_views, 3)``
879
+ grad_det_v_vec : ``(n_views, 3)``
880
+ """
881
+ volume = _as_mx_float_array(volume)
882
+ cotangent = _as_mx_float_array(cotangent)
883
+ src_pos = _as_mx_float_array(src_pos)
884
+ det_center = _as_mx_float_array(det_center)
885
+ det_u_vec = _as_mx_float_array(det_u_vec)
886
+ det_v_vec = _as_mx_float_array(det_v_vec)
887
+
888
+ D, H, W = volume.shape
889
+ n_views = src_pos.shape[0]
890
+ n_u, n_v = int(det_u), int(det_v)
891
+
892
+ # Same WHD permutation as the forward kernel
893
+ volume_perm = mx.array(mx.transpose(volume, axes=(2, 1, 0)))
894
+ Nx, Ny, Nz = W, H, D
895
+
896
+ params, fparams = _projector_params_3d(
897
+ n_views, n_u, n_v, Nx, Ny, Nz,
898
+ float(du), float(dv),
899
+ float(Nx * 0.5), float(Ny * 0.5), float(Nz * 0.5),
900
+ float(voxel_spacing),
901
+ )
902
+
903
+ grid, tg = _grid_3d(n_views, n_u, n_v)
904
+
905
+ outputs = cone_3d_geometry_grad_kernel(
906
+ inputs=[volume_perm, cotangent, src_pos, det_center, det_u_vec, det_v_vec, params, fparams],
907
+ output_shapes=[(n_views, 3), (n_views, 3), (n_views, 3), (n_views, 3)],
908
+ output_dtypes=[_MX_DTYPE, _MX_DTYPE, _MX_DTYPE, _MX_DTYPE],
909
+ grid=grid,
910
+ threadgroup=tg,
911
+ init_value=0,
912
+ )
913
+ return outputs[0], outputs[1], outputs[2], outputs[3]
914
+
915
+
800
916
  def _cone_forward_footprint_impl(volume, src_pos, det_center, det_u_vec, det_v_vec,
801
917
  det_u, det_v, du, dv, voxel_spacing=1.0):
802
918
  """Approximate separable-footprint cone-beam forward projector."""
@@ -926,6 +1042,8 @@ def cone_forward(volume, src_pos, det_center, det_u_vec, det_v_vec,
926
1042
  @cone_forward.vjp
927
1043
  def cone_forward_vjp(primals, cotangent, _):
928
1044
  volume, src_pos, det_center, det_u_vec, det_v_vec = primals[:5]
1045
+ det_u_int = int(primals[5]) if len(primals) > 5 else 128
1046
+ det_v_int = int(primals[6]) if len(primals) > 6 else 128
929
1047
  du = primals[7] if len(primals) > 7 else 1.0
930
1048
  dv = primals[8] if len(primals) > 8 else 1.0
931
1049
  voxel_spacing = primals[9] if len(primals) > 9 else 1.0
@@ -935,9 +1053,26 @@ def cone_forward_vjp(primals, cotangent, _):
935
1053
  cotangent, src_pos, det_center, det_u_vec, det_v_vec,
936
1054
  D, H, W, du, dv, voxel_spacing
937
1055
  )
1056
+
1057
+ if _GEOMETRY_VJP_ENABLED:
1058
+ grad_src_pos, grad_det_center, grad_det_u_vec, grad_det_v_vec = \
1059
+ _cone_geometry_grad_impl(
1060
+ volume, cotangent, src_pos, det_center, det_u_vec, det_v_vec,
1061
+ det_u_int, det_v_int, du, dv, voxel_spacing,
1062
+ )
1063
+ else:
1064
+ grad_src_pos = _src_pos_grad_fd(
1065
+ volume, src_pos, det_center, det_u_vec, det_v_vec,
1066
+ det_u_int, det_v_int, du, dv, voxel_spacing,
1067
+ cotangent,
1068
+ )
1069
+ grad_det_center = mx.zeros_like(det_center)
1070
+ grad_det_u_vec = mx.zeros_like(det_u_vec)
1071
+ grad_det_v_vec = mx.zeros_like(det_v_vec)
1072
+
938
1073
  return (grad_volume,
939
- mx.zeros_like(src_pos), mx.zeros_like(det_center),
940
- mx.zeros_like(det_u_vec), mx.zeros_like(det_v_vec),
1074
+ grad_src_pos, grad_det_center,
1075
+ grad_det_u_vec, grad_det_v_vec,
941
1076
  None, None, None, None, None)
942
1077
 
943
1078
 
@@ -1014,6 +1149,8 @@ def cone_forward_footprint(volume, src_pos, det_center, det_u_vec, det_v_vec,
1014
1149
  @cone_forward_footprint.vjp
1015
1150
  def cone_forward_footprint_vjp(primals, cotangent, _):
1016
1151
  volume, src_pos, det_center, det_u_vec, det_v_vec = primals[:5]
1152
+ det_u_int = int(primals[5]) if len(primals) > 5 else 128
1153
+ det_v_int = int(primals[6]) if len(primals) > 6 else 128
1017
1154
  du = primals[7] if len(primals) > 7 else 1.0
1018
1155
  dv = primals[8] if len(primals) > 8 else 1.0
1019
1156
  voxel_spacing = primals[9] if len(primals) > 9 else 1.0
@@ -1032,8 +1169,13 @@ def cone_forward_footprint_vjp(primals, cotangent, _):
1032
1169
  dv,
1033
1170
  voxel_spacing,
1034
1171
  )
1172
+ grad_src_pos = _src_pos_grad_fd(
1173
+ volume, src_pos, det_center, det_u_vec, det_v_vec,
1174
+ det_u_int, det_v_int, du, dv, voxel_spacing,
1175
+ cotangent,
1176
+ )
1035
1177
  return (grad_volume,
1036
- mx.zeros_like(src_pos), mx.zeros_like(det_center),
1178
+ grad_src_pos, mx.zeros_like(det_center),
1037
1179
  mx.zeros_like(det_u_vec), mx.zeros_like(det_v_vec),
1038
1180
  None, None, None, None, None)
1039
1181
 
File without changes
File without changes