feat(losses/metrics): implement ignore_index support across dice and …
Fixes #8734
Description
This PR introduces comprehensive native support for ignore_index in core MONAI losses and metrics, as requested in issue #8734. The ignore_index parameter allows specific label values (e.g., padding, unlabeled regions, or boundary artifacts) to be excluded from loss and metric calculations which is a critical feature for medical imaging workflows.
Implementation Summary
Losses with ignore_index support:
DiceLoss- masks ignored voxels before dice computationFocalLoss- applies masking after one-hot conversionTverskyLoss- consistent masking approach with DiceLossUnifiedFocalLoss- handles ignore_index in binary target conversion
Metrics with ignore_index support:
MeanDice&GeneralizedDiceScore- spatial masking before computationMeanIoU- excludes ignored classes from IoU calculationConfusionMatrixMetric- filters ignored indices from confusion matrixHausdorffDistanceMetric- masks boundary computationSurfaceDiceMetric&SurfaceDistanceMetric- handles ignore_index in surface calculations
Key Fixes:
- Added support for
ignore_index - Added comprehensive test coverage in
test_ignore_index_losses.pyandtest_ignore_index_metrics.py
Types of changes
- [x] Non-breaking change (fix or new feature that would not break existing functionality)
- [ ] Breaking change (fix or new feature that would cause existing functionality to change)
- [x] New tests added to cover the changes (
test_ignore_index_losses.py,test_ignore_index_metrics.py) - [x] Integration tests passed locally by running
./runtests.sh -f -u --net --coverage - [x] Quick tests passed locally by running
./runtests.sh --quick --unittests --disttests - [x] In-line docstrings updated
- [x] Documentation updated, tested
make htmlcommand in thedocs/folder
Related Issues
Could merge with or addresses similar requirements as #8667 (Ignore Class)
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] ▶️ Resume reviews
- [ ] 🔍 Trigger review
Walkthrough
Adds an optional ignore_index: int | None parameter to many loss and metric classes (DiceLoss, FocalLoss, TverskyLoss, unified focal losses, DiceMetric, MeanIoU, GeneralizedDiceScore, ConfusionMatrixMetric, Hausdorff/SurfaceDistance/SurfaceDice) and related helpers. Each constructor stores self.ignore_index and forward/compute paths build per-batch/per-voxel masks (channel-aware or sentinel-aware) to mask input/target before reductions. Utilities in metrics/utils (ignore_index_mask, mask-aware edge/distance routines) were introduced/extended. Tests for losses and metrics validating ignore_index behavior were added.
Estimated code review effort
🎯 5 (Critical) | ⏱️ ~120 minutes
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 74.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | Title clearly summarizes the main feature: implementing ignore_index support across losses and metrics. Concise and directly reflects the changeset. |
| Description check | ✅ Passed | Description covers objectives, implementation summary, affected losses/metrics, key fixes, test coverage, and types of changes. Well-structured against template requirements. |
| Linked Issues check | ✅ Passed | PR addresses issue #8734 objectives: adds ignore_index parameter to losses and metrics, masks ignored voxels from loss/metric calculations, supports binary and multi-class segmentation, maintains reduction modes and utilities. |
| Out of Scope Changes check | ✅ Passed | All changes focus on implementing ignore_index support: parameter additions to loss/metric constructors, masking logic in forward/compute methods, helper utilities, and comprehensive tests. No unrelated modifications detected. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands.
Just curious, wont a robust helper specifically for this be cleaner and be passed around to the loss/metric funcs?
Just curious, wont a robust helper specifically for this be cleaner and be passed around to the loss/metric funcs?
Ah yes, thanks for the suggestion, that should be less work than this and cleaner. I initially kept the logic scoped to the loss function to avoid over-engineering while I was verifying the math, buta robust helper in the utils would be much cleaner. I’ll refactor and update the PR shortly.
@Rusheel86 there are conflict I'll leave to you to resolve as they're a little complex but then we can run tests again. @garciadias @atbenmurray if either of you could have a look at this one, please, that would help double checking things. Thanks!
Hey @ericspod, thanks a lot for the detailed review, really appreciate you going through such a large PR. I'm on summer vacation right now so I'll have plenty of time to work on this and go through all the comments properly and get everything addressed. I'll try to have it all fixed and ready before the release goes out if that's still possible. Will push updates soon :)
Great work on this PR, @Rusheel86. Thank you! 🙏
I've left a handful of inline comments with suggestions — mostly minor inconsistencies and some thoughts around Federated Learning compatibility.
None of them are blockers on the core idea. All looks great to me.
Thanks again for pushing this forward. 👏🙌
Hey @garciadias, thank you so much for the kind words and the detailed review, I really appreciate you taking the time to go through it. I'll address all the suggestions and get all of this sorted shortly. Always glad to help and its been a great learning experience for me too :)
Hey @ericspod @garciadias, sorry for the wait, I've pushed the changes after I went through all the review comments. Here's a basic overview:
Masking
- Moved
create_ignore_masktoutils.pyso all callers import from one place - In
focal_loss.py, the mask is now built from the raw target before any clipping happens, fixes the wrong-channel bug - Added a
mask_loss_inputshelper that replaces the repeated inline masking pattern across all loss files
Losses
FocalLossnow correctly saves the original target beforeinclude_backgroundslicing and passes that tocreate_ignore_maskDiceLoss,TverskyLoss, andUnifiedFocalLossall use the newmask_loss_inputshelper consistently- Restored the
else: raise ValueError(...)guard infocal_loss.pyfor unsupported reduction values - Restored
not self.per_componentin thefirst_chexpression inmeandice.py, that was an accidental drop
Metrics
class_index=crestored in theget_edge_surface_distancecall inhausdorff_distance.pyso warnings show the actual class index- Hardcoded
1e-5and1e-6constants replaced withself.epsilonacrossunified_focal_loss.pyandgeneralized_dice.py - Redundant zero-division guard in
generalized_dice.pyremoved, keeping onlyself.epsilon
Tests
- Added test cases with
ignore_index=0andignore_index=1for both losses and metrics, the sentinel-only (ignore_index=255) coverage gap flagged - New cases cover the channel-masking path in
GeneralizedDiceScoreandget_confusion_matrix
Docs
- Added FL compatibility warning to
ignore_indexdocstrings across all affected losses and metrics - Noted in
GeneralizedDiceScorethat output shape changes from[B, C]to[B, C-1]when a valid class index is passed - Noted in
create_ignore_maskthat negative values only behave as expected for label-encoded inputs
I'll push an empty commit later so all CI checks run properly but everything should be good for another look, let me know if anything needs more work :)
All 3 failing checks appear to be CI infrastructure issues unrelated to this PR's changes, all other checks are passing.
-
static mypy check and full-dep (ubuntu latest) : fails with
ModuleNotFoundError: No module named 'pytest'insidecupy/testing/_random.py, outside the scope of this PR. -
packaging test : fails inside
monai/utils/type_conversion.pyandmonai/transforms/, none of which are touched by this PR.
Thank you, @Rusheel86! 🚀 🥇
Always happy to contribute :)