torch icon indicating copy to clipboard operation
torch copied to clipboard

feat: as_array() for sparse matrices

Open JosiahParry opened this issue 2 months ago • 1 comments

It would be great if sparse tensors could be returned to R as a matrix or a dcgSparseMatrix

library(torch)

n_nodes <- 3
i <- c(1, 1, 2, 2, 3, 3)
j <- c(2, 3, 1, 3, 1, 2)

# Create sparse adjacency matrix
indices <- torch::torch_tensor(
  rbind(i, j),
  dtype = torch::torch_int64()
)

values <- torch::torch_ones(6)

adj <- torch::torch_sparse_coo_tensor(
  indices,
  values,
  c(n_nodes, n_nodes)
)$coalesce()

# error here
as_array(adj)

One way this could be accomplished would be like so:

idx <- adj$indices() + 1L
vals <- adj$values()

Matrix::sparseMatrix(
  as_array(idx[1,]),
  as_array(idx[2,]),
  x = as_array(vals)
)

JosiahParry avatar Nov 13 '25 18:11 JosiahParry

I think this would be nice, but I'm not sure how to deal with sparse mutidimensional tensors with length(dim) > 2. Treating 2D tensors specially can cause problems for more generic code, so I'd be inclined into implementing as_sparse_matrix() instead.

as_array() failing by default on sparse tensors may be useful to avoid materializing large arrays too.

dfalbel avatar Nov 27 '25 12:11 dfalbel