π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): give a constant MI signal a zero gradient instead of NaN (#5579)
εΊζ’η62137a93bf3d
diff --git a/changelog.d/5579.fixed.md b/changelog.d/5579.fixed.mdnew file mode 100644index 000000000..1df565e5a--- /dev/null+++ b/changelog.d/5579.fixed.md@@ -0,0 +1,4 @@+`mutual_information_loss`, `normalized_mutual_information_loss`, their `_2d` and `_3d` forms and the `MILossFromRef` and+`NMILossFromRef` modules now give a constant input, target or reference a zero gradient (#5575). Previously the+discarded branch of the `torch.where` that normalises a constant signal to zero backpropagated `0 / 0`, so the constant+sample's gradient was NaN, and with it the gradient of any parameter shared across the batch. Loss values are unchanged.diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.pyindex da4a58b8c..9a3d6a531 100644--- a/kornia/losses/mutual_information.py+++ b/kornia/losses/mutual_information.py@@ -121,8 +121,11 @@ def _normalize_signal(data: torch.Tensor, num_bins: int, eps: float = 1e-8) -> tmax_val, _ = data.max(dim=-1)diff = (max_val - min_val).unsqueeze(-1)# Map the range onto the bin centres 0 ... num_bins - 1, so that the maximum lands on the last centre and gets- # full histogram weight like every other sample. The signal is considered trivial if too low variation.- return torch.where(diff > eps, (data - min_val.unsqueeze(-1)) / diff * (num_bins - 1), 0)+ # full histogram weight like every other sample. The signal is considered trivial if too low variation; its range+ # is replaced by one inside the division, so that the discarded branch does not backpropagate 0 / 0.+ nontrivial = diff > eps+ safe_diff = torch.where(nontrivial, diff, torch.ones_like(diff))+ return torch.where(nontrivial, (data - min_val.unsqueeze(-1)) / safe_diff * (num_bins - 1), 0)def _joint_histogram_to_entropies(joint_histogram: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.pyindex b252e73bb..4f066014c 100644--- a/tests/losses/test_mutual_information.py+++ b/tests/losses/test_mutual_information.py@@ -146,6 +146,29 @@ class TestMutualInformationLoss(BaseTester):self.assert_close(_normalize_signal(signal, num_bins=64), torch.zeros_like(signal))+ @pytest.mark.parametrize("kernel", [MIKernel.xu, MIKernel.truncated_gaussian])+ def test_constant_signal_has_zero_gradient(self, device, dtype, kernel):+ # A constant sample is normalised to zero, and the discarded branch of that `where` must not backpropagate+ # 0 / 0: the loss does not change under any perturbation that keeps the range below eps, so its gradient is 0.+ generator = torch.Generator().manual_seed(0)+ pred = torch.rand(2, 12, 20, generator=generator).to(device, dtype)+ target = (pred**2 + 0.1 * torch.rand(2, 12, 20, generator=generator).to(device, dtype)).detach()+ pred[1] = 0.3+ for loss_fn in (mutual_information_loss_2d, normalized_mutual_information_loss_2d):+ pred_, target_ = pred.clone().requires_grad_(), target.clone().requires_grad_()+ grad_pred, grad_target = torch.autograd.grad(+ loss_fn(pred_, target_, kernel_function=kernel).sum(), (pred_, target_)+ )+ assert grad_pred.isfinite().all() and grad_target.isfinite().all()+ self.assert_close(grad_pred[1], torch.zeros_like(grad_pred[1]), rtol=0, atol=0)+ assert grad_pred[0].abs().sum() > 0+ scale = torch.ones((), device=device, dtype=dtype, requires_grad=True)+ mutual_information_loss_2d(pred * scale, target, kernel_function=kernel).sum().backward()+ assert scale.grad.isfinite()+ reference = torch.full((240,), 0.5, device=device, dtype=dtype, requires_grad=True)+ MILossFromRef(reference, kernel_function=kernel)(target[0].reshape(-1)).backward()+ self.assert_close(reference.grad, torch.zeros_like(reference), rtol=0, atol=0)+def test_normalizes_onto_bin_centres(self, device, dtype):signal = torch.tensor([2.0, 2.5, 3.0], device=device, dtype=dtype)expected = torch.tensor([0.0, 31.5, 63.0], device=device, dtype=dtype)