Commit 8690ae7
fix(MetaTensor): astype with torch dtype now returns MetaTensor preserving metadata (#8911)
## 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:
```python
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
```
Signed-off-by: Oleksandr Sanin <alexaaander.sanin@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>1 parent ed76cd5 commit 8690ae7
2 files changed
Lines changed: 9 additions & 4 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
495 | 495 | | |
496 | 496 | | |
497 | 497 | | |
498 | | - | |
| 498 | + | |
| 499 | + | |
499 | 500 | | |
500 | 501 | | |
501 | 502 | | |
| |||
506 | 507 | | |
507 | 508 | | |
508 | 509 | | |
509 | | - | |
| 510 | + | |
510 | 511 | | |
511 | 512 | | |
512 | 513 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
435 | 435 | | |
436 | 436 | | |
437 | 437 | | |
438 | | - | |
439 | | - | |
| 438 | + | |
| 439 | + | |
| 440 | + | |
| 441 | + | |
| 442 | + | |
| 443 | + | |
440 | 444 | | |
441 | 445 | | |
442 | 446 | | |
| |||
0 commit comments