MONAI icon indicating copy to clipboard operation
MONAI copied to clipboard

feat(losses/metrics): implement ignore_index support across dice and …

Open Rusheel86 opened this issue 9 months ago • 10 comments

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 computation
  • FocalLoss - applies masking after one-hot conversion
  • TverskyLoss - consistent masking approach with DiceLoss
  • UnifiedFocalLoss - handles ignore_index in binary target conversion

Metrics with ignore_index support:

  • MeanDice & GeneralizedDiceScore - spatial masking before computation
  • MeanIoU - excludes ignored classes from IoU calculation
  • ConfusionMatrixMetric - filters ignored indices from confusion matrix
  • HausdorffDistanceMetric - masks boundary computation
  • SurfaceDiceMetric & SurfaceDistanceMetric - handles ignore_index in surface calculations

Key Fixes:

  • Added support for ignore_index
  • Added comprehensive test coverage in test_ignore_index_losses.py and test_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 html command in the docs/ folder

Related Issues

Could merge with or addresses similar requirements as #8667 (Ignore Class)

Rusheel86 avatar Feb 25 '26 15:02 Rusheel86

[!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_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot] avatar Feb 25 '26 15:02 coderabbitai[bot]

Just curious, wont a robust helper specifically for this be cleaner and be passed around to the loss/metric funcs?

aymuos15 avatar Mar 18 '26 20:03 aymuos15

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 avatar Mar 19 '26 13:03 Rusheel86

@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!

ericspod avatar May 21 '26 12:05 ericspod

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 :)

Rusheel86 avatar May 21 '26 13:05 Rusheel86

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. 👏🙌

garciadias avatar May 21 '26 16:05 garciadias

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 :)

Rusheel86 avatar May 21 '26 17:05 Rusheel86

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_mask to utils.py so 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_inputs helper that replaces the repeated inline masking pattern across all loss files

Losses

  • FocalLoss now correctly saves the original target before include_background slicing and passes that to create_ignore_mask
  • DiceLoss, TverskyLoss, and UnifiedFocalLoss all use the new mask_loss_inputs helper consistently
  • Restored the else: raise ValueError(...) guard in focal_loss.py for unsupported reduction values
  • Restored not self.per_component in the first_ch expression in meandice.py, that was an accidental drop

Metrics

  • class_index=c restored in the get_edge_surface_distance call in hausdorff_distance.py so warnings show the actual class index
  • Hardcoded 1e-5 and 1e-6 constants replaced with self.epsilon across unified_focal_loss.py and generalized_dice.py
  • Redundant zero-division guard in generalized_dice.py removed, keeping only self.epsilon

Tests

  • Added test cases with ignore_index=0 and ignore_index=1 for both losses and metrics, the sentinel-only (ignore_index=255) coverage gap flagged
  • New cases cover the channel-masking path in GeneralizedDiceScore and get_confusion_matrix

Docs

  • Added FL compatibility warning to ignore_index docstrings across all affected losses and metrics
  • Noted in GeneralizedDiceScore that output shape changes from [B, C] to [B, C-1] when a valid class index is passed
  • Noted in create_ignore_mask that 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 :)

Rusheel86 avatar May 26 '26 17:05 Rusheel86

All 3 failing checks appear to be CI infrastructure issues unrelated to this PR's changes, all other checks are passing.

  1. static mypy check and full-dep (ubuntu latest) : fails with ModuleNotFoundError: No module named 'pytest' inside cupy/testing/_random.py, outside the scope of this PR.

  2. packaging test : fails inside monai/utils/type_conversion.py and monai/transforms/, none of which are touched by this PR.

Rusheel86 avatar May 27 '26 09:05 Rusheel86

Thank you, @Rusheel86! 🚀 🥇

Always happy to contribute :)

Rusheel86 avatar May 28 '26 19:05 Rusheel86