Skip to content

Commit 9c3b441

Browse files
Use compact [1,-2,1] kernel for BendingEnergyLoss second derivatives (#8918)
Fixes #5939. ### Summary `BendingEnergyLoss` previously computed second-order derivatives by applying the central first-order helper `spatial_gradient` twice, which yields a wide `[1, 0, -2, 0, 1] / 4` stencil for pure second derivatives that spans four voxels per axis. That stencil is less accurate than the standard compact one and forced the validation "all spatial dims > 4". This PR replaces the second-order computation with compact central stencils evaluated directly on `pred`: - **Pure** ``d^2/dx_i^2``: ``x[i+1] - 2 * x[i] + x[i-1]`` (the standard `[1, -2, 1]` kernel). - **Mixed** ``d^2/(dx_i dx_j)``: ``(x[i+1,j+1] - x[i+1,j-1] - x[i-1,j+1] + x[i-1,j-1]) / 4`` (compact 4-point central scheme). Both span three voxels per axis, so the spatial-size validation is relaxed from `> 4` to `> 2`, matching `DiffusionLoss`. The public API (`__init__(normalize, reduction)`, `forward(pred)`) and `normalize` semantics are unchanged. The existing `spatial_gradient` helper is left untouched because `DiffusionLoss` still uses it. ### Why TEST_CASES expected values do not change For ``f(x) = x^2``, the analytical second derivative is the constant `2`. Both the previous central-of-central stencil ``(f[i+2] - 2*f[i] + f[i-2]) / 4`` and the new compact ``[1, -2, 1]`` stencil ``f[i+1] - 2*f[i] + f[i-1]`` are exact for quadratics, so both return `2` at every interior voxel. Mixed-partial test inputs are constant in at least one of the two axes, so both stencils return `0` for mixed terms on these cases. Squared and reduced by ``mean``, the existing `TEST_CASES` expected values (``0.0``, ``4.0``, ``100.0``) are therefore invariant under this change. What does change in the tests: - `test_ill_shape` is updated to trigger on shape `2` (was `4`) so it still exercises the spatial-size guard. - A new `TEST_CASES` row covers shape `(1, 3, 3, 3, 3)` of ones (previously rejected by the `> 4` guard) → expected `0.0`, validating the relaxed guard. Reference for the compact mixed-partial scheme: Pavel Holoborodko's finite-difference notes cited in the original issue. --------- Signed-off-by: Vishnu Kannaujia <vishnu.kannaujia@gmail.com> Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
1 parent b7d14c8 commit 9c3b441

2 files changed

Lines changed: 70 additions & 20 deletions

File tree

‎monai/losses/deform.py‎

Lines changed: 66 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,58 @@ def spatial_gradient(x: torch.Tensor, dim: int) -> torch.Tensor:
4444
return (x[slicing_s] - x[slicing_e]) / 2.0
4545

4646

47+
def spatial_gradient_squared(x: torch.Tensor, dim_1: int, dim_2: int) -> torch.Tensor:
48+
"""
49+
Calculate the second-order partial derivative of ``x`` with respect to spatial dims
50+
``dim_1`` and ``dim_2`` using compact central finite differences.
51+
52+
For ``dim_1 == dim_2`` the pure second derivative uses the ``[1, -2, 1]`` stencil:
53+
``d2x[i] = x[i+1] - 2 * x[i] + x[i-1]``.
54+
55+
For ``dim_1 != dim_2`` the mixed partial uses the compact 4-point stencil:
56+
``d2x[i, j] = (x[i+1, j+1] - x[i+1, j-1] - x[i-1, j+1] + x[i-1, j-1]) / 4``.
57+
58+
Every spatial dimension is sliced to ``[1:-1]`` so the output shape is independent of
59+
``(dim_1, dim_2)``; this lets terms be summed together. Requires ``x.shape[d] > 2``
60+
for every spatial dim ``d``.
61+
62+
Args:
63+
x: the shape should be BCH(WD).
64+
dim_1: first spatial dimension index.
65+
dim_2: second spatial dimension index.
66+
67+
Returns:
68+
Tensor with batch and channel axes preserved and every spatial axis sliced to
69+
``[1:-1]``.
70+
"""
71+
slice_inner = slice(1, -1)
72+
slice_plus = slice(2, None)
73+
slice_minus = slice(None, -2)
74+
slice_all = slice(None)
75+
76+
def _idx(overrides: dict) -> list:
77+
out: list = [slice_all, slice_all]
78+
for d in range(2, x.ndim):
79+
out.append(overrides.get(d, slice_inner))
80+
return out
81+
82+
if dim_1 == dim_2:
83+
return x[_idx({dim_1: slice_plus})] - 2 * x[_idx({})] + x[_idx({dim_1: slice_minus})]
84+
return (
85+
x[_idx({dim_1: slice_plus, dim_2: slice_plus})]
86+
- x[_idx({dim_1: slice_plus, dim_2: slice_minus})]
87+
- x[_idx({dim_1: slice_minus, dim_2: slice_plus})]
88+
+ x[_idx({dim_1: slice_minus, dim_2: slice_minus})]
89+
) / 4.0
90+
91+
4792
class BendingEnergyLoss(_Loss):
4893
"""
49-
Calculate the bending energy based on second-order differentiation of ``pred`` using central finite difference.
94+
Calculate the bending energy based on second-order differentiation of ``pred``.
95+
96+
Pure second derivatives use the compact ``[1, -2, 1]`` stencil; mixed partials use a
97+
compact 4-point central scheme. Both span three voxels per axis, so each spatial
98+
dimension of ``pred`` only needs to be greater than 2.
5099
51100
For more information,
52101
see https://github.com/Project-MONAI/tutorials/blob/main/modules/bending_energy_diffusion_loss_notes.ipynb.
@@ -79,41 +128,41 @@ def forward(self, pred: torch.Tensor) -> torch.Tensor:
79128
Raises:
80129
ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"].
81130
ValueError: When ``pred`` is not 3-d, 4-d or 5-d.
82-
ValueError: When any spatial dimension of ``pred`` has size less than or equal to 4.
131+
ValueError: When any spatial dimension of ``pred`` has size less than or equal to 2.
83132
ValueError: When the number of channels of ``pred`` does not match the number of spatial dimensions.
84133
85134
"""
86135
if pred.ndim not in [3, 4, 5]:
87136
raise ValueError(f"Expecting 3-d, 4-d or 5-d pred, instead got pred of shape {pred.shape}")
88137
for i in range(pred.ndim - 2):
89-
if pred.shape[-i - 1] <= 4:
90-
raise ValueError(f"All spatial dimensions must be > 4, got spatial dimensions {pred.shape[2:]}")
138+
if pred.shape[-i - 1] <= 2:
139+
raise ValueError(f"All spatial dimensions must be > 2, got spatial dimensions {pred.shape[2:]}")
91140
if pred.shape[1] != pred.ndim - 2:
92141
raise ValueError(
93142
f"Number of vector components, i.e. number of channels of the input DDF, {pred.shape[1]}, "
94143
f"does not match number of spatial dimensions, {pred.ndim - 2}"
95144
)
96145

97-
# first order gradient
98-
first_order_gradient = [spatial_gradient(pred, dim) for dim in range(2, pred.ndim)]
99-
100146
# spatial dimensions in a shape suited for broadcasting below
101147
if self.normalize:
102148
spatial_dims = torch.tensor(pred.shape, device=pred.device)[2:].reshape((1, -1) + (pred.ndim - 2) * (1,))
103149

104-
energy = torch.tensor(0)
105-
for dim_1, g in enumerate(first_order_gradient):
106-
dim_1 += 2
150+
# Initialize on pred.device so a GPU `pred` does not get added to a CPU
151+
# accumulator, and as a float so an integer-dtype `pred` still produces a
152+
# floating-point energy (the compact pure-derivative stencil has no
153+
# division, so a Long input would otherwise propagate as Long and fail
154+
# `torch.mean` at the reduction step).
155+
energy = torch.tensor(0.0, device=pred.device)
156+
for dim_1 in range(2, pred.ndim):
157+
d2 = spatial_gradient_squared(pred, dim_1, dim_1)
107158
if self.normalize:
108-
g *= pred.shape[dim_1] / spatial_dims
109-
energy = energy + (spatial_gradient(g, dim_1) * pred.shape[dim_1]) ** 2
110-
else:
111-
energy = energy + spatial_gradient(g, dim_1) ** 2
159+
d2 = d2 * (pred.shape[dim_1] ** 2 / spatial_dims)
160+
energy = energy + d2**2
112161
for dim_2 in range(dim_1 + 1, pred.ndim):
162+
d2_mixed = spatial_gradient_squared(pred, dim_1, dim_2)
113163
if self.normalize:
114-
energy = energy + 2 * (spatial_gradient(g, dim_2) * pred.shape[dim_2]) ** 2
115-
else:
116-
energy = energy + 2 * spatial_gradient(g, dim_2) ** 2
164+
d2_mixed = d2_mixed * (pred.shape[dim_1] * pred.shape[dim_2] / spatial_dims)
165+
energy = energy + 2 * d2_mixed**2
117166

118167
if self.reduction == LossReduction.MEAN.value:
119168
energy = torch.mean(energy) # the batch and channel average

‎tests/losses/deform/test_bending_energy.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
TEST_CASES = [
2525
[{}, {"pred": torch.ones((1, 3, 5, 5, 5), device=device)}, 0.0],
26+
[{}, {"pred": torch.ones((1, 3, 3, 3, 3), device=device)}, 0.0],
2627
[{}, {"pred": torch.arange(0, 5, device=device)[None, None, None, None, :].expand(1, 3, 5, 5, 5)}, 0.0],
2728
[
2829
{"normalize": False},
@@ -64,11 +65,11 @@ def test_ill_shape(self):
6465
with self.assertRaisesRegex(ValueError, "Expecting 3-d, 4-d or 5-d"):
6566
loss.forward(torch.ones((1, 4, 5, 5, 5, 5), device=device))
6667
with self.assertRaisesRegex(ValueError, "All spatial dimensions"):
67-
loss.forward(torch.ones((1, 3, 4, 5, 5), device=device))
68+
loss.forward(torch.ones((1, 3, 2, 5, 5), device=device))
6869
with self.assertRaisesRegex(ValueError, "All spatial dimensions"):
69-
loss.forward(torch.ones((1, 3, 5, 4, 5)))
70+
loss.forward(torch.ones((1, 3, 5, 2, 5)))
7071
with self.assertRaisesRegex(ValueError, "All spatial dimensions"):
71-
loss.forward(torch.ones((1, 3, 5, 5, 4)))
72+
loss.forward(torch.ones((1, 3, 5, 5, 2)))
7273

7374
# number of vector components unequal to number of spatial dims
7475
with self.assertRaisesRegex(ValueError, "Number of vector components"):

0 commit comments

Comments
 (0)