diffct-mlx 2.0.0__tar.gz → 2.0.1__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 (124) hide show
  1. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/CHANGELOG.md +24 -3
  2. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/PKG-INFO +26 -15
  3. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/README.md +25 -14
  4. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/footprint.py +60 -9
  5. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/kernels/__init__.py +2 -0
  6. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/kernels/cone_beam.py +242 -0
  7. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/projectors.py +38 -1
  8. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/__init__.py +1 -1
  9. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/metal/kernels/cone_beam.py +28 -31
  10. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/metal/projectors.py +5 -3
  11. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/conf.py +1 -1
  12. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/pyproject.toml +1 -1
  13. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_known_operator_gradflow.py +109 -8
  14. diffct_mlx-2.0.1/tests/test_metal_kernel_static.py +34 -0
  15. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/.github/workflows/docs.yml +0 -0
  16. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/.github/workflows/publish.yml +0 -0
  17. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/.github/workflows/release.yml +0 -0
  18. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/.gitignore +0 -0
  19. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/ATTRIBUTION.md +0 -0
  20. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/LICENSE +0 -0
  21. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/__init__.py +0 -0
  22. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/analytical.py +0 -0
  23. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/constants.py +0 -0
  24. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/differentiable.py +0 -0
  25. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/geometry.py +0 -0
  26. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/kernels/cone_footprint.py +0 -0
  27. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/kernels/fan_beam.py +0 -0
  28. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/kernels/fan_footprint.py +0 -0
  29. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/kernels/parallel_beam.py +0 -0
  30. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/kernels/parallel_footprint.py +0 -0
  31. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct/utils.py +0 -0
  32. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/analytical.py +0 -0
  33. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/__init__.py +0 -0
  34. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/_mlx.py +0 -0
  35. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/_torch.py +0 -0
  36. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/metal/__init__.py +0 -0
  37. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/metal/constants.py +0 -0
  38. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/metal/geometry.py +0 -0
  39. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/metal/kernels/__init__.py +0 -0
  40. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/metal/kernels/fan_beam.py +0 -0
  41. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/metal/kernels/parallel_beam.py +0 -0
  42. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/backend/metal/utils.py +0 -0
  43. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/calibration.py +0 -0
  44. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/filters.py +0 -0
  45. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/functionals.py +0 -0
  46. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/geometry.py +0 -0
  47. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/operators.py +0 -0
  48. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/orchestration/__init__.py +0 -0
  49. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/orchestration/out_of_core.py +0 -0
  50. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/phantoms/__init__.py +0 -0
  51. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/phantoms/engine.py +0 -0
  52. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/phantoms/shepp_logan.py +0 -0
  53. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/physics/__init__.py +0 -0
  54. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/physics/corrections.py +0 -0
  55. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/physics/data/spectra.npz +0 -0
  56. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/physics/pipeline.py +0 -0
  57. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/physics/simulate.py +0 -0
  58. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/physics/spectra.py +0 -0
  59. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/projectors.py +0 -0
  60. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/real_measured_data_helper.py +0 -0
  61. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/rebinning.py +0 -0
  62. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/__init__.py +0 -0
  63. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/_analytic.py +0 -0
  64. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/_core.py +0 -0
  65. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/_solver.py +0 -0
  66. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/asd_pocs.py +0 -0
  67. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/awtv_pocs.py +0 -0
  68. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/cases.py +0 -0
  69. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/dart.py +0 -0
  70. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/fbp.py +0 -0
  71. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/fdk.py +0 -0
  72. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/sart.py +0 -0
  73. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/sirt.py +0 -0
  74. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/solvers.py +0 -0
  75. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/reconstruction_algorithms/tv_pocs.py +0 -0
  76. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/regularizers.py +0 -0
  77. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/diffct_mlx/tv_gradients.py +0 -0
  78. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/Makefile +0 -0
  79. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/_static/.gitkeep +0 -0
  80. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/api.rst +0 -0
  81. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/examples.rst +0 -0
  82. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/fbp_fan_example.rst +0 -0
  83. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/fbp_parallel_example.rst +0 -0
  84. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/fdk_cone_example.rst +0 -0
  85. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/getting_started.rst +0 -0
  86. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/index.rst +0 -0
  87. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/iterative_reco_cone_example.rst +0 -0
  88. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/iterative_reco_fan_example.rst +0 -0
  89. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/docs/source/iterative_reco_parallel_example.rst +0 -0
  90. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/circular_trajectory/fbp_fan.py +0 -0
  91. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/circular_trajectory/fbp_parallel.py +0 -0
  92. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/circular_trajectory/fdk_cone.py +0 -0
  93. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/circular_trajectory/iterative_reco_cone.py +0 -0
  94. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/circular_trajectory/iterative_reco_fan.py +0 -0
  95. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/circular_trajectory/iterative_reco_parallel.py +0 -0
  96. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/non_circular_trajectory/iterative_reco_cone.py +0 -0
  97. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/non_circular_trajectory/iterative_reco_fan.py +0 -0
  98. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/non_circular_trajectory/iterative_reco_parallel.py +0 -0
  99. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/examples/plot_trajectory.py +0 -0
  100. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/pytest.ini +0 -0
  101. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/requirements.txt +0 -0
  102. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/__init__.py +0 -0
  103. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/_phantoms.py +0 -0
  104. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/benchmarks/README.md +0 -0
  105. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/benchmarks/__init__.py +0 -0
  106. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/benchmarks/_common.py +0 -0
  107. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/benchmarks/test_bench_cone.py +0 -0
  108. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/benchmarks/test_bench_fan.py +0 -0
  109. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/benchmarks/test_bench_parallel.py +0 -0
  110. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_adjoint_inner_product.py +0 -0
  111. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_cone_projector_autograd.py +0 -0
  112. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_cuda_smoke.py +0 -0
  113. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_diffct_mlx_extensions.py +0 -0
  114. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_fbp_fan_accuracy.py +0 -0
  115. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_fbp_fan_offsets.py +0 -0
  116. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_fbp_parallel_accuracy.py +0 -0
  117. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_fdk_cone_accuracy.py +0 -0
  118. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_fdk_cone_offsets.py +0 -0
  119. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_gradcheck.py +0 -0
  120. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_ramp_filter_windows.py +0 -0
  121. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_regressions.py +0 -0
  122. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_siddon_centering.py +0 -0
  123. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tests/test_weights.py +0 -0
  124. {diffct_mlx-2.0.0 → diffct_mlx-2.0.1}/tools/generate_spectra.py +0 -0
@@ -9,6 +9,28 @@ and the project follows [Semantic Versioning](https://semver.org/).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [2.0.1] - 2026-07-15
13
+
14
+ ### Added
15
+
16
+ - **Analytic geometry gradients for the cone Siddon projector (CUDA and
17
+ Metal)**:
18
+ `_cone_3d_geometry_grad_kernel` computes closed-form per-view gradients
19
+ for `src_pos`, `det_center`, `det_u_vec` and `det_v_vec` in a single
20
+ kernel pass (endpoint derivatives of the trilinearly smoothed line
21
+ integral, with the projected moment accumulated by the same segment
22
+ quadrature as the gradient terms). Default for cone geometry gradients
23
+ (`DIFFCT_GEOMETRY_VJP=fd` forces finite differences). The CUDA path is
24
+ validated against an exact torch-autograd `grid_sample` reference
25
+ (cos > 0.998, norm ratio within 1%) and is ~4× faster than FD; the Metal
26
+ port uses the same center-based sampling, projected-moment quadrature and
27
+ world/voxel unit conversion.
28
+ - **Footprint forward projectors are geometry-trainable** (parallel, fan,
29
+ cone): finite-difference VJPs for their geometry arrays, so the operator
30
+ layer's default `projector_mode="footprint"` — and pipelines built on it,
31
+ e.g. differentiable view-coverage objectives — receive source/detector
32
+ gradients. Backprojectors remain data-only.
33
+
12
34
  ## [2.0.0] - 2026-07-10
13
35
 
14
36
  First stable release of the unified package. Includes everything in
@@ -16,8 +38,6 @@ First stable release of the unified package. Includes everything in
16
38
  on Apple Silicon (the last open item of the unification) and the Torch
17
39
  backend gains trainable projector geometry.
18
40
 
19
- ### Added
20
-
21
41
  - **Trainable geometry on the Torch backend**: the Siddon projectors
22
42
  (parallel/fan/cone) return finite-difference VJPs for their per-view
23
43
  geometry arrays (`src_pos`, `det_center`/`det_origin`, `det_u_vec`,
@@ -340,5 +360,6 @@ necessary for the arbitrary-trajectory kernel API:
340
360
  when the detector is not plane-aligned to the voxel axes) and will
341
361
  be tackled in a dedicated follow-up.
342
362
 
343
- [Unreleased]: https://github.com/Linda-SophieSchneider/DiffCT-MLX/compare/v2.0.0...HEAD
363
+ [Unreleased]: https://github.com/Linda-SophieSchneider/DiffCT-MLX/compare/v2.0.1...HEAD
364
+ [2.0.1]: https://github.com/Linda-SophieSchneider/DiffCT-MLX/compare/v2.0.0...v2.0.1
344
365
  [2.0.0]: https://github.com/Linda-SophieSchneider/DiffCT-MLX/releases/tag/v2.0.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: diffct-mlx
3
- Version: 2.0.0
3
+ Version: 2.0.1
4
4
  Summary: Differentiable computed tomography with an auto-selecting backend (Torch/CUDA or Apple MLX)
5
5
  Project-URL: Homepage, https://github.com/Linda-SophieSchneider/DiffCT-MLX
6
6
  Project-URL: Upstream, https://github.com/sypsyp97/diffct
@@ -190,20 +190,31 @@ sizes, Plug-and-Play priors). Verified by `tests/test_known_operator_gradflow.py
190
190
  when the input carries gradients, so unrolled TV gradient steps are
191
191
  second-order differentiable (mirrors `mx.grad` composability on MLX).
192
192
 
193
- **Trainable geometry (pose/trajectory optimization).** The Torch Siddon
194
- projectors (parallel/fan/cone) also provide gradients w.r.t. their per-view
195
- geometry arrays (`src_pos`, `det_center`/`det_origin`, `det_u_vec`,
196
- `det_v_vec`, `ray_dir`) via finite-difference VJPs: computed only for inputs
197
- with `requires_grad` (the data-only path pays nothing), two forward passes per
198
- geometry component, step size chosen relative to each array's magnitude (works
199
- for mm- and m-scale setups alike). Semantics to know: Siddon ray weights are
200
- piecewise-linear in the geometry, so these are *smoothed subgradients* — exact
201
- against a matched-step contraction (pinned by tests), descent-quality in
202
- practice (see the pose-recovery test), but not second-order differentiable.
203
- On MLX, the cone projector has the equivalent VJP (`src_pos` by default, all
204
- four arrays with `DIFFCT_GEOMETRY_VJP=1`). The **footprint** family stays
205
- data-only, and stochastic simulation ops (`add_poisson_noise`) are not
206
- differentiable.
193
+ **Trainable geometry (pose/trajectory optimization).** All Torch forward
194
+ projectors provide gradients w.r.t. their per-view geometry arrays
195
+ (`src_pos`, `det_center`/`det_origin`, `det_u_vec`, `det_v_vec`, `ray_dir`),
196
+ computed only for inputs with `requires_grad` (the data-only path pays
197
+ nothing):
198
+
199
+ - **Cone Siddon** uses an **analytic geometry kernel** (default): one kernel
200
+ pass yields closed-form gradients for all four geometry arrays — the
201
+ per-ray endpoint derivatives of the trilinearly smoothed line integral,
202
+ validated against an exact torch-autograd reference (cos > 0.998) and ~4×
203
+ faster than finite differences. Set `DIFFCT_GEOMETRY_VJP=fd` to force the
204
+ FD path instead.
205
+ - **Fan/parallel Siddon and all footprint forwards** use finite-difference
206
+ VJPs (two forward passes per geometry component, magnitude-relative step —
207
+ mm- and m-scale setups both work). The operator layer's default
208
+ `projector_mode="footprint"` is therefore geometry-trainable too.
209
+
210
+ Semantics to know: the discrete forwards are piecewise-linear in the
211
+ geometry, so all of these are *smoothed* gradients — descent-quality in
212
+ practice (see the pose-recovery tests), but not second-order differentiable.
213
+ Backprojectors remain data-only, and stochastic simulation ops
214
+ (`add_poisson_noise`) are not differentiable. On MLX, cone Siddon uses the
215
+ same analytic endpoint-gradient formulation by default, including gradients
216
+ for all four geometry arrays. Set `DIFFCT_GEOMETRY_VJP=fd` for the legacy
217
+ finite-difference `src_pos` fallback.
207
218
 
208
219
  **Recommended step-size parametrization for unrolled networks.** A free
209
220
  trainable step can wander into the divergent regime, where positivity clamps
@@ -165,20 +165,31 @@ sizes, Plug-and-Play priors). Verified by `tests/test_known_operator_gradflow.py
165
165
  when the input carries gradients, so unrolled TV gradient steps are
166
166
  second-order differentiable (mirrors `mx.grad` composability on MLX).
167
167
 
168
- **Trainable geometry (pose/trajectory optimization).** The Torch Siddon
169
- projectors (parallel/fan/cone) also provide gradients w.r.t. their per-view
170
- geometry arrays (`src_pos`, `det_center`/`det_origin`, `det_u_vec`,
171
- `det_v_vec`, `ray_dir`) via finite-difference VJPs: computed only for inputs
172
- with `requires_grad` (the data-only path pays nothing), two forward passes per
173
- geometry component, step size chosen relative to each array's magnitude (works
174
- for mm- and m-scale setups alike). Semantics to know: Siddon ray weights are
175
- piecewise-linear in the geometry, so these are *smoothed subgradients* — exact
176
- against a matched-step contraction (pinned by tests), descent-quality in
177
- practice (see the pose-recovery test), but not second-order differentiable.
178
- On MLX, the cone projector has the equivalent VJP (`src_pos` by default, all
179
- four arrays with `DIFFCT_GEOMETRY_VJP=1`). The **footprint** family stays
180
- data-only, and stochastic simulation ops (`add_poisson_noise`) are not
181
- differentiable.
168
+ **Trainable geometry (pose/trajectory optimization).** All Torch forward
169
+ projectors provide gradients w.r.t. their per-view geometry arrays
170
+ (`src_pos`, `det_center`/`det_origin`, `det_u_vec`, `det_v_vec`, `ray_dir`),
171
+ computed only for inputs with `requires_grad` (the data-only path pays
172
+ nothing):
173
+
174
+ - **Cone Siddon** uses an **analytic geometry kernel** (default): one kernel
175
+ pass yields closed-form gradients for all four geometry arrays — the
176
+ per-ray endpoint derivatives of the trilinearly smoothed line integral,
177
+ validated against an exact torch-autograd reference (cos > 0.998) and ~4×
178
+ faster than finite differences. Set `DIFFCT_GEOMETRY_VJP=fd` to force the
179
+ FD path instead.
180
+ - **Fan/parallel Siddon and all footprint forwards** use finite-difference
181
+ VJPs (two forward passes per geometry component, magnitude-relative step —
182
+ mm- and m-scale setups both work). The operator layer's default
183
+ `projector_mode="footprint"` is therefore geometry-trainable too.
184
+
185
+ Semantics to know: the discrete forwards are piecewise-linear in the
186
+ geometry, so all of these are *smoothed* gradients — descent-quality in
187
+ practice (see the pose-recovery tests), but not second-order differentiable.
188
+ Backprojectors remain data-only, and stochastic simulation ops
189
+ (`add_poisson_noise`) are not differentiable. On MLX, cone Siddon uses the
190
+ same analytic endpoint-gradient formulation by default, including gradients
191
+ for all four geometry arrays. Set `DIFFCT_GEOMETRY_VJP=fd` for the legacy
192
+ finite-difference `src_pos` fallback.
182
193
 
183
194
  **Recommended step-size parametrization for unrolled networks.** A free
184
195
  trainable step can wander into the divergent regime, where positivity clamps
@@ -8,6 +8,11 @@ drop-in replacements. Currently: 2D parallel beam (fan / cone follow).
8
8
  import torch
9
9
 
10
10
  from .constants import _DTYPE
11
+ from .projectors import (
12
+ _FD_REL_EPS_POS,
13
+ _FD_REL_EPS_VEC,
14
+ _fd_geometry_grads,
15
+ )
11
16
  from .utils import (
12
17
  DeviceManager,
13
18
  TorchCUDABridge,
@@ -64,13 +69,14 @@ class ParallelFootprintProjectorFunction(torch.autograd.Function):
64
69
  _DTYPE(detector_spacing), d_ray, d_do, d_du, cx, cy, _DTYPE(voxel_spacing)
65
70
  )
66
71
 
67
- ctx.save_for_backward(ray_dir, det_origin, det_u_vec)
72
+ # image saved for the (optional) finite-difference geometry gradients.
73
+ ctx.save_for_backward(image, ray_dir, det_origin, det_u_vec)
68
74
  ctx.intermediate = (num_detectors, detector_spacing, Ny, Nx, voxel_spacing)
69
75
  return sinogram
70
76
 
71
77
  @staticmethod
72
78
  def backward(ctx, grad_sinogram):
73
- ray_dir, det_origin, det_u_vec = ctx.saved_tensors
79
+ image, ray_dir, det_origin, det_u_vec = ctx.saved_tensors
74
80
  num_detectors, detector_spacing, Ny, Nx, voxel_spacing = ctx.intermediate
75
81
  device = DeviceManager.get_device(grad_sinogram)
76
82
  grad_sinogram = _to_f32_contig(DeviceManager.ensure_device(grad_sinogram, device))
@@ -94,7 +100,21 @@ class ParallelFootprintProjectorFunction(torch.autograd.Function):
94
100
  d_grad_sino, n_views, num_detectors, d_img_grad, Nx, Ny,
95
101
  _DTYPE(detector_spacing), d_ray, d_do, d_du, cx, cy, _DTYPE(voxel_spacing)
96
102
  )
97
- return grad_image, None, None, None, None, None, None
103
+
104
+ grad_ray = grad_do = grad_duv = None
105
+ if any(ctx.needs_input_grad[1:4]):
106
+ def _launch(ray_d, det_o, det_uv):
107
+ with torch.no_grad():
108
+ return ParallelFootprintProjectorFunction.apply(
109
+ image, ray_d, det_o, det_uv,
110
+ num_detectors, detector_spacing, voxel_spacing)
111
+
112
+ grad_ray, grad_do, grad_duv = _fd_geometry_grads(
113
+ _launch, [ray_dir, det_origin, det_u_vec],
114
+ ctx.needs_input_grad[1:4], grad_sinogram,
115
+ [_FD_REL_EPS_VEC, _FD_REL_EPS_POS, _FD_REL_EPS_VEC])
116
+
117
+ return grad_image, grad_ray, grad_do, grad_duv, None, None, None
98
118
 
99
119
 
100
120
  class ParallelFootprintBackprojectorFunction(torch.autograd.Function):
@@ -189,13 +209,14 @@ class FanFootprintProjectorFunction(torch.autograd.Function):
189
209
  _DTYPE(detector_spacing), d_src, d_dc, d_du, cx, cy, _DTYPE(voxel_spacing)
190
210
  )
191
211
 
192
- ctx.save_for_backward(src_pos, det_center, det_u_vec)
212
+ # image saved for the (optional) finite-difference geometry gradients.
213
+ ctx.save_for_backward(image, src_pos, det_center, det_u_vec)
193
214
  ctx.intermediate = (num_detectors, detector_spacing, Ny, Nx, voxel_spacing)
194
215
  return sinogram
195
216
 
196
217
  @staticmethod
197
218
  def backward(ctx, grad_sinogram):
198
- src_pos, det_center, det_u_vec = ctx.saved_tensors
219
+ image, src_pos, det_center, det_u_vec = ctx.saved_tensors
199
220
  num_detectors, detector_spacing, Ny, Nx, voxel_spacing = ctx.intermediate
200
221
  device = DeviceManager.get_device(grad_sinogram)
201
222
  grad_sinogram = _to_f32_contig(DeviceManager.ensure_device(grad_sinogram, device))
@@ -219,7 +240,20 @@ class FanFootprintProjectorFunction(torch.autograd.Function):
219
240
  d_grad_sino, n_views, num_detectors, d_img_grad, Nx, Ny,
220
241
  _DTYPE(detector_spacing), d_src, d_dc, d_du, cx, cy, _DTYPE(voxel_spacing)
221
242
  )
222
- return grad_image, None, None, None, None, None, None
243
+ grad_src = grad_dc = grad_duv = None
244
+ if any(ctx.needs_input_grad[1:4]):
245
+ def _launch(src_p, det_c, det_uv):
246
+ with torch.no_grad():
247
+ return FanFootprintProjectorFunction.apply(
248
+ image, src_p, det_c, det_uv,
249
+ num_detectors, detector_spacing, voxel_spacing)
250
+
251
+ grad_src, grad_dc, grad_duv = _fd_geometry_grads(
252
+ _launch, [src_pos, det_center, det_u_vec],
253
+ ctx.needs_input_grad[1:4], grad_sinogram,
254
+ [_FD_REL_EPS_POS, _FD_REL_EPS_POS, _FD_REL_EPS_VEC])
255
+
256
+ return grad_image, grad_src, grad_dc, grad_duv, None, None, None
223
257
 
224
258
 
225
259
  class FanFootprintBackprojectorFunction(torch.autograd.Function):
@@ -318,13 +352,14 @@ class ConeFootprintProjectorFunction(torch.autograd.Function):
318
352
  cx, cy, cz, _DTYPE(voxel_spacing)
319
353
  )
320
354
 
321
- ctx.save_for_backward(src_pos, det_center, det_u_vec, det_v_vec)
355
+ # volume saved for the (optional) finite-difference geometry gradients.
356
+ ctx.save_for_backward(volume, src_pos, det_center, det_u_vec, det_v_vec)
322
357
  ctx.intermediate = (D, H, W, det_u, det_v, du, dv, voxel_spacing)
323
358
  return sino
324
359
 
325
360
  @staticmethod
326
361
  def backward(ctx, grad_sino):
327
- src_pos, det_center, det_u_vec, det_v_vec = ctx.saved_tensors
362
+ volume, src_pos, det_center, det_u_vec, det_v_vec = ctx.saved_tensors
328
363
  D, H, W, det_u, det_v, du, dv, voxel_spacing = ctx.intermediate
329
364
  device = DeviceManager.get_device(grad_sino)
330
365
  grad_sino = _to_f32_contig(DeviceManager.ensure_device(grad_sino, device))
@@ -352,7 +387,23 @@ class ConeFootprintProjectorFunction(torch.autograd.Function):
352
387
  cx, cy, cz, _DTYPE(voxel_spacing)
353
388
  )
354
389
  grad_volume = grad_vol_perm.permute(2, 1, 0).contiguous() # (D, H, W)
355
- return grad_volume, None, None, None, None, None, None, None, None, None
390
+ grad_src = grad_dc = grad_duv = grad_dvv = None
391
+ if any(ctx.needs_input_grad[1:5]):
392
+ # Finite-difference geometry VJPs of the footprint forward model
393
+ # (the separable footprint is piecewise-smooth in the geometry, so
394
+ # central differences give well-behaved smoothed gradients).
395
+ def _launch(src_p, det_c, det_uv, det_vv):
396
+ with torch.no_grad():
397
+ return ConeFootprintProjectorFunction.apply(
398
+ volume, src_p, det_c, det_uv, det_vv,
399
+ det_u, det_v, du, dv, voxel_spacing)
400
+
401
+ grad_src, grad_dc, grad_duv, grad_dvv = _fd_geometry_grads(
402
+ _launch, [src_pos, det_center, det_u_vec, det_v_vec],
403
+ ctx.needs_input_grad[1:5], grad_sino,
404
+ [_FD_REL_EPS_POS, _FD_REL_EPS_POS, _FD_REL_EPS_VEC, _FD_REL_EPS_VEC])
405
+
406
+ return grad_volume, grad_src, grad_dc, grad_duv, grad_dvv, None, None, None, None, None
356
407
 
357
408
 
358
409
  class ConeFootprintBackprojectorFunction(torch.autograd.Function):
@@ -20,6 +20,7 @@ from .cone_beam import (
20
20
  _cone_3d_forward_kernel,
21
21
  _cone_3d_backward_kernel,
22
22
  _cone_3d_fdk_backproject_kernel,
23
+ _cone_3d_geometry_grad_kernel,
23
24
  )
24
25
 
25
26
  __all__ = [
@@ -32,4 +33,5 @@ __all__ = [
32
33
  '_cone_3d_forward_kernel',
33
34
  '_cone_3d_backward_kernel',
34
35
  '_cone_3d_fdk_backproject_kernel',
36
+ '_cone_3d_geometry_grad_kernel',
35
37
  ]
@@ -575,3 +575,245 @@ def _cone_3d_fdk_backproject_kernel(
575
575
  accum += w * sample
576
576
 
577
577
  d_vol[ix, iy, iz] = accum
578
+
579
+
580
+ @_FASTMATH_DECORATOR
581
+ def _cone_3d_geometry_grad_kernel(
582
+ d_vol, Nx, Ny, Nz,
583
+ d_cot, n_views, n_u, n_v,
584
+ du, dv, d_src_pos, d_det_center, d_det_u_vec, d_det_v_vec,
585
+ cx, cy, cz, voxel_spacing,
586
+ d_grad_src, d_grad_dc, d_grad_duv, d_grad_dvv,
587
+ ):
588
+ """Analytic geometry gradients of the cone-beam line integral.
589
+
590
+ For each detector ray, differentiates the continuous line integral
591
+ ``a = int mu(s + t*(p - s)/L) dt`` w.r.t. the ray endpoints (source ``s``
592
+ and detector pixel ``p``), evaluated with a TRILINEARLY interpolated
593
+ ``mu`` so the spatial gradient exists (the cell-constant forward model is
594
+ piecewise constant; the trilinear model is its canonical smoothing — the
595
+ same convention as the MLX analytic geometry kernel):
596
+
597
+ da/ds = int (1-lambda) grad_mu dt + d_hat * int lambda (grad_mu . d_hat) dt
598
+ da/dp = int lambda grad_mu dt - d_hat * int lambda (grad_mu . d_hat) dt
599
+
600
+ with ``lambda = t / L``. (The projected moment ``S = int lambda
601
+ (grad_mu . d_hat) dt`` equals ``-A/L`` for rays whose mu vanishes at the
602
+ volume boundary, but it is accumulated with the same segment quadrature as
603
+ the G terms — substituting the closed form would subtract two large terms
604
+ with different quadrature errors and leave a systematic per-ray bias that
605
+ dominates the translation gradients.) Gradients for ``det_center`` /
606
+ ``det_v_vec`` follow from ``p = det_center + u_off * u_vec + v_off * v_vec``
607
+ by the chain rule. The traversal happens in voxel coordinates (positions
608
+ divided by ``voxel_spacing``) and the forward returns voxel-unit line
609
+ integrals, so millimetre-space gradients carry a ``1 / voxel_spacing``
610
+ factor (u/v offsets in mm cancel it for the vector gradients).
611
+
612
+ Grid: ``(iv, iu, iview) = cuda.grid(3)`` — one thread per detector ray;
613
+ per-view gradients are accumulated with atomics.
614
+ """
615
+ iv, iu, iview = cuda.grid(3)
616
+ if iview >= n_views or iu >= n_u or iv >= n_v:
617
+ return
618
+
619
+ g = d_cot[iview, iu, iv]
620
+ if g == _ZERO:
621
+ return
622
+
623
+ eps = _EPSILON
624
+
625
+ src_x = d_src_pos[iview, 0] / voxel_spacing
626
+ src_y = d_src_pos[iview, 1] / voxel_spacing
627
+ src_z = d_src_pos[iview, 2] / voxel_spacing
628
+
629
+ det_cx = d_det_center[iview, 0] / voxel_spacing
630
+ det_cy = d_det_center[iview, 1] / voxel_spacing
631
+ det_cz = d_det_center[iview, 2] / voxel_spacing
632
+
633
+ u_vec_x = d_det_u_vec[iview, 0]
634
+ u_vec_y = d_det_u_vec[iview, 1]
635
+ u_vec_z = d_det_u_vec[iview, 2]
636
+
637
+ v_vec_x = d_det_v_vec[iview, 0]
638
+ v_vec_y = d_det_v_vec[iview, 1]
639
+ v_vec_z = d_det_v_vec[iview, 2]
640
+
641
+ # Detector pixel offsets — package-wide (k - n/2) grid convention.
642
+ u_off_mm = (np.float32(iu) - np.float32(n_u) * _HALF) * du
643
+ v_off_mm = (np.float32(iv) - np.float32(n_v) * _HALF) * dv
644
+ u_off_vox = u_off_mm / voxel_spacing
645
+ v_off_vox = v_off_mm / voxel_spacing
646
+
647
+ det_x = det_cx + u_off_vox * u_vec_x + v_off_vox * v_vec_x
648
+ det_y = det_cy + u_off_vox * u_vec_y + v_off_vox * v_vec_y
649
+ det_z = det_cz + u_off_vox * u_vec_z + v_off_vox * v_vec_z
650
+
651
+ dir_x = det_x - src_x
652
+ dir_y = det_y - src_y
653
+ dir_z = det_z - src_z
654
+ length = math.sqrt(dir_x * dir_x + dir_y * dir_y + dir_z * dir_z)
655
+ if length < eps:
656
+ return
657
+ inv_len = _ONE / length
658
+ dir_x *= inv_len
659
+ dir_y *= inv_len
660
+ dir_z *= inv_len
661
+
662
+ t_min = -_INF
663
+ t_max = _INF
664
+
665
+ if abs(dir_x) > eps:
666
+ tx1 = (-cx - src_x) / dir_x
667
+ tx2 = (cx - src_x) / dir_x
668
+ t_min = max(t_min, min(tx1, tx2))
669
+ t_max = min(t_max, max(tx1, tx2))
670
+ elif src_x < -cx or src_x > cx:
671
+ return
672
+
673
+ if abs(dir_y) > eps:
674
+ ty1 = (-cy - src_y) / dir_y
675
+ ty2 = (cy - src_y) / dir_y
676
+ t_min = max(t_min, min(ty1, ty2))
677
+ t_max = min(t_max, max(ty1, ty2))
678
+ elif src_y < -cy or src_y > cy:
679
+ return
680
+
681
+ if abs(dir_z) > eps:
682
+ tz1 = (-cz - src_z) / dir_z
683
+ tz2 = (cz - src_z) / dir_z
684
+ t_min = max(t_min, min(tz1, tz2))
685
+ t_max = min(t_max, max(tz1, tz2))
686
+ elif src_z < -cz or src_z > cz:
687
+ return
688
+
689
+ if t_min >= t_max:
690
+ return
691
+
692
+ g1x = _ZERO
693
+ g1y = _ZERO
694
+ g1z = _ZERO
695
+ g2x = _ZERO
696
+ g2y = _ZERO
697
+ g2z = _ZERO
698
+ s_proj = _ZERO
699
+
700
+ t = t_min
701
+ ix = int(math.floor(src_x + t * dir_x + cx))
702
+ iy = int(math.floor(src_y + t * dir_y + cy))
703
+ iz = int(math.floor(src_z + t * dir_z + cz))
704
+
705
+ step_x = 1 if dir_x >= _ZERO else -1
706
+ step_y = 1 if dir_y >= _ZERO else -1
707
+ step_z = 1 if dir_z >= _ZERO else -1
708
+
709
+ inv_dir_x = _ONE / dir_x if abs(dir_x) > eps else _ZERO
710
+ inv_dir_y = _ONE / dir_y if abs(dir_y) > eps else _ZERO
711
+ inv_dir_z = _ONE / dir_z if abs(dir_z) > eps else _ZERO
712
+ dt_x = abs(inv_dir_x) if abs(dir_x) > eps else _INF
713
+ dt_y = abs(inv_dir_y) if abs(dir_y) > eps else _INF
714
+ dt_z = abs(inv_dir_z) if abs(dir_z) > eps else _INF
715
+
716
+ txn = (np.float32(ix + (1 if step_x > 0 else 0)) - cx - src_x) * inv_dir_x if abs(dir_x) > eps else _INF
717
+ tyn = (np.float32(iy + (1 if step_y > 0 else 0)) - cy - src_y) * inv_dir_y if abs(dir_y) > eps else _INF
718
+ tzn = (np.float32(iz + (1 if step_z > 0 else 0)) - cz - src_z) * inv_dir_z if abs(dir_z) > eps else _INF
719
+
720
+ while t < t_max:
721
+ if 0 <= ix < Nx and 0 <= iy < Ny and 0 <= iz < Nz:
722
+ t_next = min(min(min(txn, tyn), tzn), t_max)
723
+ seg_len = t_next - t
724
+
725
+ if seg_len > eps:
726
+ t_mid = t + seg_len * _HALF
727
+ mid_x = src_x + t_mid * dir_x + cx
728
+ mid_y = src_y + t_mid * dir_y + cy
729
+ mid_z = src_z + t_mid * dir_z + cz
730
+
731
+ # Trilinear cell around the segment midpoint (voxel CENTERS at
732
+ # k + 0.5, so shift by -0.5 before flooring).
733
+ fx = mid_x - _HALF
734
+ fy = mid_y - _HALF
735
+ fz = mid_z - _HALF
736
+ ix0 = int(math.floor(fx))
737
+ iy0 = int(math.floor(fy))
738
+ iz0 = int(math.floor(fz))
739
+ dx = fx - np.float32(ix0)
740
+ dy = fy - np.float32(iy0)
741
+ dz = fz - np.float32(iz0)
742
+
743
+ ix0 = max(0, min(ix0, Nx - 2))
744
+ iy0 = max(0, min(iy0, Ny - 2))
745
+ iz0 = max(0, min(iz0, Nz - 2))
746
+
747
+ omdx = _ONE - dx
748
+ omdy = _ONE - dy
749
+ omdz = _ONE - dz
750
+
751
+ v000 = d_vol[ix0, iy0, iz0]
752
+ v100 = d_vol[ix0 + 1, iy0, iz0]
753
+ v010 = d_vol[ix0, iy0 + 1, iz0]
754
+ v001 = d_vol[ix0, iy0, iz0 + 1]
755
+ v110 = d_vol[ix0 + 1, iy0 + 1, iz0]
756
+ v101 = d_vol[ix0 + 1, iy0, iz0 + 1]
757
+ v011 = d_vol[ix0, iy0 + 1, iz0 + 1]
758
+ v111 = d_vol[ix0 + 1, iy0 + 1, iz0 + 1]
759
+
760
+ dmu_x = (omdy * omdz * (v100 - v000) + dy * omdz * (v110 - v010)
761
+ + omdy * dz * (v101 - v001) + dy * dz * (v111 - v011))
762
+ dmu_y = (omdx * omdz * (v010 - v000) + dx * omdz * (v110 - v100)
763
+ + omdx * dz * (v011 - v001) + dx * dz * (v111 - v101))
764
+ dmu_z = (omdx * omdy * (v001 - v000) + dx * omdy * (v101 - v100)
765
+ + omdx * dy * (v011 - v010) + dx * dy * (v111 - v110))
766
+
767
+ lam = t_mid * inv_len
768
+ w1 = seg_len * (_ONE - lam)
769
+ w2 = seg_len * lam
770
+
771
+ g1x += w1 * dmu_x
772
+ g1y += w1 * dmu_y
773
+ g1z += w1 * dmu_z
774
+ g2x += w2 * dmu_x
775
+ g2y += w2 * dmu_y
776
+ g2z += w2 * dmu_z
777
+ s_proj += w2 * (dmu_x * dir_x + dmu_y * dir_y + dmu_z * dir_z)
778
+
779
+ if txn <= tyn and txn <= tzn:
780
+ t = txn
781
+ ix += step_x
782
+ txn += dt_x
783
+ elif tyn <= txn and tyn <= tzn:
784
+ t = tyn
785
+ iy += step_y
786
+ tyn += dt_y
787
+ else:
788
+ t = tzn
789
+ iz += step_z
790
+ tzn += dt_z
791
+
792
+ # Voxel-space endpoint gradients; the forward returns voxel-unit line
793
+ # integrals of positions given in mm/voxel_spacing, so mm-space gradients
794
+ # carry 1/voxel_spacing.
795
+ inv_vs = _ONE / voxel_spacing
796
+
797
+ gs_x = g * (g1x + dir_x * s_proj) * inv_vs
798
+ gs_y = g * (g1y + dir_y * s_proj) * inv_vs
799
+ gs_z = g * (g1z + dir_z * s_proj) * inv_vs
800
+
801
+ gp_x = g * (g2x - dir_x * s_proj) * inv_vs
802
+ gp_y = g * (g2y - dir_y * s_proj) * inv_vs
803
+ gp_z = g * (g2z - dir_z * s_proj) * inv_vs
804
+
805
+ cuda.atomic.add(d_grad_src, (iview, 0), gs_x)
806
+ cuda.atomic.add(d_grad_src, (iview, 1), gs_y)
807
+ cuda.atomic.add(d_grad_src, (iview, 2), gs_z)
808
+
809
+ cuda.atomic.add(d_grad_dc, (iview, 0), gp_x)
810
+ cuda.atomic.add(d_grad_dc, (iview, 1), gp_y)
811
+ cuda.atomic.add(d_grad_dc, (iview, 2), gp_z)
812
+
813
+ cuda.atomic.add(d_grad_duv, (iview, 0), u_off_mm * gp_x)
814
+ cuda.atomic.add(d_grad_duv, (iview, 1), u_off_mm * gp_y)
815
+ cuda.atomic.add(d_grad_duv, (iview, 2), u_off_mm * gp_z)
816
+
817
+ cuda.atomic.add(d_grad_dvv, (iview, 0), v_off_mm * gp_x)
818
+ cuda.atomic.add(d_grad_dvv, (iview, 1), v_off_mm * gp_y)
819
+ cuda.atomic.add(d_grad_dvv, (iview, 2), v_off_mm * gp_z)
@@ -15,6 +15,8 @@ from .utils import (
15
15
  _grid_2d,
16
16
  _grid_3d,
17
17
  )
18
+ import os
19
+
18
20
  from .kernels import (
19
21
  _parallel_2d_forward_kernel,
20
22
  _parallel_2d_backward_kernel,
@@ -22,6 +24,7 @@ from .kernels import (
22
24
  _fan_2d_backward_kernel,
23
25
  _cone_3d_forward_kernel,
24
26
  _cone_3d_backward_kernel,
27
+ _cone_3d_geometry_grad_kernel,
25
28
  )
26
29
 
27
30
 
@@ -48,6 +51,11 @@ from .kernels import (
48
51
  _FD_REL_EPS_POS = 1e-3 # relative step for position-like arrays (src, det center)
49
52
  _FD_REL_EPS_VEC = 1e-2 # relative step for direction-vector arrays
50
53
 
54
+ # Cone geometry gradients: "analytic" (default — one closed-form kernel pass,
55
+ # gradients for all four geometry arrays; see _cone_3d_geometry_grad_kernel)
56
+ # or "fd" (finite differences of the forward kernel, 6 passes per array).
57
+ _GEOMETRY_VJP_MODE = os.getenv("DIFFCT_GEOMETRY_VJP", "analytic").strip().lower()
58
+
51
59
 
52
60
  def _fd_eps(geom, rel):
53
61
  scale = float(geom.abs().max())
@@ -882,12 +890,41 @@ class ConeProjectorFunction(torch.autograd.Function):
882
890
 
883
891
  grad_vol = grad_vol_perm.permute(2, 1, 0).contiguous()
884
892
 
885
- # Optional finite-difference geometry gradients (only when requested).
893
+ # Optional geometry gradients (only when requested).
886
894
  grad_src = grad_dc = grad_duv = grad_dvv = None
887
895
  if any(ctx.needs_input_grad[1:5]):
888
896
  volume_perm = volume.to(dtype=torch.float32).contiguous().permute(2, 1, 0).contiguous()
889
897
  d_vol = TorchCUDABridge.tensor_to_cuda_array(volume_perm)
890
898
 
899
+ if _GEOMETRY_VJP_MODE != "fd":
900
+ # Analytic geometry gradients: one kernel pass yields all four
901
+ # arrays (per-ray closed form contracted with the cotangent).
902
+ grad_src = torch.zeros_like(src_pos)
903
+ grad_dc = torch.zeros_like(det_center)
904
+ grad_duv = torch.zeros_like(det_u_vec)
905
+ grad_dvv = torch.zeros_like(det_v_vec)
906
+ _cone_3d_geometry_grad_kernel[grid, tpb, numba_stream](
907
+ d_vol, W, H, D,
908
+ d_grad_sino, n_views, det_u, det_v,
909
+ _DTYPE(du), _DTYPE(dv),
910
+ d_src_pos_arr, d_det_center_arr, d_det_u_vec_arr, d_det_v_vec_arr,
911
+ cx, cy, cz, _DTYPE(voxel_spacing),
912
+ TorchCUDABridge.tensor_to_cuda_array(grad_src),
913
+ TorchCUDABridge.tensor_to_cuda_array(grad_dc),
914
+ TorchCUDABridge.tensor_to_cuda_array(grad_duv),
915
+ TorchCUDABridge.tensor_to_cuda_array(grad_dvv),
916
+ )
917
+ if not ctx.needs_input_grad[1]:
918
+ grad_src = None
919
+ if not ctx.needs_input_grad[2]:
920
+ grad_dc = None
921
+ if not ctx.needs_input_grad[3]:
922
+ grad_duv = None
923
+ if not ctx.needs_input_grad[4]:
924
+ grad_dvv = None
925
+ return (grad_vol, grad_src, grad_dc, grad_duv, grad_dvv,
926
+ None, None, None, None, None)
927
+
891
928
  def _launch(src_p, det_c, det_uv, det_vv):
892
929
  sino = torch.zeros((n_views, det_u, det_v), dtype=torch.float32, device=device)
893
930
  _cone_3d_forward_kernel[grid, tpb, numba_stream](
@@ -199,7 +199,7 @@ from .tv_gradients import (
199
199
  awtv_gradient,
200
200
  )
201
201
 
202
- __version__ = "2.0.0"
202
+ __version__ = "2.0.1"
203
203
 
204
204
  __all__ = [
205
205
  "backend",