Skip to content

[WIP] Sparse GCS layout implementation and sparse matrix multiplication. - #44190

Closed
v0dro wants to merge 149 commits into
pytorch:masterfrom
v0dro:sparse-csr-layout
Closed

v0dro wants to merge 149 commits into
pytorch:masterfrom
v0dro:sparse-csr-layout

Conversation

@v0dro

@v0dro v0dro commented Sep 4, 2020 •

Copy link
Copy Markdown
Contributor

Introduction

This PR introduces the GCS format for efficient storage and operations on multi-dimensional
tensors. The GCS format is special in that it drops down to the usual CSR format for 2D
tensors and supports multi-dimensional data using the same data structures used by CSR but
with a slightly augmented indexing scheme. While ready to be reviewed, the architecture and naming
scheme is still up for consideration, and it would be great if people familiar with sparse tensor support
in pytorch could have a look at the various changes that are being introduced as a result of this PR.

The GCS format is a N-D sparse array storage format that allows storing a sparse tensor using 3 1-D tensors. It is similar to the CSR format in terms of storage. What makes it particularly attractive over the current COO implementation is that 2-D tensors fall back to the traditional CSR format, which has been the preferred choice for fast SpMM and SpMV computation due to fast slicing operations and readily available support from various libraries such as MAGMA, MKL and cuSPARSE.

A detailed description of the GCS format implemented here can be found here: https://github.com/Quansight-Labs/rfcs/tree/pearu/rfc0005/RFC0003-sparse-roadmap

In particular, I have made the following additions:

  • Added a new layout type torch.sparse_gcs.
  • Added a constructor torch.sparse_gcs_tensor().
  • Added a Python-only function for conversion of dense Tensors to GCS tensor.
  • Added a new struct SparseGCSTensorImpl for implementing the special methods needed for this tensor type. Inherits from TensorImpl similar to SparseTensorImpl.

CUDA support will be added once the CPU changes are approved and merged. That way there will be a firm foundation to build the CUDA functionality upon.

Support for SpMV (with benchmarks)

It can support all the operations supported by COO, and is faster for many critical operations
such as SpMV and SpMM for 2D tensors. The graphs below show the performance using of SpMV
with and without MKL's CSR SpMV routines compared to the default COO implementation for a
variety of matrix and NNZ ratios.

Details

spmv-nnz-0 3
spmv-nnz-0 1
spmv-nnz-0 05
spmv-nnz-0 01

The following script was used for benchmarking the COO and GCS format SpMV:

Details
def test_sparse_gcs(m, nnz, test_count):
    start_timer = Event(enable_timing=True)
    stop_timer = Event(enable_timing=True)

    gcs = gen_sparse_gcs((m, m), nnz)
    vector = torch.randn(m, dtype=torch.double)

    times = []
    for _ in range(test_count):
        start_timer.record()
        gcs.matmul(vector)
        stop_timer.record()
        times.append(start_timer.elapsed_time(stop_timer))

    return sum(times) / len(times)

def test_sparse_coo(m, nnz, test_count):
    start_timer = Event(enable_timing=True)
    stop_timer = Event(enable_timing=True)

    coo = gen_sparse_coo((m, m), nnz)
    vector = torch.randn(m, dtype=torch.double)

    times = []
    for _ in range(test_count):
        start_timer.record()
        coo.matmul(vector)
        stop_timer.record()
        times.append(start_timer.elapsed_time(stop_timer))

    return sum(times) / len(times)  

Support for SpMM (with benchmarks)

The GCS also supports with dense matrices with and without using MKL. The performance vs. COO can be seen in the following
graphs:

Details

spmm-nnz-0 3
spmm-nnz-0 1
spmm-nnz-0 05
spmm-nnz-0 01

The following functions were used for obtaining the above data:

Details
def test_sparse_gcs(m, n, k, nnz, test_count):
    start_timer = Event(enable_timing=True)
    stop_timer = Event(enable_timing=True)

    gcs = gen_sparse_gcs((m, k), nnz)
    mat = torch.randn(k, n, dtype=torch.double)

    times = []
    for _ in range(test_count):
        start_timer.record()
        gcs.matmul(mat)
        stop_timer.record()
        times.append(start_timer.elapsed_time(stop_timer))

    return sum(times) / len(times)

def test_sparse_coo(m, n, k, nnz, test_count):
    start_timer = Event(enable_timing=True)
    stop_timer = Event(enable_timing=True)

    coo = gen_sparse_coo((m, k), nnz)
    mat = torch.randn(k, n, dtype=torch.double)

    times = []
    for _ in range(test_count):
        start_timer.record()
        coo.matmul(mat)
        stop_timer.record()
        times.append(start_timer.elapsed_time(stop_timer))

    return sum(times) / len(times)    

Support for fill values

The fill value is an important idea being introduced into the sparse COO format by Pearu and
the others, and the GCS format is ready for implementing various functions using the fill value
since it already supports creating the tensor by accepting a fill value.

Conclusion

The PR contains the following features:

  • Implementation of the GCS format for multi-dimensional tensor storage.
  • Pure python conversion function to convert a multi-dim (dense) strided tensor into GCS.
  • SpMV and SpMM implementation with and without using MKL for GCS for float and double.
  • Benchmarks comparing performance of SpMV and SpMM with current COO format implementation.

Note that multiplication only with dense matrix is supported for now.

In order to proceed with the implementation, I think it is important to finalize the code
structure of the constructor and other implementation details pertinent to GCS and only
then proceed with implementation of various operators. In that regard, IMO we should
first merge this PR and therefore would like to invite comments from @rgommers @pearu @ezyang @aocsa .

Particular RFC requests

  1. Currently the COO sparse matrix class is called SparseTensorImpl (same as master) and the GCS is called SparseGCSTensorImpl. Should the COO class be changed to SparseCOOTensorImpl?
  2. Both these classes inherit from TensorImpl separately. Should there be a common SparseTensorImpl class that sits between SparseCOOTensorImpl and SparseGCSTensorImpl? This way we can also add more sparse layouts in the future.
  3. Many C++ functions such as those in SparseTensorUtils.h are not guaranteed to work with GCS tensors. Should we have templated variants of each of these functions for such support? It can be added on a as-needed basis.
  4. The COO linear algebra functions exist in SparseTensorMath.cpp however I have made a departure from that and made them available inside sparse/LinearAlgebra.cpp for better discoverability (has only matmul for now). Might I suggest a similar approach for all the other functions?
  5. COO currently does not have an MKL backend. It would be interesting to see COO vs. GCS MKL performance. Maybe in a later PR?
  6. The dispatch key for COO tensor is currently SparseCPU for CPU and SparseCUDA for CUDA. How about change it to SparseCOO_CPU and similar for CUDA?
  7. How do we best write the documentation so as to convey information about the GCS format (which is not very well known outside of N-D tensor users) to the general public?


auto reduction_accessor = reduction_.accessor<int32_t, 1>();

rsplit_dim_ = reduction_accessor[reduction_.size(0)-1];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this isn't going to work on CUDA (also I still have no idea what reduction is)

@ezyang

ezyang commented Dec 7, 2020

Copy link
Copy Markdown
Contributor

I'm looking for a description of GCS format in https://github.com/Quansight-Labs/rfcs/tree/pearu/rfc0005/RFC0003-sparse-roadmap but I cannot find it. For example, I search the README for "GCS" but I don't see any occurrence of this term anywhere in the README. I see there is a file https://github.com/Quansight-Labs/rfcs/blob/pearu/rfc0005/RFC0003-sparse-roadmap/GCS_index_inconversion.md but it seems to be a very specific subproblem of solving the GCS format and I am looking for a more generic description of GCS.

Comment thread aten/src/ATen/SparseGCSTensorImpl.cpp Resolved
@ezyang

ezyang commented Dec 10, 2020

Copy link
Copy Markdown
Contributor

I think it's Efficient storage scheme for n-dimensional sparse array: GCRS/GCCS.

Huh, this has way less citations than I thought it would. https://scholar.google.com/scholar?cites=14217487981794327056&as_sdt=2005&sciodt=0,5&hl=en That's weird...

Comment thread torch/_tensor_docs.py
reduction() -> Tensor

Tensor which shows the demarcation between dimensions that will be
flattened from the N-D tensor.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This isn't enough description.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For example, what is the dimensionality/size of this tensor, depending on the size of the sparse tensor? How exactly is the "Demarcation" represented? An example?

@v0dro

v0dro commented Dec 18, 2020 •

Copy link
Copy Markdown
Contributor Author

@ezyang based on your reviews, I am thinking of making the following changes to this PR:

  1. Forget about namespaces for now and only focus on getting the GCS to work. The dispatch keys and class names for COO remain exactly as they were before.
  2. Fix documentation and work with @pearu to integrate his introduction to GCS document into this PR.
  3. FIx smaller tiny-gritties that you pointed out, such as changing the GCS dispatch key name.

One question about the indices being int and not int64_t: pytorch links with MKL LP64 by default, which means that the indexing within MKL is 32 bit. Would you advise whether we can change to MKL ILP64 so that all the indexing in GCS can uniformly use 64 bit integers without any problems with MKL interfacing?

@ezyang

ezyang commented Dec 18, 2020

Copy link
Copy Markdown
Contributor

One question about the indices being int and not int64_t: pytorch links with MKL LP64 by default, which means that the indexing within MKL is 32 bit. Would you advise whether we can change to MKL ILP64 so that all the indexing in GCS can uniformly use 64 bit integers without any problems with MKL interfacing?

I don't know. While it is true we typically prefer to expose 64-bit indexing on the user side (e.g., torch.gather), swapping out the MKL version can have far reaching implications on PyTorch and (1) isn't obviously the right thing outside of the sparse project, and (2) is likely to require a bit of work to update all other MKL bindings.

@v0dro
v0dro marked this pull request as draft January 7, 2021 05:52
@ezyang

ezyang commented Jan 19, 2021

Copy link
Copy Markdown
Contributor

let me know when to look at the PR again

@facebook-github-bot

Copy link
Copy Markdown
Contributor

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Facebook open source project. Thanks!

@v0dro v0dro closed this Mar 14, 2021
facebook-github-bot pushed a commit that referenced this pull request Apr 12, 2021
Summary:
Implement compressed sparse row format. Derived from the GCS implementation at #44190

Pull Request resolved: #50937

Reviewed By: mrshenli

Differential Revision: D27439865

Pulled By: ezyang

fbshipit-source-id: 3ba3dcb9679505b980ff6a5f513e913bbae2fb1d
krshrimali pushed a commit to krshrimali/pytorch that referenced this pull request May 19, 2021
)

Summary:
Implement compressed sparse row format. Derived from the GCS implementation at pytorch#44190

Pull Request resolved: pytorch#50937

Reviewed By: mrshenli

Differential Revision: D27439865

Pulled By: ezyang

fbshipit-source-id: 3ba3dcb9679505b980ff6a5f513e913bbae2fb1d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants