Skip to content

Conversation

@Borda
Copy link
Contributor

@Borda Borda commented Oct 28, 2025

simplify the lintong and reduce the number of used tools to increase consistency without any formatting loss

Description

A few sentences describing the changes proposed in this pull request.

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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 28, 2025

Warning

Rate limit exceeded

@Borda has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 35 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 5ba0ed1 and 6238654.

📒 Files selected for processing (35)
  • .pre-commit-config.yaml (1 hunks)
  • monai/apps/detection/utils/anchor_utils.py (3 hunks)
  • monai/losses/ds_loss.py (1 hunks)
  • monai/losses/perceptual.py (1 hunks)
  • monai/metrics/utils.py (2 hunks)
  • monai/networks/blocks/attention_utils.py (1 hunks)
  • monai/networks/blocks/crossattention.py (2 hunks)
  • monai/networks/blocks/denseblock.py (1 hunks)
  • monai/networks/blocks/mlp.py (1 hunks)
  • monai/networks/blocks/patchembedding.py (1 hunks)
  • monai/networks/blocks/pos_embed_utils.py (2 hunks)
  • monai/networks/blocks/rel_pos_embedding.py (2 hunks)
  • monai/networks/blocks/selfattention.py (3 hunks)
  • monai/networks/blocks/spatialattention.py (1 hunks)
  • monai/networks/blocks/transformerblock.py (1 hunks)
  • monai/networks/layers/simplelayers.py (1 hunks)
  • monai/networks/layers/utils.py (1 hunks)
  • monai/networks/layers/vector_quantizer.py (4 hunks)
  • monai/networks/nets/ahnet.py (1 hunks)
  • monai/networks/nets/autoencoderkl.py (2 hunks)
  • monai/networks/nets/basic_unet.py (1 hunks)
  • monai/networks/nets/dints.py (4 hunks)
  • monai/networks/nets/dynunet.py (5 hunks)
  • monai/networks/nets/netadapter.py (2 hunks)
  • monai/networks/nets/quicknat.py (3 hunks)
  • monai/networks/nets/resnet.py (1 hunks)
  • monai/networks/nets/segresnet_ds.py (3 hunks)
  • monai/networks/nets/senet.py (1 hunks)
  • monai/networks/nets/spade_network.py (3 hunks)
  • monai/networks/nets/swin_unetr.py (1 hunks)
  • monai/networks/nets/vista3d.py (6 hunks)
  • monai/networks/nets/vqvae.py (3 hunks)
  • monai/networks/schedulers/rectified_flow.py (1 hunks)
  • monai/networks/trt_compiler.py (6 hunks)
  • monai/networks/utils.py (1 hunks)

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

The diff applies widespread non-functional modernizations: many type hints converted from typing.Union/Optional and typing container aliases to PEP 604 (X | Y) and built-in generics (list[int], tuple[...]); several log/warning/error messages reformatted to f-strings; functools.lru_cache replaced with functools.cache in one metrics utility; pre-commit config adjusted (removed pyupgrade hook block, reformatted ruff args) and pyproject.toml enabled Ruff UP. No algorithmic changes or behavior-altering logic edits were introduced.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Verify PEP 604 annotations and removed typing imports across losses, transforms, network modules, and utilities.
  • Check public API signatures where annotations changed (nnUNet wrappers, SURELoss, DeepSupervisionLoss, vector quantizers, various network constructors/methods).
  • Confirm f-string replacements preserve exact log/warning/error text and spacing expected by tests.
  • Review functools.lru_cache → functools.cache semantic suitability for _get_neighbour_code_to_normals_table.
  • Inspect pre-commit and pyproject.toml edits for intended hook/lint behavior.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning Description is incomplete. Missing issue reference, and explanation is minimal. Only vague mention of 'linting' without clearly explaining the pyupgrade-to-Ruff-UP migration or scope of changes. Add issue reference (Fixes #...), clarify the pyupgrade replacement rationale, and explain why extensive typing/f-string changes accompany the tooling switch.
Docstring Coverage ⚠️ Warning Docstring coverage is 73.33% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed Title clearly summarizes the main change: replacing pyupgrade tool with Ruff's UP rule for linting.

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.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Overview

Greptile Summary

This PR modernizes Python syntax across five files by replacing outdated string formatting methods (.format()) with f-strings and updating lru_cache(maxsize=None) to the modern cache decorator. The changes align with Ruff's UP (pyupgrade) rule, consolidating linting tools to reduce tooling complexity while maintaining code quality. All modifications are syntactically equivalent transformations that adopt Python 3.6+ (f-strings) and Python 3.9+ (cache) best practices. The affected files span profiling utilities, TensorBoard/stats handlers, metrics utilities, and deepgrow datasets—all converting legacy string formatting to the recommended f-string syntax without altering any logic or output.

Important Files Changed

Filename Score Overview
tests/profile_subclass/profiling.py 5/5 Replaced .format() with f-string in a single print statement for profiling output
monai/handlers/tensorboard_handlers.py 5/5 Converted two warning messages from .format() to f-strings in TensorBoardStatsHandler
monai/handlers/stats_handler.py 5/5 Modernized two warning messages by replacing .format() with f-strings
monai/metrics/utils.py 5/5 Replaced lru_cache(maxsize=None) with cache decorator and updated import
monai/apps/deepgrow/dataset.py 5/5 Converted two logging.info statements from .format() to f-strings

Confidence score: 5/5

  • This PR is safe to merge with minimal risk—all changes are non-breaking syntax modernizations with identical functional behavior.
  • Score reflects straightforward string formatting upgrades and standard library improvements that are well-established Python best practices with no logic changes or potential runtime issues.
  • No files require special attention—all transformations are syntactically equivalent and maintain identical output.

5 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

@Borda Borda requested a review from virginiafdez as a code owner October 28, 2025 19:37
Borda and others added 3 commits October 28, 2025 20:39
Signed-off-by: jirka <jirka.borovec@seznam.cz>
for more information, see https://pre-commit.ci

Signed-off-by: jirka <jirka.borovec@seznam.cz>
Signed-off-by: jirka <jirka.borovec@seznam.cz>
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Overview

Greptile Summary

This review covers only the changes made since the last review, not the entire PR. Since the previous reviews, two critical issues were introduced: a fatal syntax error in monai/losses/dice.py (missing closing quote) that will break imports, and semantically incorrect type hints in monai/losses/sure_loss.py (parameters typed as | None but using non-None sentinel defaults). Additionally, a logical inconsistency exists in monai/losses/perceptual.py where an error message says "Adversarial Loss" instead of "Perceptual Loss" (pre-existing but now more visible). The remaining changes continue the PR's goal of replacing pyupgrade with Ruff's UP rules by modernizing string formatting (.format() → f-strings) and type annotations (Union[X, Y]X | Y, Optional[X]X | None, lru_cache(maxsize=None)cache). These syntactic updates are safe and maintain backward compatibility via from __future__ import annotations already present throughout the codebase.

Important Files Changed

Filename Score Overview
monai/losses/dice.py 1/5 BREAKING: Missing closing quote in f-string causes syntax error on line 497
monai/losses/sure_loss.py 2/5 Incorrect type hints: eps and complex_input typed as | None but use non-None sentinel defaults
monai/losses/perceptual.py 4/5 String formatting updated but error message incorrectly says "Adversarial Loss" instead of "Perceptual Loss"
monai/handlers/tensorboard_handlers.py 4/5 Format string conversion loses space separator on line 260 (: becomes :)
monai/losses/ds_loss.py 5/5 Modernizes Union to pipe syntax; safe with postponed annotations
monai/losses/spatial_mask.py 5/5 Replaces Optional with PEP 604 syntax; functionally equivalent
monai/losses/focal_loss.py 5/5 Converts Optional to pipe syntax across four type annotations
monai/losses/adversarial_loss.py 5/5 Updates %-formatting to .format() in error message
monai/transforms/utility/array.py 5/5 Removes Union import and uses pipe syntax in two method signatures
monai/metrics/utils.py 5/5 Replaces lru_cache(maxsize=None) with Python 3.9+ cache decorator
monai/handlers/stats_handler.py 5/5 Converts two .format() calls to f-strings in warning messages
monai/apps/deepgrow/dataset.py 5/5 Updates logging statements to use f-strings instead of .format()
tests/profile_subclass/profiling.py 5/5 Replaces .format() with f-string in print statement

Confidence score: 0/5

  • This PR introduces a syntax error that will prevent the module from importing and break production code immediately.
  • Score is 0/5 due to the fatal syntax error in monai/losses/dice.py (missing quote) and semantically incorrect type hints in monai/losses/sure_loss.py that misrepresent the parameter contracts. Additional concerns include a copy-paste error in monai/losses/perceptual.py and a formatting inconsistency in monai/handlers/tensorboard_handlers.py.
  • Critical attention required for monai/losses/dice.py (line 497), monai/losses/sure_loss.py (lines 46-48, 153), monai/losses/perceptual.py (line 98), and monai/handlers/tensorboard_handlers.py (line 260).

Additional Comments (1)

  1. monai/apps/nnunet/nnunet_bundle.py, line 508-509 (link)

    style: Type annotations now use PEP 604 syntax but are redundant here since the string literals already enforce types. The : str can be removed from both lines

14 files reviewed, 8 comments

Edit Code Review Agent Settings | Greptile

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Overview

Greptile Summary

This PR consolidates Python linting by replacing the standalone pyupgrade pre-commit hook with Ruff's built-in UP (pyupgrade) rules. The changes modernize Python syntax across the codebase: type hints are converted from typing.Union[A, B] and typing.Optional[T] to PEP 604 pipe-union syntax (A | B, T | None), .format() and % string formatting are replaced with f-strings, and functools.lru_cache(maxsize=None) is replaced with functools.cache. The .pre-commit-config.yaml removes the pyupgrade hook entirely and moves its exclusion patterns to the ruff hook, while pyproject.toml adds the UP rule to Ruff's lint selection. This architectural change reduces external dependencies, improves linting consistency, and simplifies CI/CD by unifying multiple syntax-modernization checks into a single tool.

Important Files Changed

Filename Score Overview
.pre-commit-config.yaml 5/5 Removes standalone pyupgrade hook and consolidates exclusions under ruff
pyproject.toml 5/5 Adds Ruff's UP rule to lint selection, enabling built-in pyupgrade checks
monai/losses/dice.py 0/5 String formatting update introduces syntax error (unclosed quote in error message)
monai/losses/perceptual.py 0/5 String formatting update plus critical indexing bug (off-by-one in feature slice)
tests/profile_subclass/profiling.py 1/5 F-string split across lines will truncate output (missing concatenation)
monai/losses/sure_loss.py 2/5 Type hint conversions introduce incorrect None annotations for sentinel-value parameters
monai/metrics/utils.py 3/5 Replaces lru_cache(maxsize=None) with cache, but function takes mutable default device=None
monai/handlers/stats_handler.py 3/5 F-string replacements missing spacing in warning messages
monai/handlers/tensorboard_handlers.py 4/5 F-string replacements missing spacing in warning messages
monai/losses/focal_loss.py 4/5 Type hints modernized to `T
monai/apps/deepgrow/dataset.py 4.5/5 Logging statements converted to multi-line f-strings correctly
monai/losses/adversarial_loss.py 5/5 String formatting updated from % to .format() correctly
monai/losses/ds_loss.py 5/5 Type hints modernized to PEP 604 union syntax correctly
monai/losses/spatial_mask.py 5/5 Type hints modernized to `T
monai/transforms/utility/array.py 5/5 Type hints modernized from Union to pipe-union syntax correctly
monai/apps/nnunet/nnunet_bundle.py 5/5 Type hints modernized across all function signatures correctly

Confidence score: 0/5

  • This PR is NOT safe to merge due to critical syntax errors and logic bugs that will break production code immediately.
  • Score reflects three blocking issues: unclosed string quote in dice.py (syntax error), off-by-one indexing bug in perceptual.py (incorrect computation), and broken output formatting in profiling.py (missing string concatenation). Additionally, incorrect type hints in sure_loss.py will mislead type checkers and several f-string replacements introduce minor spacing issues in warning messages.
  • Pay close attention to monai/losses/dice.py (syntax error on line497), monai/losses/perceptual.py (indexing bug on line 260 and copy-paste error on line 98), tests/profile_subclass/profiling.py (split f-string on lines 66-67), and monai/losses/sure_loss.py (incorrect type hints for eps and complex_input).

Additional Comments (1)

  1. monai/losses/perceptual.py, line 260 (link)

    logic: off-by-one slicing error: should be l_idx:r_idx not l_idx:i+r_idx. This will cause incorrect channel-wise feature indexing.

16 files reviewed, 5 comments

Edit Code Review Agent Settings | Greptile



@lru_cache(maxsize=None)
@cache
Copy link

Choose a reason for hiding this comment

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

logic: The decorator @cache does not accept any arguments, so the parameter device=None is not being cached as part of the key. This means calls with different devices will return the same cached tensor on the wrong device, causing errors. Either use @lru_cache(maxsize=None) with a hashable device wrapper, or accept that the cache is device-agnostic and convert the result after retrieval. Should the cache be keyed by device, or is it acceptable to convert the cached tensor to the requested device after retrieval?

Copy link
Member

Choose a reason for hiding this comment

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

I think this is a valid complaint that should be looked at.

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Overview

Greptile Summary

This review covers only the changes made since the last review, not the entire PR. The developer has corrected a critical syntax error in monai/losses/dice.py that was identified in the previous review. The error was a missing closing quote in an error message string within the GeneralizedWassersteinDiceLoss class constructor. This fix addresses a SyntaxError that would have prevented the entire monai.losses.dice module from being imported. The correction changes the malformed string 'GDL to the properly quoted 'GDL', ensuring the error message displays correctly when invalid weighting_mode values are provided. This change is part of the broader PR goal to migrate linting from pyupgrade to Ruff's UP rule, which caught this pre-existing syntax error during the linting process.

Important Files Changed

Filename Score Overview
monai/losses/dice.py 5/5 Fixed missing closing quote in error message string on line 497

Confidence score: 5/5

  • This change is a straightforward syntax error fix with zero risk of unintended side effects
  • The fix correctly addresses the exact issue identified in the previous review by properly closing the quoted string
  • No files require special attention as the single-line fix is trivial and clearly correct

1 file reviewed, no comments

Edit Code Review Agent Settings | Greptile

@ericspod
Copy link
Member

Hi @Borda thanks for the contribution. There's a lot of changes related to typing and f-strings rather than the PyUpgrade change, these are fine but it obscures what is being done here. What is the purpose of changing the .pre-commit-config.yaml file? What is accomplished here? If you can look at the code format issue the changes are otherwise ready to go and be finalised.

@Borda
Copy link
Contributor Author

Borda commented Nov 2, 2025

There's a lot of changes related to typing and f-strings rather than the PyUpgrade change

Good call, but f-string is to be upgraded, and if original pyupgrade mised it, it is rather its issue than Ruff's doing its job, right?

What is the purpose of changing the .pre-commit-config.yaml file?

removing pyupgrade hooks, which become redundant

If you can look at the code format issue the changes are otherwise ready to go and be finalised.

Yes, will do

Borda added 6 commits November 7, 2025 10:00
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
monai/networks/nets/vista3d.py (1)

882-882: Fix torch.torch.Tensor typo throughout PositionEmbeddingRandom.

torch.torch.Tensor is invalid - should be torch.Tensor. This typo appears in:

  • _pe_encoding signature (line 882)
  • forward return type (line 894)
  • forward_with_coords signature and return type (lines 910-911)
-    def _pe_encoding(self, coords: torch.torch.Tensor) -> torch.torch.Tensor:
+    def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:

-    def forward(self, size: tuple[int, int, int]) -> torch.torch.Tensor:
+    def forward(self, size: tuple[int, int, int]) -> torch.Tensor:

     def forward_with_coords(
-        self, coords_input: torch.torch.Tensor, image_size: tuple[int, int, int]
-    ) -> torch.torch.Tensor:
+        self, coords_input: torch.Tensor, image_size: tuple[int, int, int]
+    ) -> torch.Tensor:

Also applies to: 894-894, 910-911

🧹 Nitpick comments (4)
monai/networks/nets/spade_network.py (2)

159-159: F-string conversion looks good.

The error message is clearer with f-string formatting. Static analysis suggests extracting long messages to the exception class, but this is a minor style preference that can be deferred.


258-258: F-string conversion looks good.

Same improvement as line 159. The TRY003 hint (extract long messages to exception class) applies here too but is optional.

monai/networks/blocks/pos_embed_utils.py (2)

45-48: Docstrings use capitalized List instead of list.

Lines 45 and 48 reference List[int] and List[float] but the signature uses lowercase list. Update for consistency.

-        grid_size (int | List[int]): The size of the grid in each spatial dimension.
+        grid_size (int | list[int]): The size of the grid in each spatial dimension.
         embed_dim (int): The dimension of the embedding.
         spatial_dims (int): The number of spatial dimensions (2 for 2D, 3 for 3D).
-        scales (float | List[float]): The scale for every spatial dimension. If a single float is provided,
+        scales (float | list[float]): The scale for every spatial dimension. If a single float is provided,

95-95: Docstring uses capitalized List instead of list.

Line 95 references List[int] but the signature uses lowercase list. Update for consistency.

-        grid_size (List[int]): The size of the grid in each spatial dimension.
+        grid_size (int | list[int]): The size of the grid in each spatial dimension.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 8a7eeed and 5ba0ed1.

📒 Files selected for processing (32)
  • .pre-commit-config.yaml (1 hunks)
  • monai/apps/detection/utils/anchor_utils.py (3 hunks)
  • monai/networks/blocks/attention_utils.py (1 hunks)
  • monai/networks/blocks/crossattention.py (2 hunks)
  • monai/networks/blocks/denseblock.py (1 hunks)
  • monai/networks/blocks/mlp.py (1 hunks)
  • monai/networks/blocks/patchembedding.py (1 hunks)
  • monai/networks/blocks/pos_embed_utils.py (2 hunks)
  • monai/networks/blocks/rel_pos_embedding.py (2 hunks)
  • monai/networks/blocks/selfattention.py (3 hunks)
  • monai/networks/blocks/spatialattention.py (1 hunks)
  • monai/networks/blocks/transformerblock.py (1 hunks)
  • monai/networks/layers/simplelayers.py (1 hunks)
  • monai/networks/layers/utils.py (1 hunks)
  • monai/networks/layers/vector_quantizer.py (4 hunks)
  • monai/networks/nets/ahnet.py (1 hunks)
  • monai/networks/nets/autoencoderkl.py (2 hunks)
  • monai/networks/nets/basic_unet.py (1 hunks)
  • monai/networks/nets/dints.py (4 hunks)
  • monai/networks/nets/dynunet.py (5 hunks)
  • monai/networks/nets/netadapter.py (2 hunks)
  • monai/networks/nets/quicknat.py (3 hunks)
  • monai/networks/nets/resnet.py (1 hunks)
  • monai/networks/nets/segresnet_ds.py (3 hunks)
  • monai/networks/nets/senet.py (1 hunks)
  • monai/networks/nets/spade_network.py (3 hunks)
  • monai/networks/nets/swin_unetr.py (1 hunks)
  • monai/networks/nets/vista3d.py (6 hunks)
  • monai/networks/nets/vqvae.py (3 hunks)
  • monai/networks/schedulers/rectified_flow.py (1 hunks)
  • monai/networks/trt_compiler.py (6 hunks)
  • monai/networks/utils.py (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • monai/networks/utils.py
  • monai/networks/nets/swin_unetr.py
  • monai/networks/blocks/attention_utils.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • .pre-commit-config.yaml
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit configuration file

Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.

Files:

  • monai/networks/blocks/crossattention.py
  • monai/networks/nets/senet.py
  • monai/networks/blocks/mlp.py
  • monai/networks/schedulers/rectified_flow.py
  • monai/networks/blocks/patchembedding.py
  • monai/networks/nets/spade_network.py
  • monai/networks/nets/vista3d.py
  • monai/networks/blocks/spatialattention.py
  • monai/networks/layers/utils.py
  • monai/networks/blocks/transformerblock.py
  • monai/networks/layers/simplelayers.py
  • monai/networks/blocks/denseblock.py
  • monai/networks/nets/vqvae.py
  • monai/networks/nets/netadapter.py
  • monai/networks/nets/autoencoderkl.py
  • monai/apps/detection/utils/anchor_utils.py
  • monai/networks/nets/dints.py
  • monai/networks/nets/ahnet.py
  • monai/networks/nets/resnet.py
  • monai/networks/blocks/selfattention.py
  • monai/networks/trt_compiler.py
  • monai/networks/nets/dynunet.py
  • monai/networks/blocks/pos_embed_utils.py
  • monai/networks/nets/quicknat.py
  • monai/networks/layers/vector_quantizer.py
  • monai/networks/nets/segresnet_ds.py
  • monai/networks/blocks/rel_pos_embedding.py
  • monai/networks/nets/basic_unet.py
🪛 Ruff (0.14.3)
monai/networks/nets/spade_network.py

159-159: Avoid specifying long messages outside the exception class

(TRY003)


258-258: Avoid specifying long messages outside the exception class

(TRY003)

monai/networks/nets/resnet.py

243-243: Avoid specifying long messages outside the exception class

(TRY003)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
  • GitHub Check: min-dep-pytorch (2.7.1)
  • GitHub Check: min-dep-pytorch (2.6.0)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: min-dep-pytorch (2.8.0)
  • GitHub Check: min-dep-py3 (3.12)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: min-dep-py3 (3.11)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-os (windows-latest)
  • GitHub Check: min-dep-os (macOS-latest)
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: packaging
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: build-docs
🔇 Additional comments (58)
monai/networks/blocks/spatialattention.py (1)

48-48: Type annotation modernization looks good.

PEP 604 union syntax applied correctly. Semantically equivalent to Optional[torch.dtype].

monai/networks/blocks/denseblock.py (1)

14-14: PEP 585 modernization applied correctly.

Import updated to use collections.abc.Sequence instead of typing.Sequence. This is the recommended practice for Python 3.9+ and aligns with Ruff's UP rule.

monai/networks/nets/spade_network.py (1)

14-14: LGTM: Import modernization.

Switching from typing.Sequence to collections.abc.Sequence aligns with PEP 585 and Ruff's UP rules.

monai/networks/layers/vector_quantizer.py (2)

14-14: LGTM: Import modernization correct.

The shift from typing.Tuple to built-in tuple and typing.Sequence to collections.abc.Sequence aligns with Python 3.9+ best practices.


90-90: LGTM: Type hint modernization consistent.

All Tuple[...] annotations correctly updated to built-in tuple[...] syntax. Non-functional changes only.

Also applies to: 167-167, 214-214

monai/networks/blocks/pos_embed_utils.py (2)

35-35: Type hints modernized correctly.

PEP 604 union syntax and built-in generics applied properly.


88-88: Type hint modernized correctly.

PEP 604 union syntax applied properly.

monai/networks/blocks/patchembedding.py (1)

56-56: Type hint modernized correctly.

Optional[dict]dict | None is semantically equivalent and follows PEP 604.

monai/apps/detection/utils/anchor_utils.py (3)

42-42: Import modernization correct.

The shift to collections.abc.Sequence and removal of typing.List aligns with built-in generics usage throughout the file.


109-109: Type annotation correctly applied.

Explicit __annotations__ declaration avoids unintended class attribute creation in nn.Module while providing type information. Matches actual usage at line 139.


367-367: Type annotation correctly applied.

Consistent with parent class pattern. Matches actual usage at line 389.

monai/networks/layers/simplelayers.py (1)

16-16: LGTM—Standard library import modernization.

The move from typing.Sequence to collections.abc.Sequence aligns with Python 3.9+ best practices.

monai/networks/nets/senet.py (1)

122-122: LGTM—F-string modernization.

The error message is now clearer and follows modern Python conventions.

monai/networks/nets/autoencoderkl.py (2)

190-190: LGTM—Built-in generic type.

Using list[nn.Module] instead of List[nn.Module] is the modern approach for Python 3.9+.


340-340: LGTM—Built-in generic type.

Consistent with the modernization in Encoder (line 190).

monai/networks/nets/resnet.py (1)

243-243: LGTM—F-string modernization.

The error message formatting is now consistent with modern Python practices.

monai/networks/nets/ahnet.py (3)

141-141: LGTM—Modern union syntax.

The bool | None syntax is cleaner and aligns with Python 3.10+ conventions.


177-177: LGTM—Modern union syntax.

Consistent with the change in UpTransition (line 141).


288-288: LGTM—Modern union syntax.

Consistent type hint modernization throughout the file.

monai/networks/blocks/crossattention.py (2)

43-45: LGTM—Type hint modernization.

The constructor parameters now use the modern X | None syntax, consistent with Python 3.10+.


136-136: LGTM—Type hint modernization.

The forward method signature is now consistent with the constructor's type hint style.

monai/networks/nets/basic_unet.py (1)

152-152: LGTM—Type hint modernization.

The forward signature now uses modern union syntax. The docstring correctly reflects that x_e is optional.

monai/networks/blocks/transformerblock.py (1)

93-93: LGTM—Type hint modernization.

Both optional parameters now use the modern X | None syntax.

monai/networks/layers/utils.py (1)

130-130: Type annotation modernization looks good.

The change from Optional[tuple] to tuple | None is semantically equivalent and aligns with PEP 604.

monai/networks/blocks/rel_pos_embedding.py (2)

12-12: Import modernization is correct.

Moving Iterable from typing to collections.abc follows current best practices.


22-22: Type annotation update is correct.

Built-in tuple generic with union syntax is semantically equivalent to the previous annotation.

monai/networks/trt_compiler.py (4)

21-21: Import cleanup is appropriate.

Removing unused typing imports after modernization keeps the module clean.


244-246: Function signature modernization is correct.

Parameter and return type annotations properly use built-in generics and union syntax.


604-605: Parameter type updates look good.

Using dict[str, Any] | None and str | list[str] | None aligns with modern typing conventions.


628-628: Variable annotation is correctly updated.

dict[str, Any] is the modern equivalent of Dict[str, Any].

monai/networks/nets/vqvae.py (3)

109-109: Type annotation properly modernized.

Using built-in tuple with Sequence is the correct approach.


200-200: Type annotation update is correct.

Consistent use of built-in tuple generic across the codebase.


314-319: Parameter type annotations properly updated.

Both downsample_parameters and upsample_parameters use consistent modern typing.

monai/networks/nets/dints.py (4)

43-43: Interface signature modernization is correct.

The union syntax maintains the same semantics for optional parameters.


177-177: Forward signature properly updated.

Consistent with the interface definition.


305-305: Type annotation matches interface.

Consistent use of union syntax across all forward method signatures.


576-577: F-string conversion improves readability.

The f-string syntax is clearer than string concatenation for formatted output.

monai/networks/blocks/selfattention.py (3)

43-43: Parameter type annotation properly updated.

Using tuple | None is consistent with modern Python typing.


103-112: Attribute type annotations correctly modernized.

All attribute annotations use union syntax consistently across out_proj, qkv, to_q, to_k, and to_v.


155-155: Forward method signature properly updated.

The optional attn_mask parameter type is correctly expressed with union syntax.

monai/networks/nets/segresnet_ds.py (3)

390-390: Return type annotation properly modernized.

Using None | torch.Tensor | list[torch.Tensor] correctly expresses the possible return types.


426-426: Forward method return type is consistent.

Matches the _forward implementation signature.


487-487: Complex return type properly expressed.

The tuple of unions correctly represents the dual-branch output structure.

monai/networks/nets/dynunet.py (5)

14-15: Import updates are correct.

Moving Sequence to collections.abc and removing List, Tuple from typing aligns with modern practices.


36-36: Attribute type annotation properly updated.

Using Optional[list[torch.Tensor]] is correct.


140-142: Parameter type annotations modernized.

Using built-in tuple for dropout, norm_name, and act_name is correct.


173-173: Initialization annotation correctly updated.

list[torch.Tensor] properly replaces List[torch.Tensor].


327-328: Method signature parameters properly typed.

Using list[int] for channel parameters is the modern equivalent.

monai/networks/nets/quicknat.py (3)

14-14: LGTM: Import modernization is correct.

Switching to collections.abc.Sequence and removing unused typing imports after type hint updates is appropriate.


126-127: LGTM: Type hints correctly modernized.

Optional[X]X | None is a correct PEP 604 modernization with no behavioral change.


363-364: LGTM: Type hints correctly modernized.

Union[Tuple, str]tuple | str modernizes to PEP 604 syntax and replaces deprecated unparameterized Tuple with builtin tuple.

monai/networks/nets/vista3d.py (6)

15-16: LGTM. Import modernization aligns with PEP 604.

The removal of Tuple and Optional from typing and addition of Sequence from collections.abc correctly supports the built-in generic type hints used throughout the file.


695-695: LGTM. Return type modernized correctly.


772-772: LGTM. Return type modernized correctly.


876-876: LGTM. Parameter type modernized correctly.


894-894: Inconsistency: AI summary claims torch.torch.Tensor was fixed.

The summary states coords_input type was updated from torch.torch.Tensor to torch.Tensor, but the code still contains torch.torch.Tensor at lines 882, 894, 910, 911.


910-910: LGTM. Parameter type modernized correctly.

The image_size parameter type change from Tuple[int, int, int] to tuple[int, int, int] is correct (separate from the torch.torch.Tensor issue flagged above).

monai/networks/nets/netadapter.py (1)

14-14: Import cleanup aligns with built-in generic usage.

Removing Dict is correct since line 112 now uses dict[str, torch.Tensor].

Comment on lines 58 to +59
# Use Union[nn.Dropout, nn.Identity] for type annotations
self.drop1: Union[nn.Dropout, nn.Identity]
self.drop2: Union[nn.Dropout, nn.Identity]
self.drop1: nn.Dropout | nn.Identity
self.drop2: nn.Dropout | nn.Identity
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Outdated comment contradicts implementation.

Line 57 references Union syntax, but lines 58-59 use pipe syntax.

Remove or update the comment:

-        # Use Union[nn.Dropout, nn.Identity] for type annotations
         self.drop1: nn.Dropout | nn.Identity
         self.drop2: nn.Dropout | nn.Identity
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Use Union[nn.Dropout, nn.Identity] for type annotations
self.drop1: Union[nn.Dropout, nn.Identity]
self.drop2: Union[nn.Dropout, nn.Identity]
self.drop1: nn.Dropout | nn.Identity
self.drop2: nn.Dropout | nn.Identity
self.drop1: nn.Dropout | nn.Identity
self.drop2: nn.Dropout | nn.Identity
🤖 Prompt for AI Agents
In monai/networks/blocks/mlp.py around lines 57 to 59, the comment stating "Use
Union[nn.Dropout, nn.Identity] for type annotations" is outdated because the
code uses Python 3.10+ pipe syntax (self.drop1: nn.Dropout | nn.Identity and
self.drop2: nn.Dropout | nn.Identity); update the comment to reflect the pipe
syntax (e.g., "Use nn.Dropout | nn.Identity for type annotations") or remove the
comment entirely so it no longer contradicts the implementation.

if isinstance(x, tuple):
x = x[0] # it might be a namedtuple such as torchvision.model.InceptionOutputs
elif torch.jit.isinstance(x, Dict[str, torch.Tensor]):
elif torch.jit.isinstance(x, dict[str, torch.Tensor]):
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify TorchScript compatibility with built-in generic syntax.

TorchScript's type system historically required typing.Dict for proper type checking. Confirm that torch.jit.isinstance(x, dict[str, torch.Tensor]) works correctly with the project's minimum PyTorch version.


🏁 Script executed:

#!/bin/bash
# Check minimum Python and PyTorch versions, search for other TorchScript type annotations

# Find Python version requirement
rg -n 'python_requires|Programming Language :: Python ::' setup.py setup.cfg pyproject.toml 2>/dev/null || echo "No Python version requirement found"

# Find PyTorch version requirement
rg -n 'torch[=><!]' requirements.txt setup.py setup.cfg pyproject.toml 2>/dev/null | head -20

# Search for other torch.jit.isinstance calls to check consistency
rg -n 'torch\.jit\.isinstance' --type=py -C2

Length of output: 1842



---

🌐 Web query:

```web
PyTorch 2.4 TorchScript dict generic type support built-in syntax

💡 Result:

Short answer: No — as of PyTorch 2.4, TorchScript does not use the PEP 585 builtin-generic syntax (e.g. dict[str,int]). Use typing.Dict / typing.List (or the typing aliases) or PEP‑526 annotations (e.g. from typing import Dict; my_dict: Dict[str,int]) for TorchScript types. [1][2]

Sources:

  • TorchScript docs showing typing.Dict usage and PEP‑526 attribute annotations. [1]
  • PyTorch 2.4 release / TorchScript pages (docs reference behavior across 2.x). [2]


---

🏁 Script executed:

```shell
#!/bin/bash
# Check if netadapter functions are tested with TorchScript
rg -n 'netadapter|NetAdapter' --type=py tests/ 2>/dev/null | head -10
rg -n 'torch.jit.script|torch.jit.trace' tests/ --type=py | head -10
rg -n 'def.*extract' monai/networks/nets/netadapter.py -A5 | head -20

Length of output: 120


Change dict[str, torch.Tensor] to typing.Dict[str, torch.Tensor].

PyTorch 2.4 TorchScript does not support PEP 585 built-in generic syntax. The torch.jit.isinstance() check at line 112 requires typing.Dict instead of dict. This pattern also appears in retinanet_network.py:333 and should be corrected there as well.

🤖 Prompt for AI Agents
In monai/networks/nets/netadapter.py around line 112, the torch.jit.isinstance
check uses PEP 585 syntax `dict[str, torch.Tensor]` which TorchScript (PyTorch
2.4) does not support; replace it with `typing.Dict[str, torch.Tensor]` and add
or ensure `from typing import Dict` (or import typing and use typing.Dict) is
present at the top of the file; also update the same pattern in
monai/networks/nets/retinanet_network.py at line ~333 to use typing.Dict[str,
torch.Tensor].


def step(
self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor, next_timestep: Union[int, None] = None
self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor, next_timestep: int | None = None
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Update docstring to match PEP 604 syntax.

Line 294 still uses Union[int, None] while the signature now uses int | None. Update to int | None or simplify to "Optional next timestep."

-            next_timestep (Union[int, None]): Optional next timestep.
+            next_timestep (int | None): Optional next timestep.

Also applies to: 294-294

🤖 Prompt for AI Agents
In monai/networks/schedulers/rectified_flow.py around lines 285 to 294, the
function signature uses PEP 604 syntax (int | None) for next_timestep but the
docstring still shows Union[int, None]; update the docstring to match the
signature by replacing "Union[int, None]" with "int | None" or simpler text like
"Optional next timestep" and ensure the parameter description formatting matches
the rest of the docstring.

Signed-off-by: jirka <jirka.borovec@seznam.cz>
Signed-off-by: jirka <jirka.borovec@seznam.cz>
@ericspod
Copy link
Member

ericspod commented Nov 9, 2025

There's a few things coderabbit has mentioned that are worth looking at, but the failed checks are all related to versioneer files that should be ignored I think. I'm not sure why from your changes why these aren't being ignored now. All other changes looked fine to me however.

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.

2 participants