Skip to content

Handle constant B-spline mutual information inputs - #9022

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

Handle constant B-spline mutual information inputs#9022
yinkev wants to merge 3 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: ab1fbf34-7d2b-4c5c-8334-3a04c793143c

📥 Commits

Reviewing files that changed from the base of the PR and between db5f54a and de7cbc1.

📒 Files selected for processing (1)
  • tests/losses/image_dissimilarity/test_global_mutual_information_loss.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/losses/image_dissimilarity/test_global_mutual_information_loss.py

📝 Walkthrough

Walkthrough

The B-spline kernel now requires more than four bins. Bin-size computation handles constant-intensity inputs without division by zero, and half-precision inputs use float computations for cubic weights. Tests cover invalid bin counts, constant inputs, extreme ranges, finite losses, and finite gradients.

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

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: handling constant B-spline mutual information inputs.
Description check ✅ Passed The description follows the template and includes the issue, summary, types of changes, validation, scope note, and sequencing.
Linked Issues check ✅ Passed The changes address #9018 by handling constant and tiny-range B-spline inputs, enforcing num_bins > 4, and adding regression tests.
Out of Scope Changes check ✅ Passed No clear out-of-scope code changes are introduced beyond the B-spline fix and its tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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.

@yinkev

yinkev commented Jul 26, 2026

Copy link
Copy Markdown
Author

The only failing check is the macOS full-dep job (89732744347), in the unrelated distributed PersistentDataset test: Gloo cannot resolve the runner .local hostname (Unable to find address for ...local). Linux, Windows, static, packaging, and docs checks passed. I attempted to rerun only the failed job, but GitHub requires repository admin permission for the rerun. A maintainer rerun should be sufficient; no PR code change appears warranted.

@yinkev
yinkev marked this pull request as ready for review July 28, 2026 00:04

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

🧹 Nitpick comments (1)
tests/losses/image_dissimilarity/test_global_mutual_information_loss.py (1)

175-177: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the parameterized test arguments.

Add Google-style Args: sections for constant_input, dtype, and maximum; document _ as the parameterized case label or rename it to case_name.

As per path instructions, docstrings should describe each variable, return value, and raised exception in Google-style sections.

Also applies to: 216-217

🤖 Prompt for 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.

In `@tests/losses/image_dissimilarity/test_global_mutual_information_loss.py`
around lines 175 - 177, Update the docstrings for the parameterized tests,
including test_b_spline_single_constant_input_is_finite and the additionally
referenced test, with Google-style Args sections documenting constant_input,
dtype, and maximum. Document the parameterized case-label argument as _ or
rename it to case_name, and describe each argument’s purpose without changing
test behavior.

Source: Path instructions

🤖 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.

Nitpick comments:
In `@tests/losses/image_dissimilarity/test_global_mutual_information_loss.py`:
- Around line 175-177: Update the docstrings for the parameterized tests,
including test_b_spline_single_constant_input_is_finite and the additionally
referenced test, with Google-style Args sections documenting constant_input,
dtype, and maximum. Document the parameterized case-label argument as _ or
rename it to case_name, and describe each argument’s purpose without changing
test behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7ea93d41-c1d2-4149-9e0d-16831277d3ca

📥 Commits

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

📒 Files selected for processing (2)
  • monai/losses/image_dissimilarity.py
  • tests/losses/image_dissimilarity/test_global_mutual_information_loss.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • monai/losses/image_dissimilarity.py

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

yinkev commented Jul 28, 2026

Copy link
Copy Markdown
Author

Addressed the latest CodeRabbit documentation nit in de7cbc17: the parameterized B-spline regressions now document constant_input, the case label, dtype, and maximum with Google-style Args sections. The six affected cases and the complete 21-test file pass; Ruff check/format and git diff --check pass.

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