This should have a library function to handle this, but here’s how you can do it:
dense = torch.randn(3,3)
dense[[0,0,1], [1,2,0]] = 0 # make sparse
indices = torch.nonzero(dense).t()
values = dense[indices[0], indices[1]] # modify this based on dimensionality
torch.sparse.FloatTensor(indices, values, dense.size())