Skip to content

Handle constant B-spline mutual information inputs#9022

Draft
yinkev wants to merge 2 commits into
Project-MONAI:devfrom
yinkev:9018-global-mi-constant-bspline
Draft

Handle constant B-spline mutual information inputs#9022
yinkev wants to merge 2 commits into
Project-MONAI:devfrom
yinkev:9018-global-mi-constant-bspline

Conversation

@yinkev

@yinkev yinkev commented Jul 25, 2026

Copy link
Copy Markdown

Fixes #9018.

Description

B-spline global mutual information now remains finite when either prediction or target has a constant intensity range and for float16, bfloat16, or float32 inputs with tiny nonzero ranges. Configurations with four or fewer bins are rejected because the implementation reserves two padding bins at each boundary.

The fix performs reduced-precision range, bin-width, and B-spline coordinate arithmetic in float32. Bin widths too small to be represented safely by the compute or input dtype are treated as a degenerate range. This prevents zero-range division, tiny-range underflow, unrepresentable normalization slopes, and cubic-distance overflow while preserving autograd back to the original input.

Types of changes

  • 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).
  • New tests added to cover the changes.
  • Integration tests passed locally by running ./runtests.sh -f -u --net --coverage.
  • Quick tests passed locally by running ./runtests.sh --quick --unittests --disttests.
  • In-line docstrings updated.
  • Documentation updated, tested make html command in the docs/ folder.

Validation

  • zero-range and tiny-range regressions fail before the follow-up fix;
  • prediction-constant and target-constant paths are covered independently;
  • extreme-range coverage includes float16, bfloat16, and float32 tiny ranges plus a large float16 range with num_bins=64;
  • affected loss module: 20 passed, 2 expected skips;
  • ordinary float32/float64 outputs and gradients remain unchanged in differential checks;
  • Black, isort, Ruff, DCO, and git diff --check pass.

Scope note

A review also identified the pre-existing Gaussian num_bins=1 configuration issue. It is intentionally not bundled because it is unrelated to the B-spline defect tracked by #9018.

Sequencing

This PR remains draft while #9019 is the current MONAI review target.

Signed-off-by: kyinhub <kevinpyin@gmail.com>
@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The B-spline kernel now documents and enforces a requirement for more than four bins. Its bin-size calculation handles constant-intensity inputs without division by zero, and float16 distance values are promoted before cubic weight computation. Tests cover invalid bin counts, finite losses, and finite gradients for constant float32 and float16 inputs.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR satisfies #9018 by fixing constant-input finiteness, rejecting num_bins <= 4, and preventing float16 overflow.
Out of Scope Changes check ✅ Passed The code changes stay within the requested B-spline stability fix and regression coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly matches the main fix: handling constant inputs for B-spline mutual information.
Description check ✅ Passed The description follows the template with issue link, summary, change types, and validation details.
✨ 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 coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@monai/losses/image_dissimilarity.py`:
- Around line 233-240: Update the initialization logic around the kernel_type
validation and sigma calculation to reject num_bins=1 for Gaussian kernels
before computing bin-centre spacing, while preserving the existing b-spline
constraint. Add regression coverage confirming that a one-bin Gaussian
configuration raises the expected validation error.
- Around line 293-295: Update the range and bin-size arithmetic in the image
dissimilarity loss to compute intermediate values in float32, apply the
zero-range fallback there, then cast the resulting bin size back to the image
gradient dtype. In
tests/losses/image_dissimilarity/test_global_mutual_information_loss.py, add
small- and large-nonzero-range float16 cases asserting finite loss and
gradients.

In `@tests/losses/image_dissimilarity/test_global_mutual_information_loss.py`:
- Around line 175-179: Extend the constant-image coverage in
test_b_spline_constant_images_are_finite with separate cases for a constant
prediction against a varying target and a varying prediction against a constant
target. Keep the existing finite-loss and gradient assertions, and ensure both
independent zero-intensity-range paths are exercised by the tests.
- Around line 189-193: Update the float16 B-spline tests, including
test_b_spline_constant_half_precision_images_are_finite, to use an
overflow-triggering bin configuration such as num_bins=64 instead of 32.
Preserve the existing assertions and test behavior while ensuring the cubic term
can exceed the float16 range.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f51b91f4-41e6-4767-9ba0-c9a9ebbf32a0

📥 Commits

Reviewing files that changed from the base of the PR and between 3ee058b and 11ee2f4.

📒 Files selected for processing (2)
  • monai/losses/image_dissimilarity.py
  • tests/losses/image_dissimilarity/test_global_mutual_information_loss.py

Comment thread monai/losses/image_dissimilarity.py
Comment thread monai/losses/image_dissimilarity.py Outdated
Comment thread tests/losses/image_dissimilarity/test_global_mutual_information_loss.py Outdated
Comment thread tests/losses/image_dissimilarity/test_global_mutual_information_loss.py Outdated
Signed-off-by: kyinhub <kevinpyin@gmail.com>
@yinkev

yinkev commented Jul 26, 2026

Copy link
Copy Markdown
Author

CI triage: the only failed check is full-dep (macOS-latest). The affected GlobalMutualInformationLoss tests passed in that job; the failure occurred later in tests.data.test_persistentdataset_dist.TestDistDataset because Gloo could not resolve the ephemeral runner hostname. Ubuntu and Windows full-dependency jobs and all other checks passed. This is unrelated to the PR diff. Fork contributors cannot rerun upstream Actions, so the matrix will run again when this draft is rebased before promotion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GlobalMutualInformationLoss returns NaN for constant B-spline inputs

1 participant