Skip to content

Commit 8b5725b

Browse files
authored
Fix division by zero in clDice loss harmonic mean (#8739)
## Summary - Fix division by zero in `SoftclDiceLoss` and `SoftDiceclDiceLoss` when computing the harmonic mean of topology precision and sensitivity - Add a small epsilon (`1e-7`) to the denominator `(tprec + tsens)` to prevent `NaN` when both values are zero - Add test cases for zero-input and non-overlapping edge cases with `smooth=0` ## Details The clDice loss computes `cl_dice = 1.0 - 2.0 * (tprec * tsens) / (tprec + tsens)`. When both `tprec` and `tsens` are zero (e.g., empty inputs, non-overlapping predictions/targets, or `smooth=0`), this results in `0/0 = NaN`, which propagates through the loss and crashes training. While the default `smooth=1.0` prevents `tprec` and `tsens` from being exactly zero in most cases, setting `smooth=0` (a valid configuration) exposes this bug whenever skeleton overlap is zero. The fix adds `1e-7` to the harmonic mean denominator, which: - Has negligible impact on normal computation (tprec, tsens are bounded in [0, 1]) - Returns `cl_dice = 1.0` (maximum loss) when both precision and sensitivity are zero, which is the correct semantic result - Is consistent with epsilon-based denominator guards used elsewhere in MONAI (e.g., `smooth_dr` in `DiceLoss`) ## Test plan - [x] Existing `test_cldice_loss.py` tests still pass (perfect overlap cases) - [x] New `test_zero_input_no_nan`: verifies zero-valued inputs with `smooth=0` do not produce NaN - [x] New `test_no_overlap_no_nan`: verifies non-overlapping predictions/targets with `smooth=0` do not produce NaN
1 parent 557ffaa commit 8b5725b

2 files changed

Lines changed: 48 additions & 1 deletion

File tree

‎monai/losses/cldice.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,8 @@ def __init__(
134134
Args:
135135
iter_: Number of iterations for skeletonization. Must be a non-negative integer. Defaults to 3.
136136
smooth_nr: a small constant added to the numerator to avoid zero. Defaults to 1.0.
137-
smooth_dr: a small constant added to the denominator to avoid nan. Defaults to 1.0.
137+
smooth_dr: a small constant added to the denominator of the individual precision /
138+
sensitivity ratios and the internal Dice denominator to avoid nan. Defaults to 1.0.
138139
smooth: a small constant added to the denominator of the harmonic mean to avoid nan. Defaults to 1e-4.
139140
include_background: if False, channel index 0 (background category) is excluded from the calculation.
140141
if the non-background segmentations are small compared to the total image size they can get overwhelmed

‎tests/losses/test_cldice_loss.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,29 @@ def test_invalid_iter_value(self):
114114
with self.assertRaises(ValueError):
115115
SoftclDiceLoss(iter_=-1)
116116

117+
def test_zero_input_is_finite(self):
118+
loss = SoftclDiceLoss(smooth=1e-7, smooth_dr=1e-5)
119+
result = loss(torch.zeros((1, 2, 4, 4)), torch.zeros((1, 2, 4, 4)))
120+
self.assertTrue(torch.isfinite(result).all())
121+
122+
def test_non_default_smooth_dr_changes_result(self):
123+
input_tensor = torch.zeros((1, 2, 4, 4))
124+
target = torch.zeros((1, 2, 4, 4))
125+
loss_a = SoftclDiceLoss(smooth=1e-7, smooth_dr=1e-3)
126+
loss_b = SoftclDiceLoss(smooth=1e-7, smooth_dr=1e-5)
127+
result_a = loss_a(input_tensor, target)
128+
result_b = loss_b(input_tensor, target)
129+
self.assertTrue(torch.isfinite(result_a).all())
130+
self.assertTrue(torch.isfinite(result_b).all())
131+
self.assertNotAlmostEqual(result_a.item(), result_b.item(), places=5)
132+
133+
def test_non_overlapping_input_is_finite(self):
134+
loss = SoftclDiceLoss(smooth=1e-7, smooth_dr=1e-5)
135+
input_tensor = torch.tensor([[[[1.0, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 0.0]]]])
136+
target = torch.tensor([[[[0.0, 0.0], [0.0, 1.0]], [[0.0, 0.0], [0.0, 0.0]]]])
137+
result = loss(input_tensor, target)
138+
self.assertTrue(torch.isfinite(result).all())
139+
117140

118141
class TestSoftDiceclDiceLoss(unittest.TestCase):
119142
@parameterized.expand(COMBINED_CASES)
@@ -146,6 +169,29 @@ def test_invalid_alpha_negative(self):
146169
with self.assertRaises(ValueError):
147170
SoftDiceclDiceLoss(alpha=-0.5)
148171

172+
def test_zero_input_is_finite(self):
173+
loss = SoftDiceclDiceLoss(smooth=1e-7, smooth_dr=1e-5)
174+
result = loss(torch.zeros((1, 2, 4, 4)), torch.zeros((1, 2, 4, 4)))
175+
self.assertTrue(torch.isfinite(result).all())
176+
177+
def test_non_default_smooth_dr_changes_result(self):
178+
input_tensor = torch.zeros((1, 2, 4, 4))
179+
target = torch.zeros((1, 2, 4, 4))
180+
loss_a = SoftDiceclDiceLoss(smooth=1e-7, smooth_dr=1e-3)
181+
loss_b = SoftDiceclDiceLoss(smooth=1e-7, smooth_dr=1e-5)
182+
result_a = loss_a(input_tensor, target)
183+
result_b = loss_b(input_tensor, target)
184+
self.assertTrue(torch.isfinite(result_a).all())
185+
self.assertTrue(torch.isfinite(result_b).all())
186+
self.assertNotAlmostEqual(result_a.item(), result_b.item(), places=5)
187+
188+
def test_non_overlapping_input_is_finite(self):
189+
loss = SoftDiceclDiceLoss(smooth=1e-7, smooth_dr=1e-5)
190+
input_tensor = torch.tensor([[[[1.0, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 0.0]]]])
191+
target = torch.tensor([[[[0.0, 0.0], [0.0, 1.0]], [[0.0, 0.0], [0.0, 0.0]]]])
192+
result = loss(input_tensor, target)
193+
self.assertTrue(torch.isfinite(result).all())
194+
149195

150196
if __name__ == "__main__":
151197
unittest.main()

0 commit comments

Comments
 (0)