GeezerVison is showing github.com — fix: harden the remaining MPS review corners · cslht11/diffct@aa4d45f
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: README.md +1-1Lines changed: 1 addition & 1 deletion - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
| 35 | 35 | </p> | 36 | 36 |
| 37 | 37 | > **Version 2.0** replaces the circular-orbit API of 1.x with per-view trajectories. Code written for 1.x needs changes; see the [migration notes](https://github.com/sypsyp97/diffct/blob/main/docs/MIGRATION.md). | 38 | | -> For Apple Silicon, use the [MLX port by Linda-Sophie Schneider](https://github.com/Linda-SophieSchneider/DiffCT-MLX). | | 38 | +> Apple Silicon runs through the built-in MPS support (`backend="torch"`); a community [MLX port by Linda-Sophie Schneider](https://github.com/Linda-SophieSchneider/DiffCT-MLX) also exists. | 39 | 39 |
| 40 | 40 | This README describes the source checkout. Features listed under [Unreleased](CHANGELOG.md#unreleased) require installation from source. | 41 | 41 |
| |
Collapse file Copy file name to clipboardExpand all lines: diffct/backends.py +4-1Lines changed: 4 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -1105,7 +1105,10 @@ def _zero_to(value, device): | 1105 | 1105 | zero = _zero_dependency(value) | 1106 | 1106 | target_dtype = _work_dtype(device) | 1107 | 1107 | if zero.dtype.itemsize > target_dtype.itemsize: | 1108 | | - return zero.to(device=device, dtype=target_dtype) | | 1108 | + # Cast on the source device first: a fused device and dtype | | 1109 | + # copy routes the float64 gradient back through the | | 1110 | + # FP64-less device on the way out. | | 1111 | + return zero.to(dtype=target_dtype).to(device=device) | 1109 | 1112 | return zero.to(device=device) | 1110 | 1113 |
| 1111 | 1114 | loss = loss + sum(_zero_to(value, loss.device) for value in inputs) | |
Collapse file Copy file name to clipboardExpand all lines: diffct/operators.py +3-3Lines changed: 3 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -138,9 +138,9 @@ def _validate_trajectory(trajectory, beam, *, detector_surface=False, clone=True | 138 | 138 | checks.append((torch.any(torch.linalg.matrix_rank(frame) < 3), | 139 | 139 | "parallel3d rays must not be tangent to the detector plane")) | 140 | 140 | else: | 141 | | - # |det| via the triple product: matrix_rank has no MPS kernel. The | 142 | | - # float32 criterion is looser than the FP64 rank check, but still | 143 | | - # rejects near-tangent frames at practical geometry scales. | | 141 | + # |det| via the triple product: matrix_rank has no MPS kernel. Its | | 142 | + # float32 threshold sits far above the FP64 rank tolerance, so it | | 143 | + # rejects a wider band of near-tangent frames than the FP64 check. | 144 | 144 | determinant = torch.sum(frame[..., 0] * torch.linalg.cross(frame[..., 1], frame[..., 2], dim=-1), dim=-1) | 145 | 145 | scale = torch.linalg.vector_norm(frame, dim=-2).prod(dim=-1) | 146 | 146 | checks.append((torch.any(determinant.abs() <= torch.finfo(determinant.dtype).eps * scale), | |
Collapse file Copy file name to clipboardExpand all lines: diffct/reconstruction.py +2-3Lines changed: 2 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -478,10 +478,9 @@ def helical_fdk(sinogram, trajectory, volume_shape, angles, *, isocenter, | 478 | 478 | if not torch.allclose(torch.cos(phase - phase[0]), torch.ones_like(phase), rtol=0, atol=1e-5): | 479 | 479 | raise ValueError("angles must describe the source's actual unwrapped rotation") | 480 | 480 | if view_weights is None: | 481 | | - z = (torch.arange(shape[0], device="cpu", dtype=torch.float64) | | 481 | + z = (torch.arange(shape[0], device=sinogram.device, dtype=torch.float64) | 482 | 482 | + 0.5 - shape[0] / 2) * (spacing[0] if isinstance(spacing, tuple) else spacing) | 483 | | - view_weights = helical_view_weights(angles.cpu(), geometry[0][:, 2].cpu(), z) | 484 | | - view_weights = view_weights.to(device=sinogram.device) | | 483 | + view_weights = helical_view_weights(angles, geometry[0][:, 2], z) | 485 | 484 | else: | 486 | 485 | # Still validate the acquired order when a caller replaces the windows. | 487 | 486 | difference = angles[1:] - angles[:-1] | |
Collapse file Copy file name to clipboardExpand all lines: tests/test_mps_backend.py +37Lines changed: 37 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -215,6 +215,43 @@ def run(device): | 215 | 215 | torch.testing.assert_close(cpu_grad, mps_grad, rtol=2e-3, atol=2e-2) | 216 | 216 |
| 217 | 217 |
| | 218 | +@mps | | 219 | +def test_mps_learnable_cpu_fp64_trajectory_stays_consistent(): | | 220 | + # A learnable FP64 trajectory on the host projecting an MPS volume keeps | | 221 | + # working end to end; its forward matches the learnable FP32 trajectory | | 222 | + # on the same device (both clamp to the MPS working dtype), and the | | 223 | + # geometry gradients stay finite and non-zero. | | 224 | + def forward(leaves): | | 225 | + torch.manual_seed(7) | | 226 | + projector = Projector(leaves, volume_shape=(8, 8, 8), detector_shape=(12, 12), | | 227 | + backend="torch", precision="fast") | | 228 | + sinogram = projector(torch.rand(8, 8, 8, device="mps")) | | 229 | + sinogram.sum().backward() | | 230 | + return sinogram.detach().cpu(), [leaf.grad.cpu() for leaf in leaves] | | 231 | + | | 232 | + trajectory = circular_trajectory_3d(6, sid=800.0, sdd=1200.0, | | 233 | + device="cpu", dtype=torch.float64) | | 234 | + leaves64 = tuple(c.clone().requires_grad_() for c in trajectory) | | 235 | + leaves32 = tuple(c.float().clone().requires_grad_() for c in trajectory) | | 236 | + sinogram64, grads64 = forward(leaves64) | | 237 | + sinogram32, _ = forward(leaves32) | | 238 | + assert (sinogram64 - sinogram32).norm() / sinogram32.norm() < 1e-4 | | 239 | + for gradient in grads64: | | 240 | + assert torch.isfinite(gradient).all() and gradient.abs().max() > 0 | | 241 | + | | 242 | + | | 243 | +@mps | | 244 | +def test_mps_norm_result_keeps_the_float64_range(): | | 245 | + from diffct._solver_state import squared_norm | | 246 | + class Solo: | | 247 | + world_size = 1 | | 248 | + value = torch.full((100,), 2.0, device="mps", dtype=torch.float32) | | 249 | + result = squared_norm(Solo(), value, "rays", return_tensor=True) | | 250 | + assert isinstance(result, torch.Tensor) and result.device.type == "cpu" | | 251 | + assert result.dtype == torch.float64 and result.ndim == 0 | | 252 | + assert abs(result.item() - 400.0) < 1e-2 | | 253 | + | | 254 | + | 218 | 255 | @mps | 219 | 256 | def test_mps_norms_survive_a_float64_default_dtype(): | 220 | 257 | from diffct._solver_state import squared_norm | |
|