By default, PyTorch stores torch.Tensor elements contiguously in
physical memory. This leads to efficient implementations of various array
processing algorithms that require fast access to elements.
Now, some users might decide to represent data such as graph adjacency
matrices, pruned weights or points clouds by Tensors whose elements are
mostly zero valued. We recognize these are important applications and aim
to provide performance optimizations for these use cases via sparse storage formats.
Various sparse storage formats such as COO, CSR/CSC, semi-structured, LIL, etc. have been
developed over the years. While they differ in exact layouts, they all
compress data through efficient representation of zero valued elements.
We call the uncompressed values specified in contrast to unspecified,
compressed elements.
By compressing repeat zeros sparse storage formats aim to save memory
and computational resources on various CPUs and GPUs. Especially for high
degrees of sparsity or highly structured sparsity this can have significant
performance implications. As such sparse storage formats can be seen as a
performance optimization.
Like many other performance optimization sparse storage formats are not
always advantageous. When trying sparse formats for your use case
you might find your execution time to increase rather than decrease.
Please feel encouraged to open a GitHub issue if you analytically
expected to see a stark increase in performance but measured a
degradation instead. This helps us prioritize the implementation
of efficient kernels and wider performance optimizations.
We make it easy to try different sparsity layouts, and convert between them,
without being opinionated on what’s best for your particular application.
Functionality overview
We want it to be straightforward to construct a sparse Tensor from a
given dense Tensor by providing conversion routines for each layout.
In the next example we convert a 2D Tensor with default dense (strided)
layout to a 2D Tensor backed by the COO memory layout. Only values and
indices of non-zero elements are stored in this case.
We also have a prototype implementation to support semi-structured sparsity.
Please see the references for more details.
Note that we provide slight generalizations of these formats.
Batching: Devices such as GPUs require batching for optimal performance and
thus we support batch dimensions.
We currently offer a very simple version of batching where each component of a sparse format
itself is batched. This also requires the same number of specified elements per batch entry.
In this example we construct a 3D (batched) CSR Tensor from a 3D dense Tensor.
>>> t = torch.tensor([[[1.,0],[2.,3.]],[[4.,0],[5.,6.]]])>>> t.dim()3>>> t.
Dense dimensions: On the other hand, some data such as Graph embeddings might be
better viewed as sparse collections of vectors instead of scalars.
In this example we create a 3D Hybrid COO Tensor with 2 sparse and 1 dense dimension
from a 3D strided Tensor. If an entire row in the 3D strided Tensor is zero, it is
not stored. If however any of the values in the row are non-zero, they are stored
entirely. This reduces the number of indices since we need one index one per row instead
of one per element. But it also increases the amount of storage for the values. Since
only rows that are entirely zero can be emitted and the presence of any non-zero
valued elements cause the entire row to be stored.
>>> t = torch.tensor([[[0.,0],[1.,2.]],[[0.,0],[3.,4.]]])>>> t.to_sparse(sparse_dim=2)tensor(indices=tensor([[0, 1],
Operator overview
Fundamentally, operations on Tensor with sparse storage formats behave the same as
operations on Tensor with strided (or other) storage formats. The particularities of
storage, that is the physical layout of the data, influences the performance of
an operation but should not influence the semantics.
We are actively increasing operator coverage for sparse tensors. Users should not
expect support same level of support as for dense Tensors yet.
See our operator documentation for a list.
As shown in the example above, we don’t support non-zero preserving unary
operators such as cos. The output of a non-zero preserving unary operation
will not be able to take advantage of sparse storage formats to the same
extent as the input and potentially result in a catastrophic increase in memory.
We instead rely on the user to explicitly convert to a dense Tensor first and
then run the operation.
We are aware that some users want to ignore compressed zeros for operations such
as cos instead of preserving the exact semantics of the operation. For this we
can point to torch.masked and its MaskedTensor, which is in turn also backed and
powered by sparse storage formats and kernels.
Also note that, for now, the user doesn’t have a choice of the output layout. For example,
adding a sparse Tensor to a regular strided Tensor results in a strided Tensor. Some
users might prefer for this to stay a sparse layout, because they know the result will
still be sufficiently sparse.
>>> a + b.to_sparse()tensor([[0., 3.], [3., 0.]])
We acknowledge that access to kernels that can efficiently produce different output
layouts can be very useful. A subsequent operation might significantly benefit from
receiving a particular layout. We are working on an API to control the result layout
and recognize it is an important feature to plan a more optimal path of execution for
any given model.
Sparse Semi-Structured Tensors
Semi-Structured sparsity is a sparse data layout that was first introduced in NVIDIA’s Ampere architecture. It is also referred to as fine-grained structured sparsity or 2:4 structured sparsity.
This sparse layout stores n elements out of every 2n elements, with n being determined by the width of the Tensor’s data type (dtype). The most frequently used dtype is float16, where n=2, thus the term “2:4 structured sparsity.”
In PyTorch, semi-structured sparsity is implemented via a Tensor subclass.
By subclassing, we can override __torch_dispatch__ , allowing us to use faster sparse kernels when performing matrix multiplication.
We can also store the tensor in it’s compressed form inside the subclass to reduce memory overhead.
In this compressed form, the sparse tensor is stored by retaining only the specified elements and some metadata, which encodes the mask.
For 2:4 sparse tensors, the metadata overhead is minor - just 2 bits per specified element.
Here, we break down how to calculate the compression ratio ( size dense / size sparse) of a 2:4 sparse tensor.
Let (r,c)=tensor.shape and e=bitwidth(tensor.dtype), so e=16 for torch.float16 and torch.bfloat16 and e=8 for torch.int8.
Using these calculations, we can determine the total memory footprint for both the original dense and the new sparse representation.
This gives us a simple formula for the compression ratio, which is dependent only on the bitwidth of the tensor datatype.
C=MdenseMsparse=21+e1
By using this formula, we find that the compression ratio is 56.25% for torch.float16 or torch.bfloat16, and 62.5% for torch.int8.
Constructing Sparse Semi-Structured Tensors
You can transform a dense tensor into a sparse semi-structured tensor by simply using the torch.to_sparse_semi_structured function.
Please also note that we only support CUDA tensors since hardware compatibility for semi-structured sparsity is limited to NVIDIA GPUs.
The following datatypes are supported for semi-structured sparsity. Note that each datatype has its own shape constraints and compression factor.
PyTorch dtype
Shape Constraints
Compression Factor
Sparsity Pattern
Sparse Semi-Structured Tensor Operations
Currently, the following operations are supported for semi-structured sparse tensors:
torch.addmm(bias, dense, sparse.t())
torch.mm(dense, sparse)
torch.mm(sparse, dense)
aten.linear.default(dense, sparse, bias)
aten.t.default(sparse)
aten.t.detach(sparse)
To use these ops, simply pass the output of to_sparse_semi_structured(tensor) instead of using tensor once your tensor has 0s in a semi-structured sparse format, like this:
>>> a = torch.Tensor([0,0,1,1]).
Accelerating nn.Linear with semi-structured sparsity
You can accelerate the linear layers in your model if the weights are already semi-structured sparse with just a few lines of code:
PyTorch implements the so-called Coordinate format, or COO
format, as one of the storage formats for implementing sparse
tensors. In COO format, the specified elements are stored as tuples
of element indices and the corresponding values. In particular,
the indices of specified elements are collected in indices
tensor of size (ndim,nse) and with element type
torch.int64,
the corresponding values are collected in values tensor of
size (nse,) and with an arbitrary integer or floating point
number element type,
where ndim is the dimensionality of the tensor and nse is the
number of specified elements.
Construction
A sparse COO tensor can be constructed by providing the two tensors of
indices and values, as well as the size of the sparse tensor (when it
cannot be inferred from the indices and values tensors) to a function
torch.sparse_coo_tensor().
Suppose we want to define a sparse tensor with the entry 3 at location
(0, 2), entry 4 at location (1, 0), and entry 5 at location (1, 2).
Unspecified elements are assumed to have the same value, fill value,
which is zero by default. We would then write:
>>> i =[[0,1,1],[2,0,2]]>>> v =[3,4,
Sparse hybrid COO tensors
PyTorch implements an extension of sparse tensors with scalar values
to sparse tensors with (contiguous) tensor values. Such tensors are
called hybrid tensors.
PyTorch hybrid COO tensor extends the sparse COO tensor by allowing
the values tensor to be a multi-dimensional tensor so that we
have:
the indices of specified elements are collected in indices
tensor of size (sparse_dims,nse) and with element type
torch.int64,
the corresponding (tensor) values are collected in values
tensor of size (nse,dense_dims) and with an arbitrary integer
or floating point number element type.
Uncoalesced sparse COO tensors
PyTorch sparse COO tensor format permits sparse uncoalesced tensors,
where there may be duplicate coordinates in the indices; in this case,
the interpretation is that the value at that index is the sum of all
duplicate value entries. For example, one can specify multiple values,
3 and 4, for the same index 1, that leads to an 1-D
uncoalesced tensor:
>>> i =[[1,1]]>>> v =[3,4]>>> s=torch.sparse_coo_tensor(i, v
Working with sparse COO tensors
Let’s consider the following example:
>>> i =[[0,1,1], [2, 0, 2]]>>> v =[[3,4],[5,6],[7,8]]>>> s = torch.sparse_coo_tensor(i, v,(
Sparse Compressed Tensors
Sparse Compressed Tensors represents a class of sparse tensors that
have a common feature of compressing the indices of a certain dimension
using an encoding that enables certain optimizations on linear algebra
kernels of sparse compressed tensors. This encoding is based on the
Compressed Sparse Row (CSR) format that PyTorch sparse compressed
tensors extend with the support of sparse tensor batches, allowing
multi-dimensional tensor values, and storing sparse tensor values in
dense blocks.
Sparse CSR Tensor
The primary advantage of the CSR format over the COO format is better
use of storage and much faster computation operations such as sparse
matrix-vector multiplication using MKL and MAGMA backends.
In the simplest case, a (0 + 2 + 0)-dimensional sparse CSR tensor
consists of three 1-D tensors: crow_indices, col_indices and
values:
The crow_indices tensor consists of compressed row
indices. This is a 1-D tensor of size nrows+1 (the number of
rows plus 1). The last element of crow_indices is the number
of specified elements, nse. This tensor encodes the index in
values and depending on where the given row
starts. Each successive number in the tensor subtracted by the
number before it denotes the number of elements in a given row.
Sparse CSC Tensor
The sparse CSC (Compressed Sparse Column) tensor format implements the
CSC format for storage of 2 dimensional tensors with an extension to
supporting batches of sparse CSC tensors and values being
multi-dimensional tensors.
Similarly to sparse CSR tensors, a sparse CSC
tensor consists of three tensors: ccol_indices, row_indices
and values:
The ccol_indices tensor consists of compressed column
indices. This is a (B + 1)-D tensor of shape (*batchsize,ncols+.
The last element is the number of specified
elements, . This tensor encodes the index in and
depending on where the given column starts. Each
successive number in the tensor subtracted by the number before it
denotes the number of elements in a given column.
Sparse BSR Tensor
The sparse BSR (Block compressed Sparse Row) tensor format implements the
BSR format for storage of two-dimensional tensors with an extension to
supporting batches of sparse BSR tensors and values being blocks of
multi-dimensional tensors.
A sparse BSR tensor consists of three tensors: crow_indices,
col_indices and values:
The crow_indices tensor consists of compressed row
indices. This is a (B + 1)-D tensor of shape (*batchsize,nrowblocks+1). The last element is the number of specified blocks,
nse. This tensor encodes the index in values and
col_indices depending on where the given column block
starts. Each successive number in the tensor subtracted by the
number before it denotes the number of blocks in a given row.
Sparse BSC Tensor
The sparse BSC (Block compressed Sparse Column) tensor format implements the
BSC format for storage of two-dimensional tensors with an extension to
supporting batches of sparse BSC tensors and values being blocks of
multi-dimensional tensors.
A sparse BSC tensor consists of three tensors: ccol_indices,
row_indices and values:
The ccol_indices tensor consists of compressed column
indices. This is a (B + 1)-D tensor of shape (*batchsize,ncolblocks+1). The last element is the number of specified blocks,
nse. This tensor encodes the index in values and
row_indices depending on where the given row block
starts. Each successive number in the tensor subtracted by the
number before it denotes the number of blocks in a given column.
Tools for working with sparse compressed tensors
All sparse compressed tensors — CSR, CSC, BSR, and BSC tensors —
are conceptually very similar in that their indices data is split
into two parts: so-called compressed indices that use the CSR
encoding, and so-called plain indices that are orthogonal to the
compressed indices. This allows various tools on these tensors to
share the same implementations that are parameterized by tensor
layout.
Construction of sparse compressed tensors
Sparse CSR, CSC, BSR, and CSC tensors can be constructed by using
torch.sparse_compressed_tensor() function that have the same
interface as the above discussed constructor functions
torch.sparse_csr_tensor(), torch.sparse_csc_tensor(),
, and ,
respectively, but with an extra required argument. The
following example illustrates a method of constructing CSR and CSC
tensors using the same input data by specifying the corresponding
layout parameter to the
function:
Supported operations
Linear Algebra operations
The following table summarizes supported Linear Algebra operations on
sparse matrices where the operands layouts may vary. Here
T[layout] denotes a tensor with a given layout. Similarly,
M[layout] denotes a matrix (2-D PyTorch tensor), and V[layout]
denotes a vector (1-D PyTorch tensor). In addition, f denotes a
scalar (float or 0-D PyTorch tensor), * is element-wise
multiplication, and @ is matrix multiplication.
where “Sparse grad?” column indicates if the PyTorch operation supports
backward with respect to sparse matrix argument. All PyTorch operations,
except torch.smm(), support backward with respect to strided
matrix arguments.
Tensor methods and sparse
The following Tensor methods are related to sparse tensors:
We aim to support all ‘zero-preserving unary functions’: functions of one argument that map zero to zero.
If you find that we are missing a zero-preserving unary function
that you need, please feel encouraged to open an issue for a feature request.
As always please kindly try the search function first before opening an issue.
The following operators currently support sparse COO/CSR/CSC/BSR/CSR tensor inputs.
.indices() returns the metadata_mask in a tensor of size (r,c//2) and with element type torch.int16 if dtype is torch.float16 or torch.bfloat16, and element type torch.int32 if dtype is torch.int8.
torch.float16
Tensor must be 2D and (r, c) must both be a positive multiple of 64
9/16
2:4
torch.bfloat16
Tensor must be 2D and (r, c) must both be a positive multiple of 64
9/16
2:4
torch.int8
Tensor must be 2D and (r, c) must both be a positive multiple of 128
10/16
2:4
To construct a semi-structured sparse tensor, start by creating a regular dense tensor that adheres to a 2:4 (or semi-structured) sparse format.
To do this we tile a small 1x4 strip to create a 16x16 dense float16 tensor.
Afterwards, we can call to_sparse_semi_structured function to compress it for accelerated inference.
This function converts a dense tensor into a sparse semi-structured tensor.
It will return a SparseSemiStructuredTensor, a subclass of torch.Tensor.
This function will check to ensure the dense tensor has the right dtype, size, dims, and device.
We currently only support semi-structured sparse tensors for 2d CUDA tensors.
Additionally, your tensor must be a positive multiple of the minimum sparse block size, given in
_DTYPE_TO_SHAPE_CONSTRAINTS for each dtype (float32, float16, bfloat16, int8).
Parameters:
original_tensor (Tensor) – the dense tensor to convert
transposed (bool, optional) – deprecated arg to be removed in another release. Do not use.
alg_id (int, optional) – the algorithm id to use for cuSPARSELt matmul. Defaults to 0.
Can be obtained via torch._cslt_sparse_mm_search.
Returns:
A sparse semi-structured tensor created from the given original_tensor
The cuSPARSELt backend expects the specified elements and the metadata to be stored in a single tensor: packed = [ specified elements of original tensor | metadata ] For an original tensor of size (m, k) we expect the first m * k // 2 elements to be the kept elements The rest of the tensor is metadata.
This class implements semi-structured sparsity for the CUTLASS backend.
000
000
5
]
>>> s = torch.sparse_coo_tensor(i, v,(2,3))
>>> s
tensor(indices=tensor([[0, 1, 1],
[2, 0, 2]]),
values=tensor([3, 4, 5]),
size=(2, 3), nnz=3, layout=torch.sparse_coo)
>>> s.to_dense()
tensor([[0, 0, 3],
[4, 0, 5]])
Note that the input i is NOT a list of index tuples. If you want
to write your indices this way, you should transpose before passing them to
the sparse constructor:
>>> i =[[0,2],[1,0],[1,2]]>>> v =[3,4,5]>>> s = torch.sparse_coo_tensor(list(zip(*i)), v,(2,3))>>> # Or another equivalent formulation to get s>>> s = torch.sparse_coo_tensor(torch.tensor(i).t(), v,(2,3))>>> torch.sparse_coo_tensor(i.t(), v, torch.Size([2,3])).to_dense()tensor([[0, 0, 3], [4, 0, 5]])
An empty sparse COO tensor can be constructed by specifying its size
only:
We use (M + K)-dimensional tensor to denote a N-dimensional sparse
hybrid tensor, where M and K are the numbers of sparse and dense
dimensions, respectively, such that M + K == N holds.
Suppose we want to create a (2 + 1)-dimensional tensor with the entry
[3, 4] at location (0, 2), entry [5, 6] at location (1, 0), and entry
[7, 8] at location (1, 2). We would write
As mentioned above, a sparse COO tensor is a torch.Tensor
instance and to distinguish it from the Tensor instances that use
some other layout, one can use torch.Tensor.is_sparse or
torch.Tensor.layout properties:
When working with uncoalesced sparse COO tensors, one must take into
an account the additive nature of uncoalesced data: the values of the
same indices are the terms of a sum that evaluation gives the value of
the corresponding tensor element. For example, the scalar
multiplication on a sparse uncoalesced tensor could be implemented by
multiplying all the uncoalesced values with the scalar because
c*(a+b)==c*a+c*b holds. However, any nonlinear operation,
say, a square root, cannot be implemented by applying the operation to
uncoalesced data because sqrt(a+b)==sqrt(a)+sqrt(b) does not
hold in general.
Slicing (with positive step) of a sparse COO tensor is supported only
for dense dimensions. Indexing is supported for both sparse and dense
dimensions:
In PyTorch, the fill value of a sparse tensor cannot be specified
explicitly and is assumed to be zero in general. However, there exists
operations that may interpret the fill value differently. For
instance, torch.sparse.softmax() computes the softmax with the
assumption that the fill value is negative infinity.
nse
nse
0<=compressed_indices[...,i]-compressed_indices[...,i-1]<=plain_dim_size for i=1,...,compressed_dim_size,
where plain_dim_size is the number of plain dimensions
(orthogonal to compressed dimensions, e.g. columns or rows).
To be sure that a constructed sparse tensor has consistent indices,
values, and size, the invariant checks can be enabled per tensor
creation via check_invariants=True keyword argument, or
globally using torch.sparse.check_sparse_tensor_invariants
context manager instance. By default, the sparse tensor invariants
checks are disabled.
col_indices
The col_indices tensor contains the column indices of each
element. This is a 1-D tensor of size nse.
The values tensor contains the values of the CSR tensor
elements. This is a 1-D tensor of size nse.
In the general case, the (B + 2 + K)-dimensional sparse CSR tensor
consists of two (B + 1)-dimensional index tensors crow_indices and
col_indices, and of (1 + K)-dimensional values tensor such
that
crow_indices.shape==(*batchsize,nrows+1)
col_indices.shape==(*batchsize,nse)
values.shape==(nse,*densesize)
while the shape of the sparse CSR tensor is (*batchsize,nrows,ncols,*densesize) where len(batchsize)==B and
len(densesize)==K.
Construction of CSR tensors
Sparse CSR tensors can be directly constructed by using the
torch.sparse_csr_tensor() function. The user must supply the row
and column indices and values tensors separately where the row indices
must be specified using the CSR compression encoding. The size
argument is optional and will be deduced from the crow_indices and
col_indices if it is not present.
The simplest way of constructing a 2-D sparse CSR tensor from a
strided or sparse COO tensor is to use
torch.Tensor.to_sparse_csr() method. Any zeros in the (strided)
tensor will be interpreted as missing values in the sparse tensor:
>>> a = torch.tensor([[0,0,1,0],[1,2,0,0],[0,0,0,0]], dtype=torch.float64)>>> sp = a.to_sparse_csr()>>> sp
CSR Tensor Operations
The sparse matrix-vector multiplication can be performed with the
tensor.matmul() method. This is currently the only math operation
supported on CSR tensors.
The row_indices tensor contains the row indices of each
element. This is a (B + 1)-D tensor of shape (*batchsize,nse).
The values tensor contains the values of the CSC tensor
elements. This is a (1 + K)-D tensor of shape (nse,*densesize).
Construction of CSC tensors
Sparse CSC tensors can be directly constructed by using the
torch.sparse_csc_tensor() function. The user must supply the row
and column indices and values tensors separately where the column indices
must be specified using the CSR compression encoding. The size
argument is optional and will be deduced from the row_indices and
ccol_indices tensors if it is not present.
The (0 + 2 + 0)-dimensional sparse CSC tensors can be constructed from
any two-dimensional tensor using torch.Tensor.to_sparse_csc()
method. Any zeros in the (strided) tensor will be interpreted as
missing values in the sparse tensor:
>>> a = torch.tensor([[0,0,1,0],[1,2,0,0],[0,0,0,0]], dtype=torch.float64)>>> sp = a.to_sparse_csc()>>> sp
The col_indices tensor contains the column block indices of each
element. This is a (B + 1)-D tensor of shape (*batchsize,nse).
The values tensor contains the values of the sparse BSR tensor
elements collected into two-dimensional blocks. This is a (1 + 2 +
K)-D tensor of shape (nse,nrowblocks,ncolblocks,*densesize).
Construction of BSR tensors
Sparse BSR tensors can be directly constructed by using the
torch.sparse_bsr_tensor() function. The user must supply the row
and column block indices and values tensors separately where the row block indices
must be specified using the CSR compression encoding.
The size argument is optional and will be deduced from the crow_indices and
col_indices tensors if it is not present.
The (0 + 2 + 0)-dimensional sparse BSR tensors can be constructed from
any two-dimensional tensor using torch.Tensor.to_sparse_bsr()
method that also requires the specification of the values block size:
The row_indices tensor contains the row block indices of each
element. This is a (B + 1)-D tensor of shape (*batchsize,nse).
The values tensor contains the values of the sparse BSC tensor
elements collected into two-dimensional blocks. This is a (1 + 2 +
K)-D tensor of shape (nse,nrowblocks,ncolblocks,*densesize).
Construction of BSC tensors
Sparse BSC tensors can be directly constructed by using the
torch.sparse_bsc_tensor() function. The user must supply the row
and column block indices and values tensors separately where the column block indices
must be specified using the CSR compression encoding.
The size argument is optional and will be deduced from the ccol_indices and
row_indices tensors if it is not present.