Skip to content

added list extend to MultiSampleTrait #8531

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: dev
Choose a base branch
from

Conversation

lukas-folle-snkeos
Copy link

Fixes #8528.

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.

Copy link

coderabbitai bot commented Aug 8, 2025

Walkthrough

The change modifies the apply_transform function in monai/transforms/transform.py to alter how nested lists or tuples returned by transforms at the leaf recursion level are handled. Instead of always flattening these nested lists, the new logic conditionally extends or appends to the result list based on the original item's type, preserving nested structures when appropriate. Additionally, a multi-line error message in MapTransform.key_iterator was refactored into a single-line formatted string without changing functionality.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Assessment against linked issues

Objective Addressed Explanation
Fix handling of nested lists/tuples in apply_transform to avoid list-of-lists in MultiSampleTrait stacking (#8528)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 7df8cb9 and be46018.

📒 Files selected for processing (1)
  • monai/transforms/transform.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • monai/transforms/transform.py
⏰ 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-py3 (3.11)
  • GitHub Check: min-dep-pytorch (2.7.1)
  • GitHub Check: min-dep-pytorch (2.6.0)
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: min-dep-pytorch (2.4.1)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-py3 (3.12)
  • GitHub Check: min-dep-os (macOS-latest)
  • GitHub Check: min-dep-os (windows-latest)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: packaging
  • GitHub Check: build-docs
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: quick-py3 (ubuntu-latest)
✨ 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.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai 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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

Documentation and Community

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

Copy link

@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: 1

🧹 Nitpick comments (5)
monai/transforms/transform.py (5)

127-137: Docstring: fix parameter name and clarify behavior

“map_data” should be “map_items”, and mention that list/tuple returns are flattened one level.

-    If `data` is a list or tuple and `map_data` is True, each item of `data` will be transformed
+    If `data` is a list or tuple and `map_items` is True, each item of `data` will be transformed
     and this method returns a list of outcomes.
@@
-            - If an integer is provided, it specifies the maximum level of nesting to which the transformation
-              should be recursively applied. This allows treating multi-sample transforms applied after another
-              multi-sample transform while controlling how deep the mapping goes.
+            - If an integer is provided, it specifies the maximum level of nesting to which the transformation
+              should be recursively applied. When a transform returns a list or tuple, the results are flattened
+              one level at each mapped depth.

174-199: Exception logging: style-only — OK; avoid mutating data for logging

Formatting is good. Minor nit: don’t reassign data when logging a first element; use a temp to avoid shadowing.

-            if isinstance(data, (list, tuple)):
-                data = data[0]
+            if isinstance(data, (list, tuple)):
+                _data_for_log = data[0]
+            else:
+                _data_for_log = data
@@
-            if isinstance(data, dict):
-                for k, v in data.items():
+            if isinstance(_data_for_log, dict):
+                for k, v in _data_for_log.items():
                     _log_stats(data=v, prefix=k)
             else:
-                _log_stats(data=data)
+                _log_stats(data=_data_for_log)

459-461: TypeError message should report offending element type, not keys

Inside the loop, report type(key).__name__} for clarity.

-                raise TypeError(
-                    f"keys must be one of (Hashable, Iterable[Hashable]) but is {type(keys).__name__}."
-                )
+                raise TypeError(
+                    f"keys must be one of (Hashable, Iterable[Hashable]); "
+                    f"found element of type {type(key).__name__}."
+                )

515-518: key_iterator: signature formatting — OK

Optional: annotate as Generator[Any, None, None] for completeness.


66-68: Docstring nits in _apply_transform

  • Typo: “this class is function” → “this function”.
  • Sphinx ref missing closing backtick: :ref:Lazy Resampling topic<lazy_resampling>.

Also applies to: 75-78

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between b92b2ce and 7560a37.

📒 Files selected for processing (1)
  • monai/transforms/transform.py (10 hunks)
🧰 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/transforms/transform.py
⏰ 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: quick-py3 (ubuntu-latest)
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: build-docs
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: packaging
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: min-dep-os (macOS-latest)
  • GitHub Check: min-dep-pytorch (2.7.1)
  • GitHub Check: min-dep-pytorch (2.4.1)
  • GitHub Check: min-dep-os (windows-latest)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: min-dep-pytorch (2.6.0)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-py3 (3.11)
  • GitHub Check: min-dep-py3 (3.12)
🔇 Additional comments (8)
monai/transforms/transform.py (8)

93-108: _apply_transform: style-only refactor — OK

Multiline call/returns improve readability; logic unchanged.


225-263: set_random_state: seeding cast and MAX_SEED mod — OK

Casting to int64 and modding by MAX_SEED is appropriate for NumPy 2.0 compatibility; type checks/readability improved.


256-259: Type check message — OK

Clear, explicit message; no change requested.


277-279: NotImplemented message — OK

Consistent and informative.


335-337: NotImplemented message — OK

Consistent and informative.


441-448: Hook attachment formatting — OK

No behavioral change; readability improved.


481-483: sync_meta_info call — OK

Style change only; behavior preserved.


511-513: NotImplemented message — OK

Consistent across classes.

I, Lukas Folle <[email protected]>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <[email protected]>
Copy link

@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: 1

🧹 Nitpick comments (2)
monai/transforms/transform.py (2)

156-165: Type annotation tightening

The function currently declares -> list[Any] | ReturnType but constructs list[ReturnType]. Prefer narrowing to list[ReturnType] | ReturnType for consistency.

Proposed signature (outside this hunk):

def apply_transform(...) -> list[ReturnType] | ReturnType:
    ...

515-518: Return type hint could be more explicit

key_iterator yields either a Hashable or a tuple when extra iterables are present. Consider tightening the annotation for better tooling.

-    ) -> Generator:
+    ) -> Generator[Hashable | tuple[Hashable, ...], None, None]:
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between b92b2ce and 7560a37.

📒 Files selected for processing (1)
  • monai/transforms/transform.py (10 hunks)
🧰 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/transforms/transform.py
⏰ 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). (4)
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: packaging
🔇 Additional comments (14)
monai/transforms/transform.py (14)

93-96: Refactor-only: OK

Call-site reformatting reads cleaner. No functional change.


98-103: Refactor-only: OK

Tuple-unpack branch formatting is fine. No logic change.


104-108: Refactor-only: OK

Single-arg branch formatting is fine. No logic change.


174-199: Refactor-only: OK

Error-logging reformatting is clear; logic unchanged.


225-227: Refactor-only: OK

Signature reflow is fine; types unchanged.


245-251: Seed normalization: OK

Modulo against MAX_SEED post np.int64 cast is reasonable for NumPy 2.0 compat.


256-258: Refactor-only: OK

TypeError message formatting is fine.


277-279: Refactor-only: OK

NotImplementedError reflow is fine.


335-337: Refactor-only: OK

Abstract call error message reflow is fine.


441-443: Refactor-only: OK

Hook attachment formatting is clearer.


447-448: Refactor-only: OK

Inverse hook formatting is clearer.


459-461: Refactor-only: OK

Type check error formatting is fine.


481-483: Refactor-only: OK

sync_meta_info call formatting is fine.


511-513: Refactor-only: OK

NotImplementedError reflow is fine.

DCO Remediation Commit for Lukas Folle <[email protected]>

I, Lukas Folle <[email protected]>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <[email protected]>
DCO Remediation Commit for Lukas Folle <[email protected]>

I, Lukas Folle <[email protected]>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <[email protected]>
@lukas-folle-snkeos
Copy link
Author

All remaining failing CI runs are not coming from this change.

# Only extend if we're at the leaf level (map_items_ == 1) and the transform
# actually returned a list (not preserving nested structure)
if isinstance(res_item, list) and map_items_ == 1:
if not isinstance(item, (list, tuple)):
Copy link
Member

Choose a reason for hiding this comment

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

Within the containing block res_item will always be a list (line 151) and so this if statement's condition is always false. I'm not sure the logic is what you're expecting it to be here?

@ericspod ericspod requested a review from atbenmurray August 15, 2025 02:46
@ericspod
Copy link
Member

Hi @lukas-folle-snkeos thanks for the contribution! Please check the logic I flagged and we do need tests to check that this behaviour is correct. You can take the mentioned issue as an example of what to check for but I think we need to test this logic thoroughly and more clearly document what's going on in comments.

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.

Stacking two or more MultiSampleTrait-like transforms breaks execute_compose()
2 participants