Skip to content

Commit

Permalink
Fixed segfault when trying to permute empty tensor (pytorch#116335)
Browse files Browse the repository at this point in the history
Fixes pytorch#116325.

Fixed unchecked access to first element of `dims` when permuting an empty tensor. Added test to prevent regressions.

Pull Request resolved: pytorch#116335
Approved by: https://github.com/Skylion007
  • Loading branch information
tringwald authored and pytorchmergebot committed Dec 23, 2023
1 parent 015bd0e commit 3a4fe83
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
3 changes: 1 addition & 2 deletions aten/src/ATen/native/TensorShape.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1503,8 +1503,7 @@ Tensor permute_sparse_coo(const Tensor& self, IntArrayRef dims) {
}
return old_values.permute(values_perm);
}();

const auto is_coalesced = self.is_coalesced() && (dims[0] == 0);
const auto is_coalesced = self.is_coalesced() && (dims.empty() || dims[0] == 0);
// TODO: apply `is_coalesced ||= new_values.size(0) < 2`.
return _sparse_coo_tensor_with_dims_and_tensors(
sparse_ndim, dense_ndim, new_sizes, new_indices, new_values, self.options(), is_coalesced);
Expand Down
5 changes: 5 additions & 0 deletions test/test_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -952,6 +952,11 @@ def test_permute(self, device, dtype, coalesced, gradcheck):
s.permute(dims=(1, 0))
with self.assertRaisesRegex(RuntimeError, "duplicate dims"):
s.permute(dims=(1, 1, 1))
# Calling permute on a sparse tensor with an empty tuple used to segfault,
# see https://github.com/pytorch/pytorch/issues/116325
x = torch.rand((), device=device, dtype=dtype).to_sparse()
x.permute(())
self.assertEqual(len(x.values()), 1)

def test_shape(sparse_dims, nnz, with_size):
ndim = len(with_size)
Expand Down

0 comments on commit 3a4fe83

Please sign in to comment.