Skip to content

Commit 3a5cc45

Browse files
authored
Prevent half-precision mutual information overflow (#9023)
Fixes #7622. ### Description Gaussian global mutual information now avoids reduced-precision overflow in two places: 1. Gaussian Parzen-window calculations use float32 internally for float16 and bfloat16 inputs, preventing an oversized kernel preterm from producing non-finite weights. 2. Eager joint-histogram products accumulate in float32 with autocast disabled. TorchScript, which cannot compile a dynamic autocast-device context, computes the normalized joint histogram directly by scaling both operands by the square root of the sample count before matrix multiplication. Public weight, probability, loss, device, and gradient dtype contracts remain unchanged; float64 inputs continue to compute in float64. A finite Python scalar fallback preserves the Gaussian preterm when module-wide float16 conversion would otherwise overflow the registered buffer. ### Types of changes - [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`. - [x] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. ### Validation - `upstream/dev` produces non-finite many-bin float16 Gaussian weights; - under CPU float16 autocast, `upstream/dev` returns `-inf` with non-finite gradients on a 48³ volume; - direct float16 and bfloat16 Parzen outputs preserve dtype/device, remain finite, and normalize to one; - casting the loss module itself to float16 or bfloat16 with 256 bins remains finite in forward and backward; - construction under a float16 default dtype also remains finite with 256 bins; - nonconstant float16/bfloat16 losses track float32 within reduced-precision tolerance; - nonconstant CPU float16 autocast matches float32 exactly in the tested path; - scripted and eager outputs match outside autocast, and scripted CPU float16 autocast remains finite beyond 65,504 samples; - exact final head `3dfbfe95` affected selection: 32 passed, 1 skipped, 1 deselected; the full local module was 32 passed, 1 failed, 1 skipped, with the sole Python 3.14/PyTorch 2.9.1 TorchScript incompatibility reproduced identically on prior head `ceb19147`; - registration-loss integration module: 8 passed; - MPS float16 module-cast forward/backward smoke test passed; - Black, isort, Ruff, DCO, and `git diff --check` pass. ### Scope note The Parzen helper intentionally preserves its historical reduced-precision return dtype before the histogram stage. Avoiding that internal downcast would be a separate numerical-accuracy change rather than the scoped overflow fix. ### Sequencing This PR is ready for review. It overlaps #9022 in `GlobalMutualInformationLoss`; if #9022 merges first, this branch should be rebased before merge. --------- Signed-off-by: kyinhub <kevinpyin@gmail.com>
1 parent 2700a61 commit 3a5cc45

2 files changed

Lines changed: 308 additions & 37 deletions

File tree

‎monai/losses/image_dissimilarity.py‎

Lines changed: 110 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
from __future__ import annotations
1313

14+
import math
15+
1416
import torch
1517
from torch.nn import functional as F
1618
from torch.nn.modules.loss import _Loss
@@ -227,40 +229,65 @@ def __init__(
227229
smooth_dr: a small constant added to the denominator to avoid nan.
228230
229231
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.
232+
ValueError: if a Gaussian kernel has fewer than two bins or a non-finite, non-positive ``sigma_ratio``.
233+
ValueError: if a B-spline kernel is configured with four or fewer bins.
232234
"""
233235
super().__init__(reduction=LossReduction(reduction).value)
236+
self.kernel_type = look_up_option(kernel_type, ["gaussian", "b-spline"])
234237
if num_bins <= 0:
235238
raise ValueError(f"num_bins must > 0, got {num_bins}")
236-
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:
239+
if self.kernel_type == "gaussian":
240+
if num_bins < 2:
241+
raise ValueError(f"Gaussian kernel requires num_bins >= 2, got {num_bins}")
242+
if not math.isfinite(sigma_ratio) or sigma_ratio <= 0.0:
243+
raise ValueError(f"Gaussian kernel requires a finite, positive sigma_ratio, got {sigma_ratio}")
244+
elif self.kernel_type == "b-spline" and num_bins <= 4:
241245
raise ValueError(f"num_bins must be greater than 4 for b-spline kernel, got {num_bins}")
246+
bin_centers = torch.linspace(0.0, 1.0, num_bins) # (num_bins,)
247+
sigma = torch.mean(bin_centers[1:] - bin_centers[:-1]) * sigma_ratio
242248
self.num_bins = num_bins
243249
# declared as buffers so they move with the module (e.g. ``.to(device)``); only populated for the
244250
# gaussian kernel, hence the ``Tensor`` annotation reflects the type at the use sites in that path.
245251
self.preterm: torch.Tensor | None
246252
self.bin_centers: torch.Tensor | None
253+
self._preterm_value: float | None = None
247254
self.register_buffer("preterm", None, persistent=False)
248255
self.register_buffer("bin_centers", None, persistent=False)
249256
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
252-
self.register_buffer("preterm", 1 / (2 * sigma**2), persistent=False)
257+
preterm = 1 / (2 * sigma**2)
258+
preterm_value = float(preterm)
259+
if not math.isfinite(preterm_value) and num_bins > 1 and sigma_ratio != 0.0:
260+
preterm_value = (num_bins - 1) ** 2 / (2.0 * sigma_ratio**2)
261+
if not bool(torch.isfinite(preterm)):
262+
preterm = torch.as_tensor(preterm_value, dtype=torch.float32)
263+
self._preterm_value = preterm_value
264+
self.register_buffer("preterm", preterm, persistent=False)
253265
self.register_buffer("bin_centers", bin_centers[None, None, ...], persistent=False)
254266

255267
self.smooth_nr = float(smooth_nr)
256268
self.smooth_dr = float(smooth_dr)
257269

258270
def parzen_windowing(
259-
self, pred: torch.Tensor, target: torch.Tensor
271+
self, pred: torch.Tensor, target: torch.Tensor, restore_input_dtype: bool = True
260272
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
273+
"""Apply the configured Parzen window to both inputs.
274+
275+
Args:
276+
pred: the prediction tensor.
277+
target: the target tensor.
278+
restore_input_dtype: whether Gaussian weights and probabilities
279+
should use the input dtype.
280+
281+
Returns:
282+
The prediction weights and probabilities followed by the target
283+
weights and probabilities.
284+
285+
Raises:
286+
ValueError: if the configured kernel type is unsupported.
287+
"""
261288
if self.kernel_type == "gaussian":
262-
pred_weight, pred_probability = self.parzen_windowing_gaussian(pred)
263-
target_weight, target_probability = self.parzen_windowing_gaussian(target)
289+
pred_weight, pred_probability = self.parzen_windowing_gaussian(pred, restore_input_dtype)
290+
target_weight, target_probability = self.parzen_windowing_gaussian(target, restore_input_dtype)
264291
elif self.kernel_type == "b-spline":
265292
# a third order BSpline kernel is used for the pred image intensity PDF.
266293
pred_weight, pred_probability = self.parzen_windowing_b_spline(pred, order=3)
@@ -330,49 +357,96 @@ def parzen_windowing_b_spline(self, img: torch.Tensor, order: int) -> tuple[torc
330357
probability = torch.mean(weight, dim=-2, keepdim=True) # (batch, 1, num_bins)
331358
return weight, probability
332359

333-
def parzen_windowing_gaussian(self, img: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
334-
"""
335-
Parzen windowing with gaussian kernel (adapted from DeepReg implementation)
336-
Note: the input is expected to range between 0 and 1
360+
def parzen_windowing_gaussian(
361+
self, img: torch.Tensor, restore_input_dtype: bool = True
362+
) -> tuple[torch.Tensor, torch.Tensor]:
363+
"""Apply Gaussian Parzen windowing adapted from DeepReg.
364+
365+
The input is expected to range between 0 and 1.
366+
337367
Args:
338368
img: the shape should be B[NDHW].
369+
restore_input_dtype: whether weights and probabilities should use
370+
the input dtype.
371+
372+
Returns:
373+
A tuple containing per-sample Gaussian bin weights and the
374+
corresponding marginal probability.
375+
376+
Raises:
377+
ValueError: if the Gaussian kernel buffers are unavailable.
339378
"""
340-
img = torch.clamp(img, 0, 1)
379+
output_dtype = img.dtype
380+
compute_dtype = torch.float32 if output_dtype in (torch.float16, torch.bfloat16) else output_dtype
381+
img = torch.clamp(img.to(dtype=compute_dtype), 0, 1)
341382
img = img.reshape(img.shape[0], -1, 1) # (batch, num_sample, 1)
342-
if self.bin_centers is None or self.preterm is None:
383+
if self.bin_centers is None or self.preterm is None or self._preterm_value is None:
343384
raise ValueError("bin_centers and preterm must be defined for gaussian parzen windowing.")
344-
weight = torch.exp(
345-
-self.preterm.to(img) * (img - self.bin_centers.to(img)) ** 2
346-
) # (batch, num_sample, num_bin)
385+
preterm = self.preterm.to(device=img.device, dtype=compute_dtype)
386+
preterm = torch.where(
387+
torch.isfinite(preterm),
388+
preterm,
389+
torch.as_tensor(self._preterm_value, device=img.device, dtype=compute_dtype),
390+
)
391+
bin_centers = self.bin_centers.to(device=img.device, dtype=compute_dtype)
392+
weight = torch.exp(-preterm * (img - bin_centers) ** 2) # (batch, num_sample, num_bin)
347393
weight = weight / torch.sum(weight, dim=-1, keepdim=True) # (batch, num_sample, num_bin)
348394
probability = torch.mean(weight, dim=-2, keepdim=True) # (batch, 1, num_bin)
395+
if restore_input_dtype and output_dtype in (torch.float16, torch.bfloat16):
396+
weight = weight.to(dtype=output_dtype)
397+
probability = probability.to(dtype=output_dtype)
349398
return weight, probability
350399

351400
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
352401
"""
353402
Args:
354403
pred: the shape should be B[NDHW].
355404
target: the shape should be same as the pred shape.
405+
Returns:
406+
Reduced negative mutual information loss.
407+
356408
Raises:
357-
ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"].
409+
ValueError: if ``pred`` and ``target`` have different shapes, or
410+
if ``self.reduction`` is not one of ``"mean"``, ``"sum"``,
411+
or ``"none"``.
358412
"""
359413
if target.shape != pred.shape:
360414
raise ValueError(f"ground truth has differing shape ({target.shape}) from pred ({pred.shape})")
361-
wa, pa, wb, pb = self.parzen_windowing(pred, target) # (batch, num_sample, num_bin), (batch, 1, num_bin)
362-
363-
pab = torch.bmm(wa.permute(0, 2, 1), wb.to(wa)).div(wa.shape[1]) # (batch, num_bins, num_bins)
364-
# FIXME: in CI tests bmm raises "RuntimeError: Failed to find C compiler." when it tries to compile a kernel,
365-
# using permite here instead of bmm gets around this as there are no means of forcing native ops.
366-
papb = pa.permute(0, 2, 1).to(pb).mul(pb).to(pab) # (batch, num_bins, num_bins)
367-
415+
wa, pa, wb, pb = self.parzen_windowing(
416+
pred, target, restore_input_dtype=False
417+
) # (batch, num_sample, num_bin), (batch, 1, num_bin)
418+
419+
# A half-precision matrix product can overflow while accumulating the
420+
# unnormalized joint histogram. Eager execution disables autocast for
421+
# this operation. TorchScript cannot compile a dynamic autocast device,
422+
# so it computes the normalized histogram directly by scaling both
423+
# operands by sqrt(N).
424+
output_dtype = pred.dtype if self.kernel_type == "gaussian" else wa.dtype
425+
compute_dtype = torch.float32 if wa.dtype in (torch.float16, torch.bfloat16) else wa.dtype
426+
wa = wa.to(dtype=compute_dtype)
427+
wb = wb.to(wa)
428+
pa = pa.to(dtype=compute_dtype)
429+
pb = pb.to(pa)
430+
if torch.jit.is_scripting():
431+
sample_scale = float(wa.shape[1]) ** 0.5
432+
pab = torch.bmm((wa / sample_scale).permute(0, 2, 1), wb / sample_scale).to(
433+
dtype=compute_dtype
434+
) # (batch, num_bins, num_bins)
435+
papb = torch.bmm(pa.permute(0, 2, 1), pb).to(dtype=compute_dtype) # (batch, num_bins, num_bins)
436+
else:
437+
with torch.autocast(device_type=wa.device.type, enabled=False):
438+
pab = torch.bmm(wa.permute(0, 2, 1), wb).div(wa.shape[1]) # (batch, num_bins, num_bins)
439+
papb = torch.bmm(pa.permute(0, 2, 1), pb) # (batch, num_bins, num_bins)
368440
mi = torch.sum(
369441
pab * torch.log((pab + self.smooth_nr) / (papb + self.smooth_dr) + self.smooth_dr), dim=(1, 2)
370442
) # (batch)
371443

372444
if self.reduction == LossReduction.SUM.value:
373-
return torch.sum(mi).neg() # sum over the batch and channel ndims
374-
if self.reduction == LossReduction.NONE.value:
375-
return mi.neg()
376-
if self.reduction == LossReduction.MEAN.value:
377-
return torch.mean(mi).neg() # average over the batch and channel ndims
378-
raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].')
445+
loss = torch.sum(mi).neg() # sum over the batch and channel ndims
446+
elif self.reduction == LossReduction.NONE.value:
447+
loss = mi.neg()
448+
elif self.reduction == LossReduction.MEAN.value:
449+
loss = torch.mean(mi).neg() # average over the batch and channel ndims
450+
else:
451+
raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].')
452+
return loss.to(dtype=output_dtype)

0 commit comments

Comments
 (0)