Skip to content

Commit c5bddb2

Browse files
Fix compiled lazy resampling with align_corners=True (#9248)
Related to #9112. ### Description Fixes lazy resampling with the compiled extension (`BUILD_MONAI=1`) when `align_corners=True`, following @ericspod's confirmation that the native `grid_sample` path is the reference. In `spatial_resample`, the compiled branch builds `Affine(affine=xform, normalized=True, align_corners=True)` from a matrix that is already in voxel space. `AffineGrid` and the compiled `Resample` then apply the `align_corners=True` scalings (`d_out/(d_out-1)` and `(d_in-1)/d_in`) on top of it, distorting the grid passed to `grid_pull`. For non-integer `mode`, the matrix is now pre-compensated so those scalings cancel. Integer `mode` is unchanged. Verification (`BUILD_MONAI=1` unless noted): - `test_affine` + `test_affined`: 132 failed -> 0 failed. - Wider set (spacing, resize, zoom, rotate, rand_* transforms): 10 failed -> 0 failed. Default (non-compiled) run: 0 failed, unchanged. - Eager `Spacing` vs a plain `F.grid_sample(align_corners=True)` reference on three shapes: compiled was 0.2 to 0.5 off before, ~2e-7 after (native ~3e-8). - Reproduces on CPU too, so not GPU-specific. Test changes: - Added `test_lazy_rotate_align_corners_compiled` (skipped unless the extension is compiled). It fails without the fix and passes with it. - `_TEMPLATE_5_COMPILED` in `test_spacing.py` changed from 0.75 to 1.0. All sampled input coordinates for that case lie inside the image and the input is all ones, so 1.0 is the geometrically correct value. The native template (0.9553) looks like a unit-size-axis artifact and is untouched. Note: `BUILD_MONAI=1` must be set at runtime, not only at build time, for these tests to exercise the compiled path. Tested locally on RTX 3050 / WSL2 / PyTorch 2.14.1+cu132 (outside CI's range); not run on PyTorch 2.8 to 2.11 or through the full `./runtests.sh`. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [x] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [ ] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: Vikas Reddy <vikasreddy1090@gmail.com> Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
1 parent 0e9fc83 commit c5bddb2

3 files changed

Lines changed: 61 additions & 3 deletions

File tree

‎monai/transforms/spatial/functional.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
import math
1818
import warnings
19+
from collections.abc import Sequence
1920
from enum import Enum
2021

2122
import numpy as np
@@ -106,6 +107,41 @@ def _maybe_new_metatensor(img, dtype=None, device=None):
106107
)
107108

108109

110+
def _cancel_align_corners_scaling(
111+
xform: torch.Tensor, in_spatial_size: Sequence[int], out_spatial_size: Sequence[int]
112+
) -> torch.Tensor:
113+
"""
114+
Pre-compensate a voxel-space affine for the scalings applied again downstream when
115+
``align_corners=True`` and the compiled ``Resample`` path is used.
116+
117+
``xform`` is already expressed in voxel space. However, ``Affine`` passes it through ``AffineGrid``,
118+
which applies a ``d_out / (d_out - 1)`` scaling per spatial dimension, and the compiled ``Resample``
119+
applies a ``(d_in - 1) / d_in`` scaling before ``grid_pull``. This function returns
120+
``T @ S_inv @ xform @ D_inv``, where ``S_inv`` and ``D_inv`` cancel those two scalings and ``T`` is a
121+
translation by -0.5 voxel that re-centres the result, so that ``grid_pull`` receives the original
122+
``xform`` unchanged.
123+
124+
Dimensions are clamped to a minimum of 2 to avoid division by zero for singleton axes.
125+
126+
Args:
127+
xform: homogeneous affine of shape ``(rank + 1, rank + 1)`` in voxel space.
128+
in_spatial_size: spatial shape of the input image.
129+
out_spatial_size: spatial shape of the resampled output.
130+
131+
Returns:
132+
the compensated homogeneous affine, same shape, dtype and device as ``xform``.
133+
"""
134+
rank = len(xform) - 1
135+
eye = torch.eye(rank + 1, dtype=xform.dtype, device=xform.device)
136+
s_inv, d_inv, translate = eye.clone(), eye.clone(), eye.clone()
137+
for i in range(rank):
138+
d_in, d_out = max(2, int(in_spatial_size[i])), max(2, int(out_spatial_size[i]))
139+
s_inv[i, i] = d_in / (d_in - 1)
140+
d_inv[i, i] = (d_out - 1) / d_out
141+
translate[i, -1] = -0.5
142+
return translate @ s_inv @ xform @ d_inv
143+
144+
109145
def spatial_resample(
110146
img, dst_affine, spatial_size, mode, padding_mode, align_corners, dtype_pt, lazy, transform_info
111147
) -> torch.Tensor:
@@ -216,6 +252,8 @@ def spatial_resample(
216252
if isinstance(mode, int) or _use_compiled:
217253
dst_xform = create_translate(spatial_rank, [float(d - 1) / 2 for d in spatial_size])
218254
xform = xform @ convert_to_dst_type(dst_xform, xform)[0]
255+
if align_corners and not isinstance(mode, int):
256+
xform = _cancel_align_corners_scaling(xform, in_sp_size, spatial_size)
219257
affine_xform = monai.transforms.Affine(
220258
affine=xform,
221259
spatial_size=spatial_size,

‎tests/transforms/test_affine.py‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@
1919
from parameterized import parameterized
2020

2121
from monai.data import MetaTensor, set_track_meta
22-
from monai.transforms import Affine, Resize
22+
from monai.transforms import Affine, RandRotate, Resize
2323
from monai.transforms.lazy.functional import apply_pending
2424
from monai.utils import optional_import
25-
from tests.lazy_transforms_utils import test_resampler_lazy
25+
from tests.lazy_transforms_utils import get_apply_param, test_resampler_lazy
2626
from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, test_local_inversion
2727

2828
TESTS = []
@@ -291,6 +291,26 @@ def method_3(im, ac):
291291
ref = Resize(align_corners=ac, spatial_size=(sp_size, sp_size), mode="bilinear")(im)
292292
assert_allclose(out, ref, rtol=1e-4, atol=1e-4, type_test=False)
293293

294+
def test_lazy_rotate_align_corners_compiled(self):
295+
"""lazy resampling with the compiled backend and align_corners=True must match eager."""
296+
init = dict(
297+
range_x=np.pi,
298+
prob=1.0,
299+
keep_size=False,
300+
mode="nearest",
301+
padding_mode="zeros",
302+
dtype=np.float64,
303+
align_corners=True,
304+
)
305+
img = MetaTensor(torch.arange(64 * 48, dtype=torch.float32).reshape(1, 64, 48))
306+
xform = RandRotate(**init)
307+
xform.set_random_state(seed=243)
308+
eager = xform(img)
309+
xform.set_random_state(seed=243)
310+
xform.lazy = True
311+
lazy = apply_pending(xform(img), overrides=get_apply_param(init, {"img": img}))[0]
312+
assert_allclose(lazy, eager, rtol=1e-3, atol=1e-3)
313+
294314

295315
if __name__ == "__main__":
296316
unittest.main()

‎tests/transforms/test_spacing.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
from tests.lazy_transforms_utils import test_resampler_lazy
2828
from tests.test_utils import TEST_DEVICES, TEST_NDARRAYS_ALL, assert_allclose, dict_product, skip_if_quick
2929

30-
_TEMPLATE_5_COMPILED = torch.tensor([[[[0.75, 0.75]], [[0.75, 0.75]], [[0.75, 0.75]]]])
30+
_TEMPLATE_5_COMPILED = torch.tensor([[[[1.0, 1.0]], [[1.0, 1.0]], [[1.0, 1.0]]]])
3131
_TEMPLATE_5_NATIVE = torch.tensor([[[[0.95527864, 0.95527864]], [[1.0, 1.0]], [[1.0, 1.0]]]])
3232

3333

0 commit comments

Comments
 (0)