Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Linear Algebra in PyTorch

Open in Colab

PyTorch is best known as a library for deep learning, but underneath it is an array library. The best way to think about PyTorch is that it’s NumPy + GPU + automatic differentiation:

  • a torch.Tensor is a multi-dimensional array, much like a NumPy ndarray;

  • tensors can live on a GPU, and operations on them then run on the GPU;

  • PyTorch can differentiate any computation built from tensor operations.

We first use PyTorch as a linear algebra library. The module torch.linalg covers most of numpy.linalg and several of the dense routines in scipy.linalg, every routine works on a whole batch of matrices at once, and the same code runs on a CPU or a GPU.

The PyTorch documentation lists every function. The tutorials are focused on deep learning.

Deep Learning Libraries

The most common deep learning libraries for Python are

All of them provide arrays that can live on a GPU, automatic differentiation, and building blocks for neural networks. PyTorch is the most widely used in research, and it is the one we’ll use.

Running PyTorch

The PyTorch notes are meant to be run in Google Colab (use the button at the top of the page), which has PyTorch installed and provides an NVIDIA GPU free of charge. Choose the GPU before running anything: Runtime → Change runtime type → T4 GPU.

To run them on your own computer instead, install PyTorch, together with the torchvision package used in PyTorch Neural Networks, with

(pycourse) $ conda install pytorch torchvision

or with pip install torch torchvision (see the installation page for the versions that use an NVIDIA GPU). Without an NVIDIA GPU, the code below falls back to the CPU.

Tensors

PyTorch tensors are created and used much like NumPy arrays. Most NumPy functions have a PyTorch counterpart with the same name (torch.zeros, torch.linspace, torch.eye, torch.randn, ...), and indexing, slicing, broadcasting, and @ work the same way. Reductions take dim= where NumPy takes axis=, though PyTorch accepts either.

Data types. PyTorch’s default floating point type is float32 (single precision), while NumPy’s is float64 (see Bits, Bytes, and Numbers). A tensor made from a NumPy array keeps the array’s data type.

To make double precision the default for a whole notebook, call torch.set_default_dtype(torch.float64).

Converting to and from NumPy. torch.tensor(a) copies the data. torch.from_numpy(a) and t.numpy() share the same memory as numpy array, so changing one changes the other.

t.numpy() only works for a tensor on the CPU that does not track gradients; t.detach().cpu().numpy() always works.

Devices

Every tensor lives on a device, either the CPU or a GPU. PyTorch calls NVIDIA GPUs 'cuda'. The usual idiom picks the GPU when there is one:

Move a tensor with .to(device) (.cuda() and .cpu() are shorthands), or create it there with the device argument. The operands of an operation must be on the same device, and the result stays there until you move it back.

A GPU has thousands of simple arithmetic units and its own memory (16 GB on a T4). Two things to know before using one for scientific computing:

  1. Copying data between the CPU and the GPU is slow compared with computing on either one. Move the data once, do as much work as you can on the GPU, and move the results back at the end.

  2. GPUs are built for single (and lower) precision. Most are much slower in float64 than in float32: the T4 is 32 times slower, as we’ll measure below, while data center GPUs built for scientific computing, such as the A100, narrow the gap to a factor of 2.

Linear Algebra Routines

torch.linalg follows numpy.linalg and adds several routines from scipy.linalg (imported as la in Dense Linear Algebra in NumPy and SciPy):

NumPy / SciPyPyTorch
solve Ax=bAx = bnp.linalg.solvetorch.linalg.solve
LU factorizationla.lu_factor, la.lu_solvetorch.linalg.lu_factor, torch.linalg.lu_solve
Cholesky factorizationla.cho_factor, la.cho_solvetorch.linalg.cholesky, torch.cholesky_solve
triangular solvela.solve_triangulartorch.linalg.solve_triangular
least squaresnp.linalg.lstsqtorch.linalg.lstsq
QRnp.linalg.qrtorch.linalg.qr
symmetric eigenvalue problemnp.linalg.eightorch.linalg.eigh
general eigenvalue problemnp.linalg.eigtorch.linalg.eig
SVDnp.linalg.svdtorch.linalg.svd, torch.linalg.svdvals
normsnp.linalg.normtorch.linalg.vector_norm, torch.linalg.matrix_norm
condition number, determinantnp.linalg.cond, np.linalg.slogdettorch.linalg.cond, torch.linalg.slogdet
matrix exponentialla.expmtorch.linalg.matrix_exp
FFTnp.ffttorch.fft

All of them run on the GPU. Here is a symmetric positive definite system solved three ways on the GPU and checked against NumPy:

The factor-and-solve routines take the right-hand side as an n×kn \times k matrix, so that one factorization can be reused for kk right-hand sides at once. Decompositions return their factors in the same layout as NumPy:

A few differences from NumPy are worth knowing:

  • torch.linalg.eig always returns complex tensors, even when the eigenvalues are real.

  • On the GPU, torch.linalg.lstsq assumes that the matrix has full rank.

  • Routines ending in _ex, such as torch.linalg.cholesky_ex, return an error code instead of raising an exception, which is handy when a batch of matrices (see below) contains a few bad ones.

Precision

The relative error in the solution of a linear system is roughly the condition number κ(A)\kappa(A) times the machine epsilon, which is about 10-7 in single precision and 10-16 in double precision. Here are systems with prescribed condition numbers, built as A=UΣVTA = U \Sigma V^T from random orthogonal matrices U,VU, V and singular values from 1 down to 1/κ1/\kappa, and solved on the GPU:

In single precision, a condition number of 106 leaves about two correct digits, and at 108 none are left. Deep learning can live with single precision, and even with 16-bit formats that keep only 2 or 3 significant digits, because the data are noisy and training only needs approximate gradients. Many scientific computations cannot.

When Does the GPU Pay Off?

GPU operations are asynchronous: Python queues the work on the GPU and moves on without waiting for it to finish. To time GPU code we have to wait with torch.cuda.synchronize() before reading the clock. The first call of an operation also pays one-time setup costs, so we run it once before timing. (The module torch.utils.benchmark does all of this more carefully.)

Here is the speed of matrix multiplication in billions of floating point operations per second (GFLOP/s), counting 2n32n^3 operations for the product of two n×nn \times n matrices, on the CPU and on the GPU in single and double precision.

For small matrices the GPU is no faster than the CPU, or slower. Every operation pays a fixed cost to launch work on the GPU, and that cost dominates when there is little arithmetic to do.

For large matrices the GPU is many times faster in single precision, and the gap between the two GPU curves is the price of double precision.

Batches

Almost every routine in torch.linalg accepts a batch of matrices: a tensor of shape (*, m, n) is treated as a stack of m×nm \times n matrices, and the routine is applied to each of them. @ broadcasts over the batch dimensions in the same way. The batch index comes first, so that each matrix is contiguous in memory (Memory and Performance).

Here we solve 100,000 small linear systems with a Python loop and with a single call, on the CPU and on the GPU. The right-hand sides have shape (k, n, 1), a batch of n×1n \times 1 matrices, which leaves no doubt about which dimension is the batch.

NumPy’s linalg functions also accept stacks of matrices, and either way the single call is much faster than the loop. On the GPU, a batch is also how you give thousands of arithmetic units enough work. Batches of small problems come up all the time: one small system per element of a finite element mesh, per particle, per pixel, or per sample of a statistical model.

Here are 1000 products of 64×6464 \times 64 matrices on the GPU, computed one at a time and as a batch:

On a GPU the loop pays the launch cost a thousand times and the batch pays it once. (On a CPU the gap is smaller.)

Randomized SVD

For a large matrix we often want only a few singular values or eigenvalues. torch.svd_lowrank implements the randomized SVD from Sparse Linear Algebra: q is the number of random vectors (the target rank plus some oversampling) and niter is the number of power iterations. It returns U,S,VU, S, V with A≈Udiag⁡(S)VTA \approx U \operatorname{diag}(S) V^T.

Sparse Tensors

torch.sparse stores sparse matrices in the COO and CSR formats of Sparse Matrices. A COO tensor is built from a 2×nnz2 \times \text{nnz} tensor of row and column indices and a tensor of values:

Differentiating Linear Algebra

Every routine in torch.linalg can be differentiated with the automatic differentiation of PyTorch Neural Networks. For example, if AA is symmetric and its smallest eigenvalue λ1\lambda_1 is simple, with unit eigenvector v1v_1, then ∂λ1/∂A=v1v1T\partial \lambda_1 / \partial A = v_1 v_1^T.