CSR (Compressed Sparse Row) is a memory-efficient data structure for representing sparse matrices, where most elements are zero. It encodes three arrays: values (non-zero entries), col_indices (their column positions), and row_ptr (compressed pointers to the start of each row). This format eliminates the storage of zeros, drastically reducing memory footprint for models with weight sparsity from pruning. Its row-major compression is optimal for operations like sparse matrix-vector multiplication (SpMV), a core kernel in neural network inference.
Glossary
CSR Format (Compressed Sparse Row)

What is CSR Format (Compressed Sparse Row)?
The CSR (Compressed Sparse Row) format is a standard storage scheme for sparse matrices, designed to minimize memory usage and enable efficient linear algebra operations by encoding only non-zero values and their locations.
The efficiency of CSR in execution depends on the sparse data layout. The row_ptr array enables fast row traversal, but irregular column indices within a row can cause load imbalance in parallel hardware. For sparse matrix multiplication (SpMM) on GPUs, CSR kernels must optimize gather-scatter operations to mitigate overhead from irregular memory access. While excellent for general sparse storage, structured pruning patterns like N:M sparsity may use even more efficient, hardware-native formats. CSR remains foundational for representing unstructured sparsity in compressed models.
Key Characteristics of CSR Format
The Compressed Sparse Row (CSR) format is a foundational data structure for efficiently storing and operating on sparse matrices, where most elements are zero. Its design prioritizes fast row access and is a cornerstone for executing pruned neural networks.
Core Data Structure
CSR represents a sparse matrix using three one-dimensional arrays:
values(val or data): Stores all non-zero values in row-major order.column_indices(col_idx): Stores the column index for each corresponding non-zero value.row_pointers(row_ptr): Stores the cumulative number of non-zero elements up to each row. The non-zero values for rowiare found invalues[row_ptr[i]:row_ptr[i+1]].
This structure eliminates the storage of zeros, trading memory for the overhead of storing explicit indices.
Optimized for Row-Wise Operations
The row_pointers array enables constant-time lookup to find the start and end of any row's non-zero elements. This makes CSR exceptionally efficient for algorithms that iterate over rows, such as:
- Sparse Matrix-Vector Multiplication (SpMV): The canonical operation where CSR excels.
- Row slicing and access.
- Forward passes in neural networks, which are often expressed as sequences of SpMV-like operations.
Its efficiency diminishes for operations requiring fast column access, for which the Compressed Sparse Column (CSC) format is better suited.
Memory Efficiency Profile
For an M x N matrix with NZ non-zeros, CSR storage cost is:
values:NZelements.column_indices:NZinteger elements.row_pointers:M + 1integer elements.
This is typically far smaller than the dense M * N storage. The break-even point depends on the sparsity level and the bit-width of the indices. For highly sparse weight matrices in pruned models, CSR can reduce memory footprint by 10x or more compared to dense storage.
Sparse Matrix Multiplication (SpMM) Kernel
Executing Sparse Matrix-Dense Matrix Multiplication (SpMM)—the workhorse of sparse inference—with CSR involves a nested loop:
- Outer loop iterates over rows (
i). - Inner loop iterates over non-zeros in row
i(usingrow_ptr). - For each non-zero, multiply it with the corresponding row of the dense input matrix (indexed by
col_idx).
Performance is dominated by indirect memory access (gather) into the dense matrix and potential load imbalance if rows have highly variable non-zero counts. Optimized SpMM kernels use techniques like row grouping and warp-level parallelism to mitigate these issues.
Comparison with COO Format
CSR is often compared to the simpler Coordinate (COO) Format, which stores a list of (row, column, value) tuples.
| Aspect | CSR | COO |
|---|---|---|
| Storage | NZ + NZ + (M+1) | NZ + NZ + NZ (3 arrays) |
| Row Access | Fast (O(1) via row_ptr) | Slow (requires search) |
| Construction | Requires sorting | Simple to build |
| Duplicates | Not allowed | Can handle duplicates |
CSR is generally preferred for efficient computation, while COO is useful for incremental matrix construction before conversion.
Hardware & Compiler Considerations
Efficient execution of CSR-based models depends on the underlying hardware and software stack:
- GPUs with Sparse Tensor Cores (e.g., NVIDIA Ampere+): Can accelerate CSR/SpMM but often require a structured sparsity pattern (e.g., 2:4) for peak performance, necessitating a conversion from the unstructured CSR format.
- Compiler Mapping: AI compilers (e.g., TVM, MLIR) must map the abstract CSR operations to optimized gather-compute-scatter kernels on the target architecture.
- Overhead: The sparse efficiency gap is real; the theoretical FLOP reduction from sparsity is offset by kernel overhead for index processing and irregular memory access. Profiling is essential.
CSR vs. Other Sparse Storage Formats
A technical comparison of the Compressed Sparse Row (CSR) format against other common sparse tensor representations, highlighting their memory efficiency, access patterns, and suitability for different computational kernels in sparse model inference.
| Feature / Metric | CSR (Compressed Sparse Row) | COO (Coordinate Format) | CSC (Compressed Sparse Column) | Blocked CSR (BCSR) |
|---|---|---|---|---|
Primary Storage Arrays | row_ptr, col_ind, val | row_ind, col_ind, val | col_ptr, row_ind, val | row_ptr, col_ind, val (blocked) |
Optimal Access Pattern | Row-wise traversal | Random, unordered access | Column-wise traversal | Row-wise, block-aligned traversal |
Memory Overhead (Indices) | O(nnz + n_rows) | O(2 * nnz) | O(nnz + n_cols) | O(nnz + n_rows) + block metadata |
SpMM (Sparse-Dense) Kernel Suitability | ✅ Excellent for SpMM (A * B) | ❌ Poor (requires conversion) | ✅ Excellent for SpMM (A^T * B) | ✅ Excellent for vectorized/GPU SpMM |
Ease of Construction/Modification | ❌ Difficult (requires sorting, prefix sum) | ✅ Trivial (append tuples) | ❌ Difficult (requires sorting, prefix sum) | ❌ Difficult (requires block detection & alignment) |
Hardware Acceleration Support | Widely supported in BLAS libraries | Minimal native support | Widely supported in BLAS libraries | Targeted support for specific NPUs/GPUs |
Typical Use Case in ML | Inference for unstructured sparse weights (SpMM) | Initial sparse representation; graph data | Operations requiring column access | Inference for structured/blocked sparse weights |
CSR in ML Frameworks and Libraries
The Compressed Sparse Row (CSR) format is a foundational data structure for efficiently storing and computing with sparse matrices, where most elements are zero. It is critical for executing pruned neural networks on hardware accelerators.
Core Data Structure
The CSR format represents a sparse matrix using three one-dimensional arrays:
data: Stores all non-zero values in row-major order.indices: Stores the column index for each corresponding non-zero value in thedataarray.indptr(index pointer): Stores the start and end indices in thedataandindicesarrays for each row. For rowi, non-zero values are found atdata[indptr[i]:indptr[i+1]]with column indicesindices[indptr[i]:indptr[i+1]]. This structure eliminates the storage of zeros, compressing memory footprint, but introduces indirect memory access via theindicesarray.
Sparse Matrix Multiplication (SpMM)
The primary operation enabled by CSR is Sparse Matrix-Dense Matrix Multiplication (SpMM), a key kernel in sparse neural network inference. For a sparse weight matrix W in CSR and a dense input activation matrix X, the output Y = W @ X is computed row-by-row:
- Each row of
Wdefines a sparse dot product. - The
indptrarray allows efficient iteration over rows. - For each non-zero weight
W[i, j]at columnj, the operation gathers the dense vectorX[j, :], multiplies it by the weight, and scatters the result intoY[i, :]. Performance hinges on optimizing these gather-scatter operations and managing load imbalance from varying row lengths.
Integration in ML Frameworks
Major frameworks provide specialized APIs and backends for CSR:
- PyTorch: Offers
torch.sparse_csrtensor type with operators liketorch.sparse.mm()for SpMM. Sparse tensors can be created from dense ones viato_sparse_csr(). The TorchInductor compiler can fuse sparse operations. - TensorFlow / JAX: Use
scipy.sparse.csr_matrixas an interoperable standard. JAX'sjax.experimental.sparsemodule provides JIT-compatible CSR operations. TensorFlow has historical support viatf.sparse.SparseTensor(in COO format, convertible to CSR). - Framework Kernels: These APIs dispatch to optimized backend libraries like cuSPARSE (NVIDIA GPU), MKL (Intel CPU), or Eigen for actual computation, abstracting the complex kernel implementation.
Hardware Acceleration & Limitations
While CSR is versatile, its irregular memory access pattern poses challenges for peak hardware utilization:
- GPU Execution: NVIDIA's Sparse Tensor Cores (on Ampere+ GPUs) do not natively support arbitrary CSR. They require the 2:4 fine-grained structured sparsity pattern, where a custom compressed format is used. Generic CSR SpMM relies on cuSPARSE libraries which can suffer from load imbalance and metadata overhead.
- CPU Execution: Optimized MKL/OpenBLAS kernels use vectorization, but performance is often memory-bandwidth bound due to indirect accesses.
- Specialized NPUs: Many edge AI accelerators have dedicated units for structured sparsity (e.g., channel pruning). Irregular CSR from unstructured pruning may not achieve peak throughput, leading to the sparse efficiency gap. The choice between CSR and other formats (like Blocked CSR) is a hardware-aware decision.
The Sparse Efficiency Gap
A critical concept in sparse inference is that the theoretical FLOP reduction from pruning does not translate linearly to speedup. With CSR, this gap is caused by:
- Kernel Overhead: Decoding
indptrandindicesarrays, conditional branching, and pointer chasing add fixed costs. - Inefficient Memory Access: The gather of dense inputs via
indicesresults in non-contiguous, cache-unfriendly reads, often stalling the compute pipeline. - Load Imbalance: Rows with vastly different numbers of non-zeros cause thread divergence in parallel execution, leaving some cores idle. Thus, a model with 90% weight sparsity (a 10x FLOP reduction) may only achieve a 2-3x actual speedup using generic CSR kernels, emphasizing the need for hardware-aligned sparsity patterns.
Related Sparse Formats
CSR is one of several sparse storage formats, each with trade-offs:
- CSC (Compressed Sparse Column): The column-major analogue of CSR. Optimal for operations that access columns of the sparse matrix.
- COO (Coordinate Format): Stores explicit (row, column, value) tuples. Simpler to construct but often less efficient for SpMM due to lack of row compression.
- Blocked CSR (BSR): Groups non-zeros into small dense blocks (e.g., 4x4). Improves memory access regularity and enables use of vector/SIMD units, trading some sparsity for better hardware utilization.
- Structured Sparsity Formats (e.g., 2:4): Used by NVIDIA Sparse Tensor Cores. Stores a compressed matrix of non-zero values plus a bitmask, enabling predictable, aligned memory accesses and 2x theoretical speedup on supported GPUs.
Frequently Asked Questions
The Compressed Sparse Row (CSR) format is a foundational data structure for efficiently storing and computing with sparse matrices, where most elements are zero. It is critical for executing pruned neural networks in on-device and high-performance computing environments.
The Compressed Sparse Row (CSR) format is a storage scheme for sparse matrices that compresses row index information to minimize memory overhead. It works by using three one-dimensional arrays:
values(ordata): Stores all the non-zero values, in row-major order.col_indices: Stores the column index for each corresponding non-zero value in thevaluesarray.row_ptr(orrow_offsets): Stores the cumulative count of non-zero elements up to each row. The value at indexigives the start position in thevaluesandcol_indicesarrays for rowi, androw_ptr[i+1]gives the end position.
For a matrix with M rows and N columns, and nnz non-zero elements, the memory footprint is O(nnz + M) instead of O(M * N). The row_ptr array enables fast row-wise traversal, making operations like Sparse Matrix-Vector Multiplication (SpMV) efficient, as all non-zeros for a given row are stored contiguously.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
CSR is one of several core data structures and computational primitives essential for executing pruned neural networks efficiently. These related terms define the ecosystem of sparse computation.
COO Format (Coordinate Format)
A sparse tensor storage format that explicitly stores a list of (row, column, value) tuples for each non-zero element. It offers simplicity and ease of construction but can have higher memory overhead for arithmetic operations compared to compressed formats like CSR or CSC. COO is often used as an intermediate representation before conversion to a more compute-efficient format.
Sparse Matrix Multiplication (SpMM)
The fundamental computational kernel for multiplying a sparse matrix by a dense matrix. It is the core operation in sparse linear layers and attention projections. Efficient SpMM implementations for formats like CSR must:
- Skip multiplications with zero elements.
- Efficiently gather input values using column indices.
- Scatter and accumulate partial results across rows. Performance is heavily dependent on the sparse data layout and memory access patterns.
Gather-Scatter Operations
Fundamental parallel computing primitives critical for sparse computation. Gather collects data from non-contiguous memory addresses (specified by an index array) into a contiguous vector for processing. Scatter writes a contiguous result vector back to non-contiguous addresses. In CSR-based SpMM, gather is used to fetch the dense input values corresponding to sparse column indices, and scatter is used to accumulate outputs into the correct row locations.
Sparse Tensor Core
A specialized hardware unit within modern NVIDIA GPUs (Ampere architecture and later) designed to accelerate sparse matrix operations. It leverages a structured 2:4 sparsity pattern, where in every block of 4 weights, 2 must be zero. This pattern allows the hardware to effectively double the theoretical compute throughput for dense matrix math by skipping the zero operations. While more restrictive than the unstructured sparsity stored in CSR, it represents a major hardware-in-the-loop optimization for sparse inference.
Sparse Inference Engine
A software runtime or framework component specifically designed to load and execute sparse neural network models. It contains optimized kernels (like SpMM) for target hardware (CPUs, GPUs, NPUs) that understand formats like CSR. Examples include specialized backends in TensorFlow Lite, PyTorch with torch.sparse, and proprietary vendor SDKs. The engine manages the decoding of sparse formats, memory allocation, and scheduling to maximize hardware utilization.
Sparse Efficiency Gap
The observed performance difference between the theoretical speedup predicted by the reduction in FLOPs (from zero-skipping) and the actual speedup achieved on hardware. This gap is caused by overheads inherent to sparse computation, including:
- Metadata processing: Decoding CSR row pointers and column indices.
- Irregular memory access: Leading to poor cache utilization and memory bandwidth saturation.
- Load imbalance: Where threads process rows with vastly different numbers of non-zeros. Bridging this gap is a primary goal of kernel and hardware optimization.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us