Skip to content

Fix #8775: handle torch.Tensor input in compute_shape_offset#8812

Open
williams145 wants to merge 4 commits intoProject-MONAI:devfrom
williams145:fix/issue-8775-compute-shape-offset-pytorch29
Open

Fix #8775: handle torch.Tensor input in compute_shape_offset#8812
williams145 wants to merge 4 commits intoProject-MONAI:devfrom
williams145:fix/issue-8775-compute-shape-offset-pytorch29

Conversation

@williams145
Copy link
Copy Markdown

Description

compute_shape_offset in monai/data/utils.py passes spatial_shape directly to np.array(). When spatial_shape is a torch.Tensor, this relies on the non-tuple sequence indexing protocol, which PyTorch removed in version 2.9. The call raises a hard error on PyTorch ≥ 2.9.

The fix is to wrap spatial_shape in tuple() before passing it to np.array(). This routes through __iter__, which is stable across all PyTorch versions, and produces 0-d scalar tensors that NumPy consumes correctly.

Root cause

The direct caller in monai/transforms/spatial/functional.py (line 115) constructs an in_spatial_size as a torch.Tensor and passes it straight to compute_shape_offset. This path has been broken since PyTorch 2.9.

Changes

  • monai/data/utils.py — one-character change: np.array(spatial_shape, ...)np.array(tuple(spatial_shape), ...)
  • tests/data/utils/test_compute_shape_offset.py: new unit tests covering torch.Tensor, np.ndarray, and plain list inputs

Fixes #8775

…fset

np.array(spatial_shape) fails with PyTorch >= 2.9 when spatial_shape is
a torch.Tensor, because PyTorch removed the non-tuple sequence indexing
protocol from tensors in that release.

Wrapping with tuple() first routes through __iter__, yielding scalar
0-d tensors that NumPy can consume via the scalar protocol. This makes
the function compatible with torch.Tensor, np.ndarray, and plain sequence
inputs alike.

The caller in monai/transforms/spatial/functional.py (line 115) already
passes a torch.Tensor, so this is a real-world breakage on PyTorch 2.9.

Signed-off-by: UGBOMEH OGOCHUKWU WILLIAMS <williamsugbomeh@gmail.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 9, 2026

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: b51a0e6f-7215-4fb3-8afb-62fc702071a4

📥 Commits

Reviewing files that changed from the base of the PR and between dfdb87d and da6c5a5.

📒 Files selected for processing (1)
  • tests/data/utils/test_compute_shape_offset.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/data/utils/test_compute_shape_offset.py

📝 Walkthrough

Walkthrough

The pull request updates test coverage for compute_shape_offset. It renames the test class from TestComputeShapeOffsetRegression to TestComputeShapeOffset, adds a shared fixture defining a 4×4 identity affine matrix, and introduces new test cases validating function behavior with NumPy arrays, Python lists, and PyTorch tensors as spatial_shape inputs. Tests assert output shape structure and verify numerical correctness when both input and output affines are identities using np.testing.assert_allclose with tolerance 1e-5.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Title accurately summarizes the main change: wrapping spatial_shape in tuple() to fix PyTorch 2.9+ compatibility in compute_shape_offset.
Description check ✅ Passed Description clearly explains root cause, solution, and changes. However, missing explicit checkbox selections for test additions and type of change declarations in the template.
Linked Issues check ✅ Passed PR addresses issue #8775 by wrapping spatial_shape in tuple() before np.array() and adding test coverage for torch.Tensor, list, and ndarray inputs as required.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing #8775: one-line code fix in monai/data/utils.py and expanded test coverage in test_compute_shape_offset.py.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ 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.

Copy link
Copy Markdown
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: 1

🧹 Nitpick comments (1)
tests/data/utils/test_compute_shape_offset.py (1)

24-45: Add docstrings for new test definitions.

setUp and the new test_* methods currently lack docstrings.

As per coding guidelines, "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."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/data/utils/test_compute_shape_offset.py` around lines 24 - 45, Add
Google-style docstrings to the test methods setUp, test_numpy_array_input,
test_list_input, test_torch_tensor_input, and
test_identity_affines_preserve_shape describing purpose, arguments (if any),
return (None), and any exceptions; for example, document that setUp initializes
self.affine, that each test calls compute_shape_offset with different shape
input types and asserts expected output length or values, and that no exceptions
are expected. Keep docstrings brief and placed immediately under each function
definition.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/data/utils/test_compute_shape_offset.py`:
- Around line 29-44: Tests in test_compute_shape_offset.py unpack
compute_shape_offset into (out_shape, offset) but never use offset, triggering
an unused variable lint warning; update the test cases (those calling
compute_shape_offset in test_list_input, test_torch_tensor_input,
test_identity_affines_preserve_shape and the earlier scalar input) to either
unpack as (out_shape, _) or explicitly assert offset when relevant so the unused
`offset` is removed — locate the calls to compute_shape_offset and change the
second variable name to `_` (or add a meaningful assert on `offset` where the
test intends to validate it).

---

Nitpick comments:
In `@tests/data/utils/test_compute_shape_offset.py`:
- Around line 24-45: Add Google-style docstrings to the test methods setUp,
test_numpy_array_input, test_list_input, test_torch_tensor_input, and
test_identity_affines_preserve_shape describing purpose, arguments (if any),
return (None), and any exceptions; for example, document that setUp initializes
self.affine, that each test calls compute_shape_offset with different shape
input types and asserts expected output length or values, and that no exceptions
are expected. Keep docstrings brief and placed immediately under each function
definition.
🪄 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: c0c7abd9-cf23-46e3-9fa1-2b7c49d4ed74

📥 Commits

Reviewing files that changed from the base of the PR and between 8d39519 and 33ebd0a.

📒 Files selected for processing (2)
  • monai/data/utils.py
  • tests/data/utils/test_compute_shape_offset.py

… unused variable

- Add Google-style docstrings to class and all test methods to satisfy
  docstring coverage CI check (was 16.67%, needed 80%)
- Replace unused `offset` variable with `_` in four test cases (RUF059)

Signed-off-by: UGBOMEH OGOCHUKWU WILLIAMS <williamsugbomeh@gmail.com>
@williams145
Copy link
Copy Markdown
Author

The quick-py3 (macOS-latest) failure is a pre-existing infrastructure issue, pytype 2024.4.11 fails to install on the macOS runner due to a missing pybind11 dependency, which is unrelated to the changes in this PR. The same failure appears on other open PRs against dev for the same reason.

@ericspod
Copy link
Copy Markdown
Member

ericspod commented Apr 9, 2026

Hi @williams145 thanks for this fix, this was already in the works in #8776 however. What I'd suggest is to merge that one first then merge in your extended test set which I think are good to add. We have to merge #8814 before this can be merged however which should address the pybind11 issue.

@williams145
Copy link
Copy Markdown
Author

Hi @williams145 thanks for this fix, this was already in the works in #8776 however. What I'd suggest is to merge that one first then merge in your extended test set which I think are good to add. We have to merge #8814 before this can be merged however which should address the pybind11 issue.

PR #8814 has been merged. The pybind11 blocker should now be resolved, this should mean that CI can be re-triggered when convenient.

Copy link
Copy Markdown

@atharvajoshi01 atharvajoshi01 left a comment

Choose a reason for hiding this comment

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

Converting to tuple before passing to np.array is a good fix for PyTorch >= 2.9 which deprecated non-tuple sequence indexing. Test coverage looks solid — covers numpy, list, tuple, and torch.Tensor inputs.

ericspod and others added 2 commits April 10, 2026 10:36
Signed-off-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.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.

[BUG] compute_shape_offset triggers PyTorch ≥2.9 breaking change for non-tuple sequence indexing

3 participants