MONAI icon indicating copy to clipboard operation
MONAI copied to clipboard

BUGFIX: support NDHWC input in sliding_window_inference and DiceMetric

Open mattlin1124 opened this issue 4 months ago • 1 comments

What

Move ensure_channel_first to monai/utils/tensor_utils.py and re-export from inferers/utils.py for backward compatibility.

Update MeanDice channel normalization logic:

Use num_classes as authoritative hint when provided.

Without num_classes: apply heuristic first, then y-informed fallback.

Fail fast on ambiguous shapes (dim1 == dim-1 > 1).

Detect and raise on inconsistent inputs (label-map vs one-hot) when num_classes is missing.

Add unit tests covering:

NHWC with H==W==C and num_classes=None → expect ValueError.

NHWC with num_classes=C → matches NCHW baseline.

Label-map y_pred vs one-hot y → passes with num_classes=C, raises without.

Update docstrings to clarify channel-last support and explicit error conditions.

Why

Decouple metrics from inferers by placing generic tensor-layout helpers under utils.

Prevent silent NHWC/NCHW misinterpretation in DiceMetric.

Provide explicit errors and guidance when inputs are ambiguous or inconsistent.

How verified

Local checks: pre-commit run -a, mypy monai passed.

New tests in tests/metrics/test_dice_layouts.py cover ambiguity, parity with specified num_classes, and label-map vs one-hot cases.

CI expected to cover full platform matrix (Ubuntu/Windows/macOS, GPU backends).

Summary by CodeRabbit

  • New Features
    • Added seamless support for channel-last 5D inputs (N, D, H, W, C) with C = 1, 3, or 4 in sliding window inference and Mean Dice metric. Inputs are automatically converted to channel-first (N, C, D, H, W), eliminating the need for manual permutation.
    • Works transparently with no changes to public APIs. Behavior remains unchanged for other input shapes, ensuring backward compatibility and consistent results.

mattlin1124 avatar Aug 29 '25 07:08 mattlin1124

Walkthrough

Adds automatic handling of 5D channel-last tensors (N, D, H, W, C with C in {1, 3, 4}) by permuting to channel-first (N, C, D, H, W) in sliding window inference and mean Dice computation. No public signatures changed; existing logic runs after reordering.

Changes

Cohort / File(s) Summary of Changes
Inference utilities
monai/inferers/utils.py
Detect 5D channel-last inputs (C in {1,3,4}) in sliding_window_inference and permute to channel-first before windowing; behavior unchanged otherwise.
Metrics
monai/metrics/meandice.py
In _compute_tensor, detect 5D channel-last y_pred/y (C in {1,3,4}) and permute to channel-first; maintain contiguity; rest of Dice logic unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant Inference as sliding_window_inference
  Caller->>Inference: input (N, D, H, W, C)
  alt 5D and C in {1,3,4}
    Inference->>Inference: Permute to (N, C, D, H, W)
  else
    Note over Inference: Use input as-is
  end
  Inference->>Inference: Windowing & aggregation
  Inference-->>Caller: output
sequenceDiagram
  autonumber
  participant Trainer as Metric caller
  participant Dice as _compute_tensor
  Trainer->>Dice: y_pred, y
  alt 5D and last dim C in {1,3,4}
    Dice->>Dice: Permute y_pred/y to (N, C, D, H, W)
  else
    Note over Dice: Use tensors as-is
  end
  Dice->>Dice: Compute Dice as before
  Dice-->>Trainer: dice score(s)

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10–15 minutes

Poem

I hop through dims with tidy cheer,
From NDHWC to channels near—
A twist, a turn, a quick permute,
Now windows slide and metrics compute.
Ears up, tail flick—jobs aligned,
Carrots for code that’s well-defined! 🥕

✨ Finishing Touches
  • [ ] 📝 Generate Docstrings
🧪 Generate unit tests
  • [ ] Create PR with unit tests
  • [ ] Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot] avatar Aug 29 '25 07:08 coderabbitai[bot]