Skip to content

Permutation of Sparse Tensor #78422

@ignaciogavier

Description

@ignaciogavier

🚀 The feature, motivation and pitch

I'm working with COO sparse tensors and would like to get a permutation of any COO sparse tensor.
In the current version, torch.permute throws the following error:
RuntimeError: sparse tensors do not have strides
Also, in-place modification of indices is not possible.

Alternatives

I have considered the following solution (it wouldn't be the same as torch.permute since this one returns a view of the original tensor):

torch.permute_sparse(input, dims) → Tensor
Returns a copy of the original tensor input with its dimensions permuted.

  • input (Tensor) – the input tensor.
  • dims (tuple of python:ints) – The desired ordering of dimensions

The source code:

def permute_sparse(input, dims):
    dims = torch.LongTensor(dims)
    return torch.sparse_coo_tensor(indices=input._indices()[dims], values=input._values(), size=torch.Size(torch.tensor(input.size())[dims]))

An example:

>>> indices = torch.tensor([[1, 1],
                            [2, 1],
                            [1, 0],
                            [3, 3]])
>>> values = torch.tensor([ 1, -1])
>>> s = torch.sparse_coo_tensor(indices=indices, values=values, size=(2, 3, 4, 5))
>>> s.size()
torch.Size([2, 3, 4, 5])
>>> permute_sparse(s, (3, 2, 0, 1)).size()
torch.Size([5, 4, 2, 3])

Additional context

No response

cc @nikitaved @pearu @cpuhrsch @amjames

Metadata

Metadata

Assignees

No one assigned

    Labels

    module: sparseRelated to torch.sparsetriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions