Skip to content

fix(MetaTensor): astype with torch dtype now returns MetaTensor preserving metadata#8911

Open
AlexanderSanin wants to merge 1 commit into
Project-MONAI:devfrom
AlexanderSanin:fix/metatensor-astype-preserve-type-v2
Open

fix(MetaTensor): astype with torch dtype now returns MetaTensor preserving metadata#8911
AlexanderSanin wants to merge 1 commit into
Project-MONAI:devfrom
AlexanderSanin:fix/metatensor-astype-preserve-type-v2

Conversation

@AlexanderSanin

Copy link
Copy Markdown
Contributor

Summary

  • MetaTensor.astype() called with a torch dtype (e.g. torch.int32, torch.float16) was silently returning a plain torch.Tensor, discarding all metadata (affine matrix, spacing, applied_operations, and any custom keys).
  • Root cause: out_type was hardcoded to torch.Tensor instead of type(self) (MetaTensor), so convert_data_type set track_meta=False and stripped the metadata.
  • Fix: use out_type = type(self) when mod_str == "torch", so convert_data_type receives output_type=MetaTensor, sets track_meta=True, and the dtype cast is performed while preserving all metadata.
  • The auto3dseg/analyzer.py module already annotated label_tensor.astype(torch.int16) as returning a MetaTensor (line 493), relying on this contract.

Closes #8202

Test plan

  • Existing test_astype test updated to assert isinstance(result, MetaTensor) and that metadata keys survive the cast.
  • All 96 tests/data/meta_tensor/ tests pass locally (0 failures).
  • Manual verification:
import torch
from monai.data import MetaTensor

t = MetaTensor(torch.tensor([1., 2., 3.]), meta={"fname": "scan.nii"})
result = t.astype(torch.int32)
assert isinstance(result, MetaTensor)          # was torch.Tensor before
assert result.meta["fname"] == "scan.nii"      # metadata preserved
assert result.dtype == torch.int32             # dtype correctly cast

@AlexanderSanin

Copy link
Copy Markdown
Contributor Author

Hey @ericspod @garciadias. Could you, please, have a look at this?

@coderabbitai

coderabbitai Bot commented Jun 10, 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: 9c36c85c-af20-415a-bfd3-9ae90c1b4f3b

📥 Commits

Reviewing files that changed from the base of the PR and between eccefc5 and deba0f1.

📒 Files selected for processing (2)
  • monai/data/meta_tensor.py
  • tests/data/meta_tensor/test_meta_tensor.py

📝 Walkthrough

Walkthrough

The PR updates MetaTensor.astype() to preserve the MetaTensor subclass when casting to PyTorch dtypes. Previously, the method returned a plain torch.Tensor, losing metadata. The implementation now uses type(self) instead of torch.Tensor as the output type for torch dtype casts. The docstring clarifies the return behavior: torch dtypes return MetaTensor with metadata preserved, while numpy dtypes return np.ndarray. Test assertions were updated to verify the MetaTensor return type and metadata preservation across PyTorch dtype casts.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 The title directly and clearly describes the main change: MetaTensor.astype() with torch dtypes now returns MetaTensor while preserving metadata.
Description check ✅ Passed The description covers the bug, root cause, fix, and includes test details and manual verification examples. All key template sections are addressed.
Linked Issues check ✅ Passed The PR addresses issue #8202 by making MetaTensor.astype() return MetaTensor instead of plain torch.Tensor, preserving metadata as expected [#8202].
Out of Scope Changes check ✅ Passed All changes are scoped to fixing MetaTensor.astype() behavior and updating tests; no unrelated modifications detected.

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

…rving metadata

When calling MetaTensor.astype() with a torch dtype (e.g. torch.int32),
the result was a plain torch.Tensor, silently losing all metadata (affine,
spacing, applied transforms, etc.). The root cause was that out_type was
hardcoded to torch.Tensor instead of the actual type of self.

Fix by using type(self) as out_type when a torch dtype is requested, so
that convert_data_type() receives output_type=MetaTensor, sets
track_meta=True, and preserves metadata through the dtype cast.

The analyzer module already annotated the result of astype(torch.int16)
as MetaTensor, relying on this contract.

Updated test to assert the result is an instance of MetaTensor and that
the metadata key is preserved after the cast.

Closes Project-MONAI#8202

Signed-off-by: Oleksandr Sanin <alexaaander.sanin@gmail.com>
@AlexanderSanin AlexanderSanin force-pushed the fix/metatensor-astype-preserve-type-v2 branch from cc01db4 to deba0f1 Compare June 10, 2026 09:21
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.

Metatensor method astype can't into metatensor

2 participants