Sparse, Nested & Complex Tensors
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Dense, strided tensors cover most deep learning code. Three special representations cover the cases where the dense layout wastes memory or cannot express the data: sparse tensors (mostly zeros), nested tensors (a batch of sequences with different lengths, without padding) and complex tensors (values with a real and imaginary part). This page describes each one, how stable it is, and what can go wrong. The basics of tensors are in Tensors: Creation, Attributes & Dtypes, and structured sparsity as a model-compression technique is in Quantization & Sparsity.
Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31; the semi-structured (2:4) sparsity example needs a CUDA GPU with sparse tensor cores and was not executed. All three features are marked in the documentation as beta, prototype or not under active development, so read the status of each section before building on it.
Sparse tensors
A sparse tensor stores only the specified elements and treats everything else as a fill value, which is zero for almost every operation. The documentation describes the sparse API as being in beta and subject to change. Sparse formats do not always make code faster; the page itself recommends filing an issue when a sparse operation is slower than the dense equivalent, so always measure.
Layouts and constructors
| Layout | Constructor | Conversion from dense |
|---|---|---|
COO (coordinate) |
|
|
CSR (compressed sparse row) |
|
|
CSC (compressed sparse column) |
|
|
BSR (block sparse row) |
|
|
BSC (block sparse column) |
|
|
torch.sparse_compressed_tensor is the generic constructor and takes a layout argument. COO stores one index per dimension for every element, so it is flexible but memory hungry. The compressed layouts store a compressed pointer array plus one index array, which is smaller and faster for matrix products on 2D data. The block layouts keep dense blocks, which suits GPU kernels. Batch dimensions and dense dimensions are supported (a hybrid COO tensor has dense dimensions after the sparse ones).
import torch
dense = torch.tensor([[0.0, 2.0, 0.0],
[3.0, 0.0, 0.0],
[0.0, 0.0, 4.0]])
coo = dense.to_sparse() # COO
csr = dense.to_sparse_csr() # CSR
print(coo.layout, coo._nnz()) # torch.sparse_coo 3
print(csr.crow_indices()) # tensor([0, 1, 2, 3])
print(csr.col_indices()) # tensor([1, 0, 2])
print(csr.values()) # tensor([2., 3., 4.])
# Explicit construction of the same COO tensor
indices = torch.tensor([[0, 1, 2], [1, 0, 2]])
values = torch.tensor([2.0, 3.0, 4.0])
same = torch.sparse_coo_tensor(indices, values, size=(3, 3))
print(torch.equal(same.to_dense(), dense)) # True
Coalescing and the fill value
A COO tensor can be uncoalesced, which means the same index may appear more than once; the duplicates are summed when the tensor is coalesced or densified. indices() and values() are only defined on a coalesced tensor, so call coalesce() first. _indices() and _values() skip that requirement but return detached tensors, so use coalesce().values() when you need gradients.
i = torch.tensor([[0, 0], [1, 1]]) # the same position twice
v = torch.tensor([1.0, 2.0])
x = torch.sparse_coo_tensor(i, v, (2, 2))
print(x.is_coalesced()) # False
print(x.coalesce().values()) # tensor([3.])
The unspecified elements are zero for almost all operations. torch.sparse.softmax is an exception: it treats unspecified elements as negative infinity, so they get zero probability. Index validation is off by default for speed; pass check_invariants=True to a constructor, or use torch.sparse.check_sparse_tensor_invariants, while debugging.
Operations
The documented support includes the matrix products torch.mv, torch.mm, torch.bmm, torch.matmul, torch.addmm, torch.sparse.mm, torch.sparse.addmm, torch.sparse.sampled_addmm, torch.smm, torch.hspmm, torch.sspaddmm, the sparse solver torch.sparse.spsolve (CSR), the reductions and normalizations torch.sparse.sum, torch.sparse.softmax and torch.sparse.log_softmax, torch.sparse.spdiags, and low-rank routines such as torch.pca_lowrank, torch.svd_lowrank and torch.lobpcg. Zero-preserving elementwise functions such as abs, sin, sqrt, neg, log1p, expm1 and erf accept sparse input. Functions that map zero to a non-zero value (for example cos) are not supported on CSR tensors; convert with to_dense() first.
Output layout is not selectable: sparse plus strided produces a strided tensor. For autograd, torch.sparse.mm and torch.sparse.addmm support backward with respect to the sparse argument, while torch.smm does not.
import torch
adj = torch.tensor([[0.0, 1.0, 0.0],
[1.0, 0.0, 1.0],
[0.0, 1.0, 0.0]]).to_sparse()
feat = torch.randn(3, 4, requires_grad=True)
out = torch.sparse.mm(adj, feat) # sparse @ dense -> dense
out.sum().backward()
print(out.shape, feat.grad.shape) # torch.Size([3, 4]) torch.Size([3, 4])
This sparse-times-dense product is the core of graph convolutions; see Graph Neural Networks for the model side.
Semi-structured (2:4) sparsity
NVIDIA sparse tensor cores accelerate matrices where two out of every four consecutive elements are zero. PyTorch exposes this as torch.sparse.semi_structured.to_sparse_semi_structured. The documentation marks it as a prototype, available only on CUDA. For float16 and bfloat16 the tensor must be 2D with both dimensions positive multiples of 64 (multiples of 128 for int8); storage drops to about 56.25% of the dense size for 16-bit types. Supported operations are torch.addmm, torch.mm, aten.linear.default and aten.t, and the usual way to use it is to replace the weight of an nn.Linear after the weights have been pruned to the 2:4 pattern.
import torch
from torch import nn
from torch.sparse import to_sparse_semi_structured
# Requires a CUDA GPU with sparse tensor cores (Ampere or newer).
linear = nn.Linear(128, 128).half().cuda().eval()
# Prune to 2:4: keep two of every four weights (illustrative mask).
mask = torch.tensor([0, 0, 1, 1], device="cuda").tile(128, 32).bool()
linear.weight = nn.Parameter(to_sparse_semi_structured(linear.weight * mask))
x = torch.rand(64, 128).half().cuda()
with torch.no_grad():
y = linear(x)
How to choose which weights to prune, and how to recover accuracy, is a pruning topic covered in Model Compression.
Nested tensors
A batch of sentences of different lengths is usually padded to the longest one, which wastes memory and compute and forces you to carry a mask. A nested tensor stores the sequences packed back to back and remembers where each one starts. The documentation states that nested tensors are not currently under active development, so treat the API as experimental, and prefer the jagged layout, which is the recommended one.
Strided versus jagged layout
torch.strided is the original layout and torch.jagged is the newer one, usually shortened to NJT. NJT supports one ragged dimension, has broader operator coverage and works with torch.compile. Internally an NJT is a single packed values() tensor plus an offsets() tensor marking the boundaries between batch items.
import torch
a = torch.randn(4, 8) # sequence of 4 tokens, 8 features
b = torch.randn(2, 8) # sequence of 2 tokens
nt = torch.nested.nested_tensor([a, b], layout=torch.jagged)
print(nt.shape) # torch.Size([2, j1, 8]) - j1 is the ragged dimension
print(nt.values().shape) # torch.Size([6, 8]) - packed, no padding
print(nt.offsets()) # tensor([0, 4, 6])
Construction functions
| Function | Behaviour |
|---|---|
|
Copies the inputs into packed memory and returns a leaf tensor; inputs need the same number of dimensions. |
|
Preserves autograd history so gradients flow back to the original tensors; list inputs are still copied. |
|
Builds a non-contiguous view over a padded dense tensor without copying; for the jagged layout only |
|
Builds an NJT from its components. Passing both offsets and lengths creates a tensor with holes. |
|
Selects with a mask while keeping the dimensionality, encoding the structure in offsets. |
Operations and attention
unbind() returns views of the constituent tensors, torch.nested.to_padded_tensor(nt, padding) converts to a dense padded tensor (always a copy, so avoid it in hot paths), and shape operations such as unsqueeze, unflatten, cat, stack and transpose are supported. NJTs work with scaled_dot_product_attention and FlexAttention for variable-length attention without a padding mask; see Attention, SDPA, FlexAttention & Transformers.
import torch
import torch.nn.functional as F
seqs = [torch.randn(5, 64), torch.randn(3, 64)]
nt = torch.nested.nested_tensor(seqs, layout=torch.jagged)
# (batch, ragged, features) -> (batch, heads, ragged, head_dim)
q = nt.unflatten(-1, [4, 16]).transpose(1, 2)
out = F.scaled_dot_product_attention(q, q, q)
padded = torch.nested.to_padded_tensor(out.transpose(1, 2).flatten(-2), 0.0)
print(padded.shape) # torch.Size([2, 5, 64]) for the padded copy
The reshaping steps in this snippet (unflatten and transpose of the dense dimensions, then flatten back) run on CPU in 2.15. Operations that touch the batch or ragged dimension are not supported and raise an error (for example nt.flatten(0, 1) raises RuntimeError and nt.transpose(0, 1) raises ValueError); restructure the projection so those dimensions are left alone.
Pitfalls
-
Binary operations need operands that share the same
offsets; build the second NJT withnested_tensor_from_jaggedusing the first one’soffsets()to satisfy that. -
A
NotImplementedErrormentioning anatenoperator means that operator has no NJT support; fall back tounbind()or padding. -
Under
torch.compile, data-dependent operations such aschunk()on the batch dimension may need the Dynamo optionscapture_scalar_outputsandcapture_dynamic_output_shape_opsenabled. -
Starting with PyTorch 2.15, nested tensors are no longer on the default
weights_onlyallowlist, so loading a saved nested tensor needstorch.serialization.safe_globalsorweights_only=Falsefor a trusted file (from the 2.15 release notes). See Saving & Loading Models.
Complex tensors
Complex tensors have dtypes torch.cfloat (complex64) and torch.cdouble (complex128), and the documentation marks the feature as beta. They are used for signal processing (FFT), physics and some neural network layers. They replace the older workaround of keeping a real tensor with a trailing dimension of size 2.
import torch
z = torch.randn(2, 2, dtype=torch.cfloat)
# Real tensor with trailing dimension 2 <-> complex tensor, both without copying
r = torch.randn(3, 2)
c = torch.view_as_complex(r)
back = torch.view_as_real(c) # shape (3, 2) again
# .real and .imag are views: in-place edits change the complex tensor
c.real.mul_(2)
print(torch.abs(c), torch.angle(c)) # magnitude and phase
spectrum = torch.fft.fft(torch.randn(8))
print(spectrum.dtype) # torch.complex64
Most factory functions accept complex dtypes, with the documented exceptions linspace, logspace and arange. Linear algebra routines such as matmul, linalg.svd and linalg.solve support complex input, and complex tensors can be saved and loaded like any other tensor.
Autograd and optimizers
Gradients of complex-valued computations use the conjugate Wirtinger derivative, so a real-valued loss of complex parameters has a well-defined gradient and the existing optimizers work unchanged. Stepping an optimizer on complex parameters is meant to match stepping it on their view_as_real equivalents, with small numerical differences possible; optimizers with global reductions such as LBFGS can differ slightly. The loss must be real: call .abs(), .real or similar before backward().
Choosing the right representation
| Representation | Use it when | Avoid it when |
|---|---|---|
Sparse (COO, CSR, BSR) |
Adjacency matrices, bag-of-words features, very sparse embeddings gradients, 2:4 pruned weights on Ampere GPUs |
The matrix is only moderately sparse; measure first because dense kernels are often faster |
Nested (jagged) |
Variable-length sequences feeding attention without padding |
You need operators outside the supported set, or long-term API stability |
Complex |
FFTs, spectral methods, phase-aware layers |
You need quantization, TorchScript or distributed training on those tensors |