Fix tensor creation with empty names crash (#163957)

Partially fixes #148324

Pull Request resolved: https://github.com/pytorch/pytorch/pull/163957
Approved by: https://github.com/malfet, https://github.com/janeyx99
This commit is contained in:
arkadip-maitra
2025-09-26 17:40:55 +00:00
committed by PyTorch MergeBot
parent 9534c59311
commit d7491fb1c1
2 changed files with 6 additions and 1 deletions

View File

@ -280,6 +280,11 @@ class TestNamedTensor(TestCase):
self.assertEqual(named_tensor.diagonal(outdim='E', dim1='B', dim2='D').names,
['A', 'C', 'E'])
def test_empty_names(self):
ref_tensor = torch.tensor([[1, 2, 3, 4], [4, 3, 2, 1]])
empty_named_tensor = torch.tensor([[1, 2, 3, 4], [4, 3, 2, 1]], names=[])
self.assertEqual(ref_tensor, empty_named_tensor)
def test_max_pooling(self):
def check_tuple_return(op, inputs, expected_names):
values, indices = op(*inputs)

View File

@ -1497,7 +1497,7 @@ Tensor tensor_ctor(
pin_memory);
auto names = r.toDimnameListOptional(5);
if (names) {
at::namedinference::propagate_names(
at::namedinference::propagate_names_if_nonempty(
new_tensor, *names, /*validate_names=*/true);
}
new_tensor.detach_(); // ensure new_tensor a leaf node