Skip to content

fix: add missing stacklevel=2 to warnings.warn() in losses/ (Fixes #8929)#8930

Open
rtmalikian wants to merge 2 commits into
Project-MONAI:devfrom
rtmalikian:fix/issue-8929-losses-stacklevel
Open

fix: add missing stacklevel=2 to warnings.warn() in losses/ (Fixes #8929)#8930
rtmalikian wants to merge 2 commits into
Project-MONAI:devfrom
rtmalikian:fix/issue-8929-losses-stacklevel

Conversation

@rtmalikian

Copy link
Copy Markdown

Fixes #8929

Problem

28 calls to warnings.warn() in monai/losses/ are missing the stacklevel parameter. Without stacklevel=2, warnings point to the MONAI internal code instead of the user's calling code, making it difficult for users to identify which part of their script triggered the warning.

Solution

Added stacklevel=2 to all 28 warnings.warn() calls across 9 loss modules:

  • dice.py (7 instances)
  • tversky.py (3 instances)
  • mcc_loss.py (3 instances)
  • focal_loss.py (3 instances)
  • hausdorff_loss.py (3 instances)
  • unified_focal_loss.py (3 instances)
  • spatial_mask.py (3 instances)
  • perceptual.py (2 instances)
  • adversarial_loss.py (1 instance)

Also fixes a typo in perceptual.py: "supp, ort""support" (carried from #8924).

Verification

# All 28 warnings.warn() calls now have stacklevel=2
$ grep -c "stacklevel" monai/losses/*.py
# Each file's stacklevel count matches its warnings.warn count

# All 9 files pass syntax check
$ python3 -c "import ast; [ast.parse(open(f).read()) for f in files]"
9 files checked, 0 errors

Changelog

Date Change Author
2026-06-19 Add missing stacklevel=2 to 28 warnings.warn() calls in 9 loss modules rtmalikian

Files Changed

  • monai/losses/dice.py — 7 warnings.warn() calls updated
  • monai/losses/tversky.py — 3 calls updated
  • monai/losses/mcc_loss.py — 3 calls updated
  • monai/losses/focal_loss.py — 3 calls updated
  • monai/losses/hausdorff_loss.py — 3 calls updated
  • monai/losses/unified_focal_loss.py — 3 calls updated
  • monai/losses/spatial_mask.py — 3 calls updated
  • monai/losses/perceptual.py — 2 calls updated + typo fix
  • monai/losses/adversarial_loss.py — 1 call updated

Verification

  • All 28 warnings.warn() calls now include stacklevel=2
  • All 9 modified files pass Python syntax validation
  • No duplicate stacklevel parameters

About the Author: Raphael Malikian — Clinical AI Solutions Architect. I specialise in building and fixing AI/ML systems for healthcare, including vector databases, RAG pipelines, and clinical NLP. If you need help with your project or think I can add value to your organisation, feel free to reach out — I'd love to connect.

📧 rtmalikian@gmail.com
🔗 GitHub: https://github.com/rtmalikian
🔗 LinkedIn: http://www.linkedin.com/in/raphael-t-malikian-mbbs-bsc-hons-71075436a


Disclosure: This code was developed with assistance from MiMo-v2.5-Pro (Xiaomi) via Hermes Agent (Nous Research). All changes were reviewed, tested against the actual codebase, and verified for correctness.

Add stacklevel=2 to 28 warnings.warn() calls across 9 loss modules
so that warnings correctly point to the user's calling code instead
of MONAI internal code.

Affected files:
- dice.py (7 instances)
- tversky.py (3 instances)
- mcc_loss.py (3 instances)
- focal_loss.py (3 instances)
- hausdorff_loss.py (3 instances)
- unified_focal_loss.py (3 instances)
- spatial_mask.py (3 instances)
- perceptual.py (2 instances)
- adversarial_loss.py (1 instance)

Also fixes a typo in perceptual.py: 'supp, ort' -> 'support'.

Fixes Project-MONAI#8929

Signed-off-by: Raphael Malikian <rtmalikian@gmail.com>
@coderabbitai

coderabbitai Bot commented Jun 19, 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

Run ID: fb2ec141-a9f8-4bd3-a4bb-643d241e984a

📥 Commits

Reviewing files that changed from the base of the PR and between faa2e69 and fd98601.

📒 Files selected for processing (2)
  • monai/losses/adversarial_loss.py
  • monai/losses/perceptual.py
✅ Files skipped from review due to trivial changes (2)
  • monai/losses/adversarial_loss.py
  • monai/losses/perceptual.py

📝 Walkthrough

Walkthrough

All warnings.warn calls across 8 loss module files (adversarial_loss.py, dice.py, focal_loss.py, hausdorff_loss.py, mcc_loss.py, spatial_mask.py, tversky.py, unified_focal_loss.py) were updated to pass stacklevel=2, redirecting warning tracebacks to caller code instead of internal forward methods. perceptual.py receives correct stacklevel=2 argument placement and a warning string typo fix. No logic changes.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.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 change: adding stacklevel=2 to warnings.warn() calls in loss modules and references the related issue.
Description check ✅ Passed Description covers problem, solution, verification, and files changed; includes clear rationale for the fix and lists all affected modules with change counts.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 and usage tips.

@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 (2)
monai/losses/perceptual.py (1)

129-131: 💤 Low value

Consider moving stacklevel parameter to previous line for consistency.

The stacklevel=2 parameter is on a separate line with a leading comma, inconsistent with line 115 in this file and most other warnings in this PR.

Suggested formatting
         warnings.warn(
-            f"Setting cache_dir to {cache_dir}, this may change the default cache dir for all torch.hub calls."
-        , stacklevel=2)
+            f"Setting cache_dir to {cache_dir}, this may change the default cache dir for all torch.hub calls.",
+            stacklevel=2)
🤖 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 `@monai/losses/perceptual.py` around lines 129 - 131, The stacklevel=2
parameter in the warnings.warn() call is on a separate line with a leading
comma, which is inconsistent with the formatting used at line 115 and elsewhere
in the codebase. Move the stacklevel=2 parameter to the same line as the
f-string message by placing the comma at the end of the f-string and positioning
stacklevel=2 on the same line with proper indentation to match the consistent
formatting style used throughout the file.
monai/losses/adversarial_loss.py (1)

130-133: 💤 Low value

Consider moving stacklevel parameter to previous line for consistency.

The stacklevel=2 parameter is on a separate line with a leading comma. Other files in this PR keep the parameter on the same line as the closing quote. Consistent formatting improves readability.

Suggested formatting
         warnings.warn(
             "Variable target_is_real has been set to False, but for_discriminator is set"
-            "to False. To optimise a generator, target_is_real must be set to True."
-        , stacklevel=2)
+            "to False. To optimise a generator, target_is_real must be set to True.",
+            stacklevel=2)
🤖 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 `@monai/losses/adversarial_loss.py` around lines 130 - 133, In the
warnings.warn call in the adversarial_loss.py file, the stacklevel parameter is
currently on a separate line with a leading comma. Move the stacklevel=2
parameter to the same line as the closing quote of the warning message string
and adjust the formatting so the comma follows the string closure rather than
appearing on a separate line. This will align with the formatting convention
used elsewhere in the PR.
🤖 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 `@monai/losses/adversarial_loss.py`:
- Around line 130-133: In the warnings.warn call in the adversarial_loss.py
file, the stacklevel parameter is currently on a separate line with a leading
comma. Move the stacklevel=2 parameter to the same line as the closing quote of
the warning message string and adjust the formatting so the comma follows the
string closure rather than appearing on a separate line. This will align with
the formatting convention used elsewhere in the PR.

In `@monai/losses/perceptual.py`:
- Around line 129-131: The stacklevel=2 parameter in the warnings.warn() call is
on a separate line with a leading comma, which is inconsistent with the
formatting used at line 115 and elsewhere in the codebase. Move the stacklevel=2
parameter to the same line as the f-string message by placing the comma at the
end of the f-string and positioning stacklevel=2 on the same line with proper
indentation to match the consistent formatting style used throughout the file.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2d1171ec-b7a8-49b8-b1cf-d02878e99e70

📥 Commits

Reviewing files that changed from the base of the PR and between 15f5073 and faa2e69.

📒 Files selected for processing (9)
  • monai/losses/adversarial_loss.py
  • monai/losses/dice.py
  • monai/losses/focal_loss.py
  • monai/losses/hausdorff_loss.py
  • monai/losses/mcc_loss.py
  • monai/losses/perceptual.py
  • monai/losses/spatial_mask.py
  • monai/losses/tversky.py
  • monai/losses/unified_focal_loss.py

…rsarial_loss.py

Address CodeRabbit review: move stacklevel parameter to same line
as closing quote for consistent formatting across the PR.

Signed-off-by: Raphael Malikian <rtmalikian@gmail.com>
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.

fix: add missing stacklevel=2 to warnings.warn() calls in losses/

1 participant