enh(engines/utils): use tuple/dict comprehensions in PrepareBatchExtraInput#8831
enh(engines/utils): use tuple/dict comprehensions in PrepareBatchExtraInput#8831Zeesejo wants to merge 7 commits intoProject-MONAI:devfrom
Conversation
Fixes Project-MONAI#8820 - input_amplitude was incorrectly computed from `target` and target_amplitude from `input`. Corrected to match semantic meaning and standard forward(input, target) convention. Signed-off-by: Zeeshan Modi <92383127+Zeesejo@users.noreply.github.com>
Fixes Project-MONAI#8822 - The forward() docstring examples used `print(1-SSIMLoss()(x,y))`, but SSIMLoss already computes 1-ssim internally. The `1-` prefix made examples return ssim (not loss), misleading users into training with inverted loss. Signed-off-by: Zeeshan Modi <92383127+Zeesejo@users.noreply.github.com>
…aInput Replace the imperative list-append and dict-update loops in PrepareBatchExtraInput.__call__ with direct tuple generator and dict comprehension expressions. Also add explicit type annotations for args_ and kwargs_. Suggested by @ericspod in Project-MONAI#8747. Closes Project-MONAI#8806. Signed-off-by: Zeeshan Modi <92383127+Zeesejo@users.noreply.github.com>
for more information, see https://pre-commit.ci
📝 WalkthroughWalkthroughThe Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
monai/engines/utils.py (1)
222-223: Tighten the type annotations (optional).
tupleanddictare valid but uninformative. Considertuple[torch.Tensor, ...]anddict[str, torch.Tensor]to match the return signature on line 215 and what_get_datayields.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@monai/engines/utils.py` around lines 222 - 223, The current annotations for args_ and kwargs_ are too broad; narrow them to match what _get_data returns and the function's declared return (see the return signature around line 215). Change args_: tuple = () to something like args_: tuple[torch.Tensor, ...] = () and kwargs_: dict = {} to kwargs_: dict[str, torch.Tensor] = {} (or other more specific key/value types used by _get_data) so the types reflect actual tensors and string keys used by the code.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@monai/engines/utils.py`:
- Around line 236-240: The indentation around the branch that handles
self.extra_keys is wrong: fix the over-indented lines so the elif
isinstance(self.extra_keys, dict): and its kwargs_ = {k: _get_data(v) ...} are
aligned with the other conditional branches and move the return statement
(return cast(torch.Tensor, image), cast(torch.Tensor, label), args_, kwargs_)
out of the elif-block to the outer scope of the function so it always executes;
ensure symbols referenced include self.extra_keys, _get_data, kwargs_, args_,
image and label so the dict, list/str/tuple and default branches all return
consistently.
---
Nitpick comments:
In `@monai/engines/utils.py`:
- Around line 222-223: The current annotations for args_ and kwargs_ are too
broad; narrow them to match what _get_data returns and the function's declared
return (see the return signature around line 215). Change args_: tuple = () to
something like args_: tuple[torch.Tensor, ...] = () and kwargs_: dict = {} to
kwargs_: dict[str, torch.Tensor] = {} (or other more specific key/value types
used by _get_data) so the types reflect actual tensors and string keys used by
the code.
🪄 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
Run ID: 52809bac-7f01-4e6d-9d51-a2e6b88f7193
📒 Files selected for processing (1)
monai/engines/utils.py
| elif isinstance(self.extra_keys, dict): | ||
| for k, v in self.extra_keys.items(): | ||
| kwargs_.update({k: _get_data(v)}) | ||
| kwargs_ = {k: _get_data(v) for k, v in self.extra_keys.items()} | ||
|
|
||
|
|
||
| return cast(torch.Tensor, image), cast(torch.Tensor, label), tuple(args_), kwargs_ | ||
| return cast(torch.Tensor, image), cast(torch.Tensor, label), args_, kwargs_ |
There was a problem hiding this comment.
Broken indentation — file fails to import.
Lines 237 and 240 are over-indented, triggering IndentationError: unindent does not match any outer indentation level (confirmed by Ruff and the premerge/premerge-min pipelines). Beyond the syntax error, the return at line 240 sits at the elif block's indentation, so once parsed it would only execute when extra_keys is a dict — the str/list/tuple branch would fall through with no return.
🔧 Proposed fix
if isinstance(self.extra_keys, (str, list, tuple)):
args_ = tuple(_get_data(k) for k in ensure_tuple(self.extra_keys))
-
elif isinstance(self.extra_keys, dict):
- kwargs_ = {k: _get_data(v) for k, v in self.extra_keys.items()}
-
+ kwargs_ = {k: _get_data(v) for k, v in self.extra_keys.items()}
- return cast(torch.Tensor, image), cast(torch.Tensor, label), args_, kwargs_
+ return cast(torch.Tensor, image), cast(torch.Tensor, label), args_, kwargs_🧰 Tools
🪛 GitHub Actions: premerge
[error] 240-240: Python import failed with IndentationError: 'unindent does not match any outer indentation level' at line 240.
🪛 GitHub Actions: premerge-min
[error] 240-240: Python failed with IndentationError: "unindent does not match any outer indentation level" during import. Step: "python -c "import monai; monai.config.print_config()"".
🪛 Ruff (0.15.10)
[warning] 240-240: unindent does not match any outer indentation level
(invalid-syntax)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@monai/engines/utils.py` around lines 236 - 240, The indentation around the
branch that handles self.extra_keys is wrong: fix the over-indented lines so the
elif isinstance(self.extra_keys, dict): and its kwargs_ = {k: _get_data(v) ...}
are aligned with the other conditional branches and move the return statement
(return cast(torch.Tensor, image), cast(torch.Tensor, label), args_, kwargs_)
out of the elif-block to the outer scope of the function so it always executes;
ensure symbols referenced include self.extra_keys, _get_data, kwargs_, args_,
image and label so the dict, list/str/tuple and default branches all return
consistently.
Fixes #8806
Description
This implements the suggestion made by @ericspod in the review of #8747.
In
PrepareBatchExtraInput.__call__(monai/engines/utils.py), replace the imperativelist.appendloop anddict.updateloop with a direct tuple generator expression and dict comprehension, respectively. Also adds explicit type annotations (args_: tupleandkwargs_: dict) for clarity.Before:
After:
Types of changes
./runtests.sh -f -u --net --coverage../runtests.sh --quick --unittests --disttests.make htmlcommand in thedocs/folder.