Skip to content

RFC-0002: Proposed Roadmap for torch.sparse matrix multiplication - #4

Closed
dhavide wants to merge 13 commits into
pytorch:masterfrom
dhavide:master
Closed

dhavide wants to merge 13 commits into
pytorch:masterfrom
dhavide:master

Conversation

@dhavide

@dhavide dhavide commented Apr 8, 2020

Copy link
Copy Markdown

Suggestions for a strategy on how to go forward with torch.sparse

  • This doc discusses only matrix multiplication (because it is mentioned in many issues)
  • The goal is to start here as a way to go deeper into other issues associated with torch.sparse.

@rgommers
rgommers requested review from ezyang and pearu April 8, 2020 20:01
@ezyang

ezyang commented Apr 9, 2020

Copy link
Copy Markdown
Contributor

One very basic newbie question: is there a generalization of CSR format that works for higher dimensions? Or is it a 2D only kind of deal?

@gchanan

gchanan commented Apr 9, 2020

Copy link
Copy Markdown

I did a quick read, thanks for the thorough writeup!

Some questions that come to mind:

  1. Can the csr format be generalized to more than just 2-d tensors? Having "2d" in all the names feels pretty clunky and we could just error out if the input matrix is not 2d if it's not generalizable.
  2. I'd like to see more detail on the constructor(s). The conversion operator IMO doesn't really matter because it's mostly used in tests (most uses for sparse tensors you wouldn't want to materialize the dense tensor anyway).

@hameerabbasi

Copy link
Copy Markdown
Contributor

One very basic newbie question: is there a generalization of CSR format that works for higher dimensions? Or is it a 2D only kind of deal?

There is GCRS (https://ieeexplore.ieee.org/document/7237032) and CSF (https://dl.acm.org/doi/10.1145/2833179.2833183). If you want to go completely-bonkers-general-all-formats-are-one there's TACO (https://arxiv.org/abs/1804.10112).

@albanD

albanD commented Apr 9, 2020

Copy link
Copy Markdown
Contributor

Hi,

Thanks for the proposal.
I would have one question about the timeline.
I assume that this new Tensor type will have .is_sparse() == true. But how is it going to interact with code that already exists and use this to special case on the COO sparse Tensors we have?
For example here https://github.com/pytorch/pytorch/blob/5bbcddae3bfb7abaeaada29369c6ed5964d390fe/torch/csrc/autograd/functions/accumulate_grad.h#L61-L68 we assume that when we have a sparse Tensor, then we can access _values and _indices. But this might not be true anymore.
Should a new point be added to the timeline to investigate the current codebase and make sure all the special casing we do for sparse Tensors will be ok for all sparse Tensors?

@dhavide

dhavide commented Apr 9, 2020

Copy link
Copy Markdown
Author

I did a quick read, thanks for the thorough writeup!

Some questions that come to mind:

1. Can the csr format be generalized to more than just 2-d tensors?  Having "2d" in all the names feels pretty clunky and we could just error out if the input matrix is not 2d if it's not generalizable.

2. I'd like to see more detail on the constructor(s). The conversion operator IMO doesn't really matter because it's mostly used in tests (most uses for sparse tensors you wouldn't want to materialize the dense tensor anyway).
  1. As Hameer points out, there are generalizations beyond 2D. We actually do need to consider this
    because there are use cases (e.g., NLP) in which storing batches of sparse matrices is useful.
    The precise implementation of this is quite complicated and needs to be considered carefully.
    We can modify the proposal to make this more explicit.

    Anyway, it's fine with to change the identifiers (someone else has already winced at the 2d
    suffix for the modifications to the API). The primary motivation was to serve as a warning of a
    restriction, but that restriction may not exist in the eventual implementation.

  2. More details about the constructor is a good idea. We'll modify the proposal accordingly.

@dhavide

dhavide commented Apr 9, 2020

Copy link
Copy Markdown
Author

Hi,

Thanks for the proposal.
I would have one question about the timeline.
I assume that this new Tensor type will have .is_sparse() == true. But how is it going to interact with code that already exists and use this to special case on the COO sparse Tensors we have?
For example here https://github.com/pytorch/pytorch/blob/5bbcddae3bfb7abaeaada29369c6ed5964d390fe/torch/csrc/autograd/functions/accumulate_grad.h#L61-L68 we assume that when we have a sparse Tensor, then we can access _values and _indices. But this might not be true anymore.
Should a new point be added to the timeline to investigate the current codebase and make sure all the special casing we do for sparse Tensors will be ok for all sparse Tensors?

Excellent point. Yes, this has the potential to break existing parts of the codebase, so an additional point needs to be added to the timeline to verify this (concerns about autograd are mentioned in passing in the current draft, but this certainly needs to be called out explicitly in the timeline).

Comment thread PyTorch-Sparse-Roadmap.md Resolved
Comment thread PyTorch-Sparse-Roadmap.md Resolved
@rgommers

Copy link
Copy Markdown
Contributor

One very basic newbie question: is there a generalization of CSR format that works for higher dimensions? Or is it a 2D only kind of deal?

There is GCRS (https://ieeexplore.ieee.org/document/7237032) and CSF (https://dl.acm.org/doi/10.1145/2833179.2833183). If you want to go completely-bonkers-general-all-formats-are-one there's TACO (https://arxiv.org/abs/1804.10112).

Important disclaimer there is that those >2-D generalizations are not supported by cuSPARSE, MKL et al. CSR is the best-supported format by those libraries, followed by COO. So it's unclear to me whether it makes sense to have more than one >2-D format.

@pearu pearu left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall LGTM. Added some suggestions and questions regarding CSR implementation details.

Comment thread PyTorch-Sparse-Roadmap.md Resolved
Comment thread PyTorch-Sparse-Roadmap.md Resolved
Comment thread PyTorch-Sparse-Roadmap.md Resolved
@ezyang

ezyang commented Apr 14, 2020

Copy link
Copy Markdown
Contributor

I think we've already gotten here in the convo, but just to state it explicitly: if csr unambiguously refers to 2d only, we don't need to qualify the name with 2d; and we don't have to work on generalized versions if it's not clear, 2d only is fine.

@albanD

albanD commented Apr 14, 2020

Copy link
Copy Markdown
Contributor

Wouldn't a batch of sparse matrix be an important usecase as well?
For nn use, have only 2D Tensors will be quite limited.

@dzhulgakov

Copy link
Copy Markdown

This is great proposal! Interesting thought: CSR is effectively equivalent to offsets representation that embedding_bag and other operations use. So it'd be good to explore whether we can change APIs there too to accept sparse tensors.

I'd also vote for extending representation to >2 dimensions if possible (or at least not baking it in API names now). Batch use case Alban mentioned is one example. Another point is that several embedding_bags' input can be thought as sparse 3d tensor (e.g. batch X num_features X feature_dim for sparse features). So it might be interesting to explore whether sparse tensor api is a good representation for it.

@dhavide

dhavide commented Apr 20, 2020

Copy link
Copy Markdown
Author

Wouldn't a batch of sparse matrix be an important usecase as well?
For nn use, have only 2D Tensors will be quite limited.

@albanD yes, batches of sparse matrices is obviously important. I have modified the proposal to describe how CSR extends to tensors of arbitrary rank (and added references to papers that describe other extensions in greater detail). I believe this category of generalization is sufficient (even if the indexing sparse dimension in RO is always the leading dimension).

@pearu

pearu commented Apr 23, 2020

Copy link
Copy Markdown

@dhavide could you also rename PyTorch-Sparse-Roadmap.md to PyTorch-Sparse-MatMul-Roadmap.md, or similar?

@jamestwebber

Copy link
Copy Markdown

@rgommers pointed me here from the CuPy issue–glad to see progress being made! To add some comments from an end-user (domain is computational biology).

The big assumption is that faster sparse matrix products actually constitutes a meaningful benefit to PyTorch users—the hope is that the accuracy of this assumption will become clear in the early stages of prototyping.

I think this would have a major benefit in my area of research. I work a lot with single-cell RNA sequencing data (scRNAseq), and the raw data is a large, sparse count matrix. By "large": on the order of 10k rows for one experiment, easily 100k to 1M+ for very large projects or meta-analyses, and 10s of thousands of features. By "sparse": typically 1-2% nonzero values. Not "big data" so much as wide, complex data. This type of data is becoming more prevalent and datasets are growing as methods improve, see this google sheet showing the trend over time (credit to @vals who might drop in later).

When analyzing scRNA data, the difference between sparse and dense representations can be the difference between fitting the data in GPU memory or not, which can greatly impact the speed of training. The rest of the model could be dense but just using sparse tensors for the input would allow for larger batches and less memory-copying. It's hard to know exactly how big a benefit that would provide but I think it'd be considerable.

One thing I would add as something to think about (but out of scope here, I guess): I'd love to be able to pass a sparse tensor in to torch.distributions. For example, call torch.distributions.Binomial(total_counts=sparse_counts, p=0.5).sample() and get a sparse tensor with the same shape and sampled counts in the nonzero locations.

That's kind of a niche thing to do but it might be doable with the fill_value attribute, for distributions where certain values have a trivial answer. My hunch is that most users want sparse tensors to be a drop-in replacement as much as possible, because trying to keep track of the options gets difficult (I always have this issue with scipy, where the sparse datatype is always a matrix, not an array).

@pearu pearu left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dhavide , there are a couple for bugs in the CSR format description.

Could you also rename RFC-0004 to RFC-0002 according to the revised numbering convention of proposals?

@pearu pearu changed the title Proposed Roadmap for torch.sparse matrix multiplication RFC-0002: Proposed Roadmap for torch.sparse matrix multiplication May 30, 2020

@pearu pearu left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The proposed CSR construction API is incorrect (RO and CO have different lengths and hence cannot be collected in single indices tensor) and proposed a fix.

I also suggest implementing arbitrary rank CSR construction function as it will be no different from the rank 2 case. However, the implementations of algorithms may restrict to supporting only rank 2 cases in short term.

Comment on lines +325 to +332
```{python}
sparse_csr_tensor(indices, values, size=None, dtype=None,
device=None, requires_grad=False) -> Tensor
```

where `indices` would be a list of two lists (e.g., `RO` & `CO`
from the description of CSR format above) and `values` would be a tensor
containing the corresponding (presumably) nonzero entries of the sparse

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This API for CSR is incorrect/inefficient: RO has a length size[0]+1 while CO has length nnz and so RO and CO lists should be separated.

I suggest the following API for sparse_csr_tensor:

sparse_csr_tensor(pointers, indices, values, size=None, dtype=None,
                  device=None, requires_grad=False)       -> Tensor

where the pointers argument is a 1-D array of length size[0] + 1 containing the cumulative number of nonzero elements in the sparse array computed for each index of the first sparse dimension.

Xref: https://github.com/Quansight/pearu-issues/issues/28


2. Construct and test a prototype implementation of conversion functions
`torch.to_sparse_csr` and `torch.to_sparse_coo` to convert sparse PyTorch
tensors of sparse rank 2 between COO and CSR formats.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can target immediately arbitrary rank (>=2) CSR sparse tensors in the constructor, including the hybrid feature, without any extra effort. The algorithms, however, may be restricted to 2-D in the short run.

@npuichigo

Copy link
Copy Markdown

So will block sparse be supported as some people ask for that maybe for sparse attention? (pytorch/pytorch#9222)

@rgommers

rgommers commented Jan 4, 2021

Copy link
Copy Markdown
Contributor

Thanks for asking @npuichigo. We've discussed it briefly recently and it's clearly of interest. The first target for increasing sparse matrix performance at the moment is the GCS format: pytorch/pytorch#44190. Considering the block sparse use cases and interest in pytorch/pytorch#9222, it does seem like that's a good next candidate. I'll add a note to the tracking issue for sparse tensor improvements (pytorch/pytorch#44634) to reassess the priority of block-sparse.

This pull request was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.