Repository navigation
Commit 8b5725b
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 NaN1 parent 557ffaa commit 8b5725b
2 files changed
Lines changed: 48 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
134 | 134 | | |
135 | 135 | | |
136 | 136 | | |
137 | | - | |
| 137 | + | |
| 138 | + | |
138 | 139 | | |
139 | 140 | | |
140 | 141 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
114 | 114 | | |
115 | 115 | | |
116 | 116 | | |
| 117 | + | |
| 118 | + | |
| 119 | + | |
| 120 | + | |
| 121 | + | |
| 122 | + | |
| 123 | + | |
| 124 | + | |
| 125 | + | |
| 126 | + | |
| 127 | + | |
| 128 | + | |
| 129 | + | |
| 130 | + | |
| 131 | + | |
| 132 | + | |
| 133 | + | |
| 134 | + | |
| 135 | + | |
| 136 | + | |
| 137 | + | |
| 138 | + | |
| 139 | + | |
117 | 140 | | |
118 | 141 | | |
119 | 142 | | |
| |||
146 | 169 | | |
147 | 170 | | |
148 | 171 | | |
| 172 | + | |
| 173 | + | |
| 174 | + | |
| 175 | + | |
| 176 | + | |
| 177 | + | |
| 178 | + | |
| 179 | + | |
| 180 | + | |
| 181 | + | |
| 182 | + | |
| 183 | + | |
| 184 | + | |
| 185 | + | |
| 186 | + | |
| 187 | + | |
| 188 | + | |
| 189 | + | |
| 190 | + | |
| 191 | + | |
| 192 | + | |
| 193 | + | |
| 194 | + | |
149 | 195 | | |
150 | 196 | | |
151 | 197 | | |
0 commit comments