|
11 | 11 |
|
12 | 12 | from __future__ import annotations |
13 | 13 |
|
| 14 | +import math |
| 15 | + |
14 | 16 | import torch |
15 | 17 | from torch.nn import functional as F |
16 | 18 | from torch.nn.modules.loss import _Loss |
@@ -227,40 +229,65 @@ def __init__( |
227 | 229 | smooth_dr: a small constant added to the denominator to avoid nan. |
228 | 230 |
|
229 | 231 | 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. |
232 | 234 | """ |
233 | 235 | super().__init__(reduction=LossReduction(reduction).value) |
| 236 | + self.kernel_type = look_up_option(kernel_type, ["gaussian", "b-spline"]) |
234 | 237 | if num_bins <= 0: |
235 | 238 | 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: |
241 | 245 | 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 |
242 | 248 | self.num_bins = num_bins |
243 | 249 | # declared as buffers so they move with the module (e.g. ``.to(device)``); only populated for the |
244 | 250 | # gaussian kernel, hence the ``Tensor`` annotation reflects the type at the use sites in that path. |
245 | 251 | self.preterm: torch.Tensor | None |
246 | 252 | self.bin_centers: torch.Tensor | None |
| 253 | + self._preterm_value: float | None = None |
247 | 254 | self.register_buffer("preterm", None, persistent=False) |
248 | 255 | self.register_buffer("bin_centers", None, persistent=False) |
249 | 256 | 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) |
253 | 265 | self.register_buffer("bin_centers", bin_centers[None, None, ...], persistent=False) |
254 | 266 |
|
255 | 267 | self.smooth_nr = float(smooth_nr) |
256 | 268 | self.smooth_dr = float(smooth_dr) |
257 | 269 |
|
258 | 270 | def parzen_windowing( |
259 | | - self, pred: torch.Tensor, target: torch.Tensor |
| 271 | + self, pred: torch.Tensor, target: torch.Tensor, restore_input_dtype: bool = True |
260 | 272 | ) -> 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 | + """ |
261 | 288 | 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) |
264 | 291 | elif self.kernel_type == "b-spline": |
265 | 292 | # a third order BSpline kernel is used for the pred image intensity PDF. |
266 | 293 | 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 |
330 | 357 | probability = torch.mean(weight, dim=-2, keepdim=True) # (batch, 1, num_bins) |
331 | 358 | return weight, probability |
332 | 359 |
|
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 | +
|
337 | 367 | Args: |
338 | 368 | 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. |
339 | 378 | """ |
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) |
341 | 382 | 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: |
343 | 384 | 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) |
347 | 393 | weight = weight / torch.sum(weight, dim=-1, keepdim=True) # (batch, num_sample, num_bin) |
348 | 394 | 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) |
349 | 398 | return weight, probability |
350 | 399 |
|
351 | 400 | def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: |
352 | 401 | """ |
353 | 402 | Args: |
354 | 403 | pred: the shape should be B[NDHW]. |
355 | 404 | target: the shape should be same as the pred shape. |
| 405 | + Returns: |
| 406 | + Reduced negative mutual information loss. |
| 407 | +
|
356 | 408 | 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"``. |
358 | 412 | """ |
359 | 413 | if target.shape != pred.shape: |
360 | 414 | 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) |
368 | 440 | mi = torch.sum( |
369 | 441 | pab * torch.log((pab + self.smooth_nr) / (papb + self.smooth_dr) + self.smooth_dr), dim=(1, 2) |
370 | 442 | ) # (batch) |
371 | 443 |
|
372 | 444 | 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