Skip to content

Commit e184689

Browse files
authored
Handle constant B-spline mutual information inputs (#9022)
Fixes #9018. ### Description B-spline global mutual information now remains finite when either prediction or target has a constant intensity range and for float16, bfloat16, or float32 inputs with tiny nonzero ranges. B-spline configurations with four or fewer bins are rejected because the implementation reserves two padding bins at each boundary. Gaussian configurations with one or fewer bins are rejected before bin-centre spacing is computed. The fix performs reduced-precision range, bin-width, and B-spline coordinate arithmetic in float32. Bin widths too small to be represented safely by the compute or input dtype are treated as a degenerate range. This prevents zero-range division, tiny-range underflow, unrepresentable normalization slopes, and cubic-distance overflow while preserving autograd back to the original input. ### Types of changes - [x] A 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`. - [x] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. ### Validation - zero-range and tiny-range regressions fail before the follow-up fix; - prediction-constant and target-constant paths are covered independently; - extreme-range coverage includes float16, bfloat16, and float32 tiny ranges plus a large float16 range with `num_bins=64`; - a one-bin Gaussian constructor regression verifies invalid spacing is rejected; - exact final head `354e5975` affected loss module: 24 passed, 1 skipped; - ordinary float32/float64 outputs and gradients remain unchanged in differential checks; - Black, isort, Ruff, DCO, and `git diff --check` pass. --------- Signed-off-by: kyinhub <kevinpyin@gmail.com>
1 parent b229330 commit e184689

2 files changed

Lines changed: 133 additions & 6 deletions

File tree

‎monai/losses/image_dissimilarity.py‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,8 @@ def __init__(
214214
IEEE Transactions in Medical Imaging. Vol.22, No.1,
215215
January 2003. pp.120-128.
216216
217-
num_bins: number of bins for intensity
217+
num_bins: number of bins for intensity. The Gaussian kernel requires
218+
more than 1 bin, and the B-spline kernel requires more than 4 bins.
218219
sigma_ratio: a hyper param for gaussian function
219220
reduction: {``"none"``, ``"mean"``, ``"sum"``}
220221
Specifies the reduction to apply to the output. Defaults to ``"mean"``.
@@ -224,13 +225,20 @@ def __init__(
224225
- ``"sum"``: the output will be summed.
225226
smooth_nr: a small constant added to the numerator to avoid nan.
226227
smooth_dr: a small constant added to the denominator to avoid nan.
228+
229+
Raises:
230+
ValueError: if a Gaussian kernel is configured with one or fewer
231+
bins, or if a B-spline kernel is configured with four or fewer bins.
227232
"""
228233
super().__init__(reduction=LossReduction(reduction).value)
229234
if num_bins <= 0:
230235
raise ValueError(f"num_bins must > 0, got {num_bins}")
231-
bin_centers = torch.linspace(0.0, 1.0, num_bins) # (num_bins,)
232-
sigma = torch.mean(bin_centers[1:] - bin_centers[:-1]) * sigma_ratio
233236
self.kernel_type = look_up_option(kernel_type, ["gaussian", "b-spline"])
237+
if self.kernel_type == "gaussian" and num_bins <= 1:
238+
raise ValueError(f"num_bins must be greater than 1 for gaussian kernel, got {num_bins}")
239+
# B-spline windowing reserves two padding bins at each boundary.
240+
if self.kernel_type == "b-spline" and num_bins <= 4:
241+
raise ValueError(f"num_bins must be greater than 4 for b-spline kernel, got {num_bins}")
234242
self.num_bins = num_bins
235243
# declared as buffers so they move with the module (e.g. ``.to(device)``); only populated for the
236244
# gaussian kernel, hence the ``Tensor`` annotation reflects the type at the use sites in that path.
@@ -239,6 +247,8 @@ def __init__(
239247
self.register_buffer("preterm", None, persistent=False)
240248
self.register_buffer("bin_centers", None, persistent=False)
241249
if self.kernel_type == "gaussian":
250+
bin_centers = torch.linspace(0.0, 1.0, num_bins) # (num_bins,)
251+
sigma = torch.mean(bin_centers[1:] - bin_centers[:-1]) * sigma_ratio
242252
self.register_buffer("preterm", 1 / (2 * sigma**2), persistent=False)
243253
self.register_buffer("bin_centers", bin_centers[None, None, ...], persistent=False)
244254

@@ -282,13 +292,22 @@ def parzen_windowing_b_spline(self, img: torch.Tensor, order: int) -> tuple[torc
282292
# Note that there can still be non-zero bin values in the padded region,
283293
# it's just that these bins will never be a central bin for the Parzen
284294
# window.
285-
_max, _min = torch.max(img), torch.min(img)
295+
compute_img = (
296+
img.float() if not torch.is_floating_point(img) or img.dtype in (torch.float16, torch.bfloat16) else img
297+
)
298+
_max, _min = torch.max(compute_img), torch.min(compute_img)
286299
padding = 2
287-
bin_size = (_max - _min) / (self.num_bins - 2 * padding)
300+
interior_bins = self.num_bins - 2 * padding
301+
value_range = _max - _min
302+
raw_bin_size = value_range / interior_bins
303+
# Fall back only when the promoted bin size is non-finite or too small
304+
# to remain a nonzero normal value in the compute dtype.
305+
valid_bin_size = torch.isfinite(raw_bin_size) & (raw_bin_size >= torch.finfo(compute_img.dtype).tiny)
306+
bin_size = torch.where(valid_bin_size, raw_bin_size, torch.ones_like(raw_bin_size))
288307
norm_min = torch.div(_min, bin_size) - padding
289308

290309
# assign bin/window index to each voxel
291-
window_term = torch.div(img, bin_size) - norm_min # B[NDHW]
310+
window_term = torch.div(compute_img, bin_size) - norm_min # B[NDHW]
292311
# make sure the extreme values are in valid (non-padded) bins
293312
window_term = torch.clamp(window_term, padding, self.num_bins - padding - 1) # B[NDHW]
294313
window_term = window_term.reshape(window_term.shape[0], -1, 1) # (batch, num_sample, 1)

‎tests/losses/image_dissimilarity/test_global_mutual_information_loss.py‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,16 @@ def test_b_spline_bin_centers_exists_as_none(self):
135135

136136
self.assertIsNone(loss.bin_centers)
137137

138+
def test_b_spline_num_bins_must_allow_padding(self):
139+
"""Verify B-spline bin counts leave room for boundary padding."""
140+
with self.assertRaisesRegex(ValueError, "num_bins must be greater than 4"):
141+
GlobalMutualInformationLoss(kernel_type="b-spline", num_bins=4)
142+
143+
def test_gaussian_num_bins_must_allow_spacing(self):
144+
"""Verify Gaussian bin counts allow a finite bin-centre spacing."""
145+
with self.assertRaisesRegex(ValueError, "num_bins must be greater than 1"):
146+
GlobalMutualInformationLoss(kernel_type="gaussian", num_bins=1)
147+
138148
@parameterized.expand(
139149
[
140150
(torch.ones((1, 2), dtype=torch.float), torch.ones((1, 3), dtype=torch.float)), # mismatched_simple_dims
@@ -164,6 +174,104 @@ def test_ill_opts(self, num_bins, reduction, expected_exception, expected_messag
164174
GlobalMutualInformationLoss(num_bins=num_bins, reduction=reduction)(pred, target)
165175

166176

177+
class TestGlobalMutualInformationLossBSpline(unittest.TestCase):
178+
"""Test B-spline mutual information on degenerate intensity ranges."""
179+
180+
@parameterized.expand(["prediction", "target"])
181+
def test_b_spline_single_constant_input_is_finite(self, constant_input):
182+
"""Verify either independently constant input yields finite gradients.
183+
184+
Args:
185+
constant_input: Which input (``"prediction"`` or ``"target"``)
186+
is held constant.
187+
"""
188+
varying = torch.linspace(0.0, 1.0, 64).reshape(1, 1, 8, 8)
189+
if constant_input == "prediction":
190+
pred = torch.zeros_like(varying, requires_grad=True)
191+
target = varying
192+
else:
193+
pred = varying.clone().requires_grad_()
194+
target = torch.ones_like(varying)
195+
loss = GlobalMutualInformationLoss(kernel_type="b-spline")
196+
197+
result = loss(pred, target)
198+
199+
self.assertTrue(torch.isfinite(result))
200+
result.backward()
201+
self.assertIsNotNone(pred.grad)
202+
self.assertTrue(torch.isfinite(pred.grad).all())
203+
204+
def test_b_spline_constant_half_precision_images_are_finite(self):
205+
"""Verify constant float16 inputs survive overflow-sized bin distances."""
206+
pred = torch.zeros((1, 1, 8, 8), dtype=torch.float16, requires_grad=True)
207+
target = torch.ones_like(pred)
208+
loss = GlobalMutualInformationLoss(kernel_type="b-spline", num_bins=64)
209+
210+
result = loss(pred, target)
211+
212+
self.assertTrue(torch.isfinite(result))
213+
self.assertAlmostEqual(result.item(), 0.0, places=6)
214+
result.backward()
215+
self.assertIsNotNone(pred.grad)
216+
self.assertTrue(torch.isfinite(pred.grad).all())
217+
218+
def test_b_spline_integer_target_is_supported(self):
219+
"""Verify integer targets do not fail floating-point range validation."""
220+
pred = torch.linspace(0.0, 1.0, 64).reshape(1, 1, 8, 8).requires_grad_()
221+
target = torch.arange(64, dtype=torch.int64).reshape(1, 1, 8, 8)
222+
loss = GlobalMutualInformationLoss(kernel_type="b-spline")
223+
224+
result = loss(pred, target)
225+
226+
self.assertTrue(torch.isfinite(result))
227+
result.backward()
228+
self.assertIsNotNone(pred.grad)
229+
self.assertTrue(torch.isfinite(pred.grad).all())
230+
231+
def test_b_spline_float16_small_range_preserves_signal(self):
232+
"""Verify a small nonzero float16 range retains loss and gradient signal."""
233+
values = torch.linspace(0.0, 5e-4, 64, dtype=torch.float16).reshape(1, 1, 8, 8)
234+
pred = values.clone().requires_grad_()
235+
loss = GlobalMutualInformationLoss(kernel_type="b-spline", num_bins=64)
236+
237+
result = loss(pred, values)
238+
239+
self.assertTrue(torch.isfinite(result))
240+
self.assertLess(result.item(), -1.0)
241+
result.backward()
242+
self.assertIsNotNone(pred.grad)
243+
self.assertTrue(torch.isfinite(pred.grad).all())
244+
self.assertGreater(torch.count_nonzero(pred.grad).item(), 0)
245+
246+
@parameterized.expand(
247+
[
248+
("float16_tiny", torch.float16, torch.finfo(torch.float16).tiny / 2),
249+
("bfloat16_tiny", torch.bfloat16, torch.finfo(torch.bfloat16).tiny / 2),
250+
("float32_tiny", torch.float32, torch.finfo(torch.float32).tiny / 2),
251+
("float16_large", torch.float16, 65000.0),
252+
]
253+
)
254+
def test_b_spline_nonzero_ranges_are_finite(self, case_name, dtype, maximum):
255+
"""Verify extreme nonzero ranges yield finite loss and gradients.
256+
257+
Args:
258+
case_name: Descriptive label for the parameterized range case.
259+
dtype: Tensor dtype used for the prediction and target.
260+
maximum: Nonzero upper endpoint of the tested intensity range.
261+
"""
262+
values = torch.tensor([0.0, maximum, maximum, 0.0], dtype=dtype).reshape(1, 1, 2, 2)
263+
pred = values.clone().requires_grad_()
264+
target = torch.flip(values, dims=(-1,))
265+
loss = GlobalMutualInformationLoss(kernel_type="b-spline", num_bins=64)
266+
267+
result = loss(pred, target)
268+
269+
self.assertTrue(torch.isfinite(result))
270+
result.backward()
271+
self.assertIsNotNone(pred.grad)
272+
self.assertTrue(torch.isfinite(pred.grad).all())
273+
274+
167275
class TestGlobalMutualInformationLossBuffers(unittest.TestCase):
168276
def test_gaussian_kernel_registers_buffers(self):
169277
"""Verify gaussian kernel registers preterm and bin_centers as non-trainable, non-persistent buffers."""

0 commit comments

Comments
 (0)