fix(MetaTensor): astype with torch dtype now returns MetaTensor preserving metadata#8911
Conversation
|
Hey @ericspod @garciadias. Could you, please, have a look at this? |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThe PR updates Estimated code review effort🎯 1 (Trivial) | ⏱️ ~5 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 |
…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>
cc01db4 to
deba0f1
Compare
Summary
MetaTensor.astype()called with a torch dtype (e.g.torch.int32,torch.float16) was silently returning a plaintorch.Tensor, discarding all metadata (affine matrix, spacing, applied_operations, and any custom keys).out_typewas hardcoded totorch.Tensorinstead oftype(self)(MetaTensor), soconvert_data_typesettrack_meta=Falseand stripped the metadata.out_type = type(self)whenmod_str == "torch", soconvert_data_typereceivesoutput_type=MetaTensor, setstrack_meta=True, and the dtype cast is performed while preserving all metadata.auto3dseg/analyzer.pymodule already annotatedlabel_tensor.astype(torch.int16)as returning aMetaTensor(line 493), relying on this contract.Closes #8202
Test plan
test_astypetest updated to assertisinstance(result, MetaTensor)and that metadata keys survive the cast.tests/data/meta_tensor/tests pass locally (0 failures).