Skip to main content

5  Cost Models and Sparse Storage

To choose between algorithms, we compare both arithmetic and storage. A matrix may be small enough to store but too expensive to factor. A sparse matrix has sufficiently few nonzero entries that storing only those entries changes the cost of its basic operations.

We count additions and multiplications for dense products, then describe storage by coordinates and by rows. These formats also show how to assemble a sparse matrix from local contributions without first allocating a dense array.

5.1 Asymptotic Notation and Operation Counts

NoteDefinition: Asymptotic Notation

Let \(f\) and \(g\) be positive functions of an integer \(n\). We write \(f(n)=O(g(n))\) if there are constants \(C>0\) and \(n_0\) such that \(f(n)\leq Cg(n)\) for every \(n\geq n_0\). We write \(f(n)=\Theta(g(n))\) if both \(f(n)=O(g(n))\) and \(g(n)=O(f(n))\) hold.

WarningExercise

Show that \(3n^2+100n+5=\Theta(n^2)\), and arrange \(5n^3+n\), \(100n^2\), \(n^2\log n\), and \(2^{10}n^2\) in order of growth.

NoteDefinition: Flop

A flop is one floating-point addition, subtraction, multiplication, division, or square root.

NoteTheorem: Costs of the Basic Dense Kernels

Let \(\bx,\by\in\fR^n\), \(\bA\in\fR^{m\times n}\), \(\bB\in\fR^{n\times p}\), and let \(\bL\in\fR^{n\times n}\) be nonsingular and lower triangular. The standard algorithms require

  1. \(2n-1\) flops for the inner product \(\bx^T\by\),

  2. \(m(2n-1)\) flops for the product \(\bA\bx\),

  3. \(mp(2n-1)\) flops for the product \(\bA\bB\),

  4. \(n^2\) flops for the solution of \(\bL\bz=\by\) by forward substitution.

We count scalar arithmetic operations and exclude assignments and index calculations.

  1. To form \(\sum_{j=1}^nx_jy_j\), first compute its \(n\) products. Adding \(n\) numbers requires \(n-1\) additions. The total is \(n+(n-1)=2n-1\) operations.

  2. Each output entry is an inner product between one row of length \(n\) and the input vector. There are \(m\) output entries. The count is therefore \(m(2n-1)\), whose leading term is \(2mn\).

  3. If \(\bA\in\fR^{m\times n}\) and \(\bB\in\fR^{n\times p}\), there are \(mp\) output entries. Each entry uses an inner product of length \(n\). Hence the count is \(mp(2n-1)\), with leading term \(2mnp\).

  4. In forward substitution, row \(i\) forms \(i-1\) products, subtracts those \(i-1\) terms from the right-hand side, and divides by the diagonal entry. The diagonal is nonzero by triangular nonsingularity. The count per row is \(2(i-1)+1\). Therefore \[ \begin{align} \sum_{i=1}^n[2(i-1)+1] =2\frac{n(n-1)}2+n=n^2. \end{align} \]

For square matrices, put \(m=n=p\) to obtain the familiar leading count \(2n^3\). These counts describe the straightforward algorithms under the stated convention.

The order of evaluation matters even when the result does not change. For \(\bA,\bB\in\fR^{n\times n}\) and \(\bx\in\fR^n\), forming \((\bA\bB)\bx\) costs about \(2n^3\) flops, whereas \(\bA(\bB\bx)\) costs about \(4n^2\) flops. The factorizations of later sections have costs of the same kind. Dense LU factorization requires about \(\tfrac23n^3\) flops (the referenced result), Cholesky about \(\tfrac13n^3\), and Householder QR of an \(m\times n\) matrix about \(2mn^2-\tfrac23n^3\).

NoteExample

(The dense barrier) At a sustained rate of \(10^{10}\) flops per second, a dense LU factorization with \(n=10^4\) requires about \(\tfrac23\cdot10^{12}\) flops, or roughly one minute. With \(n=10^5\) it requires about \(\tfrac23\cdot10^{15}\) flops, or roughly nineteen hours, and storing the matrix in double precision requires \(8\cdot10^{10}\) bytes. A finite-difference discretization on a \(300\times300\times300\) grid already has \(n\approx2.7\times10^7\) unknowns. Dense methods are therefore out of reach for such problems, and the matrix must be stored and used in a form that exploits its zero entries.

TipRemark

(Memory traffic) Flop counts ignore the cost of moving data between memory and the processor. A dense matrix–matrix product reuses each loaded entry \(O(n)\) times, and blocked implementations run close to the peak arithmetic rate. A sparse matrix–vector product performs two flops for each stored nonzero but reads at least one value and one index for it. Its running time is therefore set by memory bandwidth rather than by the flop count, and reducing the number of stored entries reduces the running time directly.

5.2 Sparse Matrix Storage

A matrix is sparse when the number of its nonzero entries, written \(\operatorname{nnz}(\bA)\), is much smaller than \(n^2\). The finite-difference Poisson matrix on an \(N\times N\) grid has \(n=N^2\) unknowns and fewer than \(5n\) nonzero entries. Stored densely, it would occupy \(n^2\) words, and a matrix–vector product would cost \(2n^2\) flops. A sparse format stores only the nonzero entries and their positions.

NoteDefinition: Coordinate and Compressed Sparse Row Formats

Let \(\bA\in\fR^{n\times n}\) have \(\operatorname{nnz}(\bA)\) nonzero entries.

  1. The coordinate (COO) format stores three arrays of length \(\operatorname{nnz}(\bA)\) that list each nonzero entry as a triplet \((i,j,a_{ij})\). The triplets may appear in any order, and repeated positions are understood to be summed.

  2. The compressed sparse row (CSR) format stores the nonzero values row by row in an array \(`val`\), their column indices in an array \(`col`\) of the same length, and an array \(`ptr`\) of length \(n+1\). The entries of row \(i\) occupy positions \(`ptr`_i,...,`ptr`_{i+1}-1\) of \(`val`\) and \(`col`\).

The arrays below use mathematical indexing, beginning at one. In a Python implementation, column indices and positions begin at zero, and the first row pointer is zero. The difference \(`ptr`_{i+1}-`ptr`_i\) counts stored entries in row \(i\) under either convention. An empty row has equal consecutive pointers.

WarningExercise

Write the COO triplets and the CSR arrays of the \(5\times5\) matrix \(\operatorname{tridiag}(-1,2,-1)\). Then compute \(\bA\bx\) for \(\bx=(1,2,3,4,5)^T\) directly from the CSR arrays.

NoteExample

The matrix \[ \begin{align} \bA=\begin{pmatrix}4&0&-1&0\\0&3&0&0\\-1&0&5&2\\0&0&2&6\end{pmatrix} \end{align} \] has eight nonzero entries. Its CSR arrays are \[ \begin{align} `val`&=(4,-1,\;3,\;-1,5,2,\;2,6), & `col`&=(1,3,\;2,\;1,3,4,\;3,4), & `ptr`&=(1,3,4,7,9). \end{align} \] Row \(3\) occupies positions \(`ptr`_3=4\) through \(`ptr`_4-1=6\).

NoteTheorem: Cost of a CSR Matrix–Vector Product

For \(\bA\) stored in CSR format, the product \(\by=\bA\bx\) computed by \[ \begin{align} y_i=\sum_{k=`ptr`_i}^{`ptr`_{i+1}-1}`val`_k\,x_{`col`_k}, \qquad i=1,...,n, \end{align} \] requires at most \(2\operatorname{nnz}(\bA)\) flops. The format stores \(2\operatorname{nnz}(\bA)+n+1\) numbers.

Consider the computation row by row. For each stored entry \(a_{ij}\), compute the product \(a_{ij}x_j\) and add it to the accumulator for output entry \(i\). This uses one multiplication and at most one addition per stored entry. Thus at most \(2\operatorname{nnz}(\bA)\) arithmetic operations are needed for the contributions.

There are also \(n\) row accumulators to initialize or write. Traversing the row pointers takes \(O(n)\) work. Consequently the complete count is \(O(\operatorname{nnz}(\bA)+n)\). In the common case of at least one stored entry in every row, \(n\leq\operatorname{nnz}(\bA)\) and the count simplifies to \(O(\operatorname{nnz}(\bA))\).

Storage consists of one value and one column index per stored entry, together with \(n+1\) row pointers. Its size is also \(O(\operatorname{nnz}(\bA)+n)\). Empty rows explain why the row-pointer term cannot be discarded without an assumption.

The CSR format is efficient for computing \(\bA\bx\) but inconvenient for constructing a matrix, because the position of an entry in \(`val`\) depends on how many entries precede it. Matrices are therefore usually assembled in COO format, where a new entry is simply appended, and converted to CSR once assembly is complete.

NoteTheorem: Conversion from COO to CSR

A matrix given by \(t\) triplets can be converted to CSR format in \(O(t+n)\) operations.

We describe an explicit algorithm. The matrix has \(n\) rows and columns, and \(t\) is the number of input triplets, including duplicates.

  1. Initialize \(n\) counters to zero. For each triplet \((i,j,a)\), increment the counter for row \(i\). Initialization costs \(O(n)\) and the pass costs \(O(t)\).

  2. Starting with \(`ptr`_1=1\), add the row counts successively. This prefix sum costs \(O(n)\) and gives the start and end positions of every row in an intermediate array of length \(t\).

  3. Keep a next-free-position counter for each row. Pass over the input again and place the column and value of each triplet in its row’s next free slot. Each placement and increment takes constant time. This pass costs \(O(t+n)\) including counter initialization.

  4. Use arrays of length \(n\) called \(`stamp`\) and \(`pos`\). When processing row \(i\), a column \(j\) has already appeared in that row exactly when \(`stamp`_j=i\). If it has appeared, add the value to output slot \(`pos`_j\). Otherwise append a new output entry and set \(`stamp`_j=i\) and \(`pos`_j\) to its slot. The row stamp avoids clearing a length-\(n\) array for each row. Each intermediate entry is examined once.

  5. There are a fixed number of passes of length \(t\), and a fixed number of arrays initialized or scanned in \(O(n)\) time. The total is \(O(t+n)\). The resulting CSR columns need not be sorted within a row. Requiring sorted column indices is an additional operation and is not included in this bound.

NoteExample

(Assembling the Poisson matrix) For the one-dimensional Poisson matrix, we append for each \(i=1,...,n\) the triplet \((i,i,2h^{-2})\), together with \((i,i-1,-h^{-2})\) when \(i>1\) and \((i,i+1,-h^{-2})\) when \(i<n\). The result has \(3n-2\) triplets and converts to CSR in \(O(n)\) operations. Finite-element matrices are assembled in the same way by looping over elements, and each element contributes a small block of triplets that overlaps the contributions of its neighbors. The overlapping triplets are summed during the conversion.

TipRemark

(Column storage and transposes) The compressed sparse column (CSC) format stores \(\bA\) column by column and is the CSR format of \(\bA^T\). Column-oriented algorithms, such as sparse Cholesky factorization and column-oriented triangular solves, use CSC. A product \(\bA^T\bx\) with a CSR matrix is computed by scattering \(x_i\,`val`_k\) into position \(`col`_k\) of the result. The scatter has the same flop count as the CSR product, but parallel threads that process different rows may then write to the same output entry.

5.3 Further Exercises

WarningExercise

Count the flops and the memory reads of the CSR product in the referenced result, assuming 8-byte values and 4-byte indices. Compute the ratio of flops to bytes read, and explain why this ratio makes the product limited by memory bandwidth.

WarningExercise

Write the scatter algorithm for \(\bA^T\bx\) from CSR arrays, and prove that it costs at most \(2\operatorname{nnz}(\bA)\) flops.

WarningExercise

Assemble the five-point Poisson matrix on an \(N\times N\) grid in COO format, convert it to CSR, and compare the time of a sparse and a dense matrix–vector product for \(N=50,100,200\). Report \(\operatorname{nnz}\), the storage of both formats, and the two times.