π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix float16 overflow in Dice loss spatial reductions (#5123)
AhmetHakanBezir5ce4825437b4
diff --git a/changelog.d/5123.fixed.md b/changelog.d/5123.fixed.mdnew file mode 100644index 000000000..9ba340c07--- /dev/null+++ b/changelog.d/5123.fixed.md@@ -0,0 +1,3 @@+`dice_loss` and `DiceLoss` sum float16 and bfloat16 inputs over the image in float32 and return the loss in the usual+dtype. In float16 a sum above 65504 used to overflow, so the loss came back as 1.0 or NaN instead of its value, with+`average="micro"` from 128 Γ 256 pixels on.diff --git a/kornia/losses/dice.py b/kornia/losses/dice.pyindex 13a6e477a..e896bb041 100644--- a/kornia/losses/dice.py+++ b/kornia/losses/dice.py@@ -78,6 +78,11 @@ def dice_loss(Return:One-element torch.Tensor of the computed loss.+ Note:+ Spatial reductions use float32 for float16 and bfloat16 inputs to avoid+ overflow on large images. The returned loss retains the usual dtype+ promotion between the inputs and class weights.+Example:>>> N = 5 # num_classes>>> pred = torch.randn(1, N, 3, 5, requires_grad=True)@@ -128,6 +133,8 @@ def dice_loss(else:weight = pred.new_ones(pred.shape[1])+ output_dtype = torch.promote_types(pred.dtype, weight.dtype)+# set dimensions for the appropriate averagingdims: tuple[int, ...] = (2, 3)@@ -138,8 +145,10 @@ def dice_loss(pred_soft = pred_soft * weighttarget_one_hot = target_one_hot * weight- intersection = torch.sum(pred_soft * target_one_hot, dims)- cardinality = torch.sum(pred_soft + target_one_hot, dims)+ # Half-precision pixel counts can overflow before the Dice ratio is formed.+ reduction_dtype = torch.float32 if pred_soft.dtype in (torch.float16, torch.bfloat16) else pred_soft.dtype+ intersection = torch.sum(pred_soft * target_one_hot, dims, dtype=reduction_dtype)+ cardinality = torch.sum(pred_soft + target_one_hot, dims, dtype=reduction_dtype)dice_score = 2.0 * intersection / (cardinality + eps)dice_loss = -dice_score + 1.0@@ -148,7 +157,7 @@ def dice_loss(if average == "macro":dice_loss = (dice_loss * weight).sum(-1) / weight.sum()- return torch.mean(dice_loss)+ return torch.mean(dice_loss).to(output_dtype)class DiceLoss(nn.Module):diff --git a/tests/losses/test_dice.py b/tests/losses/test_dice.pyindex fc6eb5185..2a34c8843 100644--- a/tests/losses/test_dice.py+++ b/tests/losses/test_dice.py@@ -24,6 +24,41 @@ from testing.base import BaseTesterclass TestDiceLoss(BaseTester):+ @pytest.mark.parametrize("height", [256, 512])+ @pytest.mark.parametrize("average", ["micro", "macro"])+ @pytest.mark.parametrize("weighted", [False, True])+ def test_large_image_reduction(self, device, dtype, height, average, weighted):+ logits = torch.full((1, 2, height, 256), -2.0, device=device, dtype=dtype, requires_grad=True)+ with torch.no_grad():+ logits[:, 0] = 2.0+ labels = torch.zeros((1, height, 256), device=device, dtype=torch.int64)+ weight = torch.tensor([1.0, 2.0], device=device, dtype=dtype) if weighted else None+ criterion = kornia.losses.DiceLoss(average=average, weight=weight)++ loss = criterion(logits, labels)+ reference_dtype = torch.float64 if dtype == torch.float64 else torch.float32+ reference = kornia.losses.dice_loss(+ logits.to(reference_dtype),+ labels,+ average=average,+ weight=weight.to(reference_dtype) if weight is not None else None,+ ).to(dtype)++ assert loss.dtype == dtype+ assert loss.device == device+ assert torch.isfinite(loss)+ self.assert_close(loss, reference)+ loss.backward()+ assert torch.isfinite(logits.grad).all()++ @pytest.mark.parametrize("average", ["micro", "macro"])+ def test_weight_dtype_promotion(self, device, dtype, average):+ logits = torch.tensor([2.0, -2.0], device=device, dtype=dtype).reshape(1, 2, 1, 1)+ labels = torch.zeros((1, 1, 1), device=device, dtype=torch.int64)+ weight = torch.tensor([1.0, 2.0], device=device, dtype=torch.float32)+ loss = kornia.losses.dice_loss(logits, labels, average=average, weight=weight)+ assert loss.dtype == torch.promote_types(dtype, weight.dtype)+def test_smoke(self, device, dtype):num_classes = 3logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)