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.Tensoris a multi-dimensional array, much like a NumPyndarray;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
PyTorch
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 torchvisionor 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.
import time
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse as sparse
import scipy.sparse.linalg as sla
import torch
torch.manual_seed(37830)
rng = np.random.default_rng(37830)
torch.__version__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.
A = torch.randn(3, 4)
x = torch.linspace(0, 1, 4)
print(A @ x)
print(A[:, 0], A.sum(dim=0))
print(A.T.shape)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.
a = np.random.rand(3)
print(torch.tensor([1.0, 2.0]).dtype)
print(torch.tensor(a).dtype)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.
a = np.zeros(3)
t = torch.from_numpy(a)
t[0] = 1.0
at.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:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type == 'cuda':
print(torch.cuda.get_device_name())
else:
print("No GPU found. In Colab, choose Runtime > Change runtime type > T4 GPU.")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 = torch.randn(1000, 1000, device=device)
x = torch.randn(1000).to(device)
y = A @ x
print(y.device)
y.cpu()[:5]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:
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.
GPUs are built for single (and lower) precision. Most are much slower in
float64than infloat32: 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 / SciPy | PyTorch | |
|---|---|---|
| solve | np.linalg.solve | torch.linalg.solve |
| LU factorization | la.lu_factor, la.lu_solve | torch.linalg.lu_factor, torch.linalg.lu_solve |
| Cholesky factorization | la.cho_factor, la.cho_solve | torch.linalg.cholesky, torch.cholesky_solve |
| triangular solve | la.solve_triangular | torch.linalg.solve_triangular |
| least squares | np.linalg.lstsq | torch.linalg.lstsq |
| QR | np.linalg.qr | torch.linalg.qr |
| symmetric eigenvalue problem | np.linalg.eigh | torch.linalg.eigh |
| general eigenvalue problem | np.linalg.eig | torch.linalg.eig |
| SVD | np.linalg.svd | torch.linalg.svd, torch.linalg.svdvals |
| norms | np.linalg.norm | torch.linalg.vector_norm, torch.linalg.matrix_norm |
| condition number, determinant | np.linalg.cond, np.linalg.slogdet | torch.linalg.cond, torch.linalg.slogdet |
| matrix exponential | la.expm | torch.linalg.matrix_exp |
| FFT | np.fft | torch.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:
n = 500
M = rng.standard_normal((n, n))
A_np = M @ M.T + n * np.eye(n) # symmetric positive definite
b_np = rng.standard_normal(n)
x_np = np.linalg.solve(A_np, b_np)
A = torch.from_numpy(A_np).to(device) # float64, on the GPU
b = torch.from_numpy(b_np).to(device)
x1 = torch.linalg.solve(A, b)
L = torch.linalg.cholesky(A)
x2 = torch.cholesky_solve(b.reshape(-1, 1), L) # note the order: right-hand side first
LU, pivots = torch.linalg.lu_factor(A)
x3 = torch.linalg.lu_solve(LU, pivots, b.reshape(-1, 1))
for name, x in [('solve', x1), ('cholesky', x2), ('lu', x3)]:
print(f"{name:8}: difference from NumPy {np.linalg.norm(x.flatten().cpu().numpy() - x_np):.1e}")The factor-and-solve routines take the right-hand side as an matrix, so that one factorization can be reused for right-hand sides at once. Decompositions return their factors in the same layout as NumPy:
evals, evecs = torch.linalg.eigh(A)
print(torch.allclose(A @ evecs, evecs * evals)) # A V = V diag(lambda)
print(torch.allclose(torch.linalg.svdvals(A), evals.flip(0))) # for SPD A, singular values = eigenvaluesA few differences from NumPy are worth knowing:
torch.linalg.eigalways returns complex tensors, even when the eigenvalues are real.On the GPU,
torch.linalg.lstsqassumes that the matrix has full rank.Routines ending in
_ex, such astorch.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 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 from random orthogonal matrices and singular values from 1 down to , and solved on the GPU:
n = 200
U, _ = np.linalg.qr(rng.standard_normal((n, n)))
V, _ = np.linalg.qr(rng.standard_normal((n, n)))
x_true = rng.standard_normal(n)
for kappa in [1e2, 1e4, 1e6, 1e8]:
A_np = U @ np.diag(np.logspace(0, -np.log10(kappa), n)) @ V.T
b_np = A_np @ x_true
errors = []
for dtype in [torch.float32, torch.float64]:
A = torch.tensor(A_np, dtype=dtype, device=device)
b = torch.tensor(b_np, dtype=dtype, device=device)
x = torch.linalg.solve(A, b).cpu().double().numpy()
errors.append(np.linalg.norm(x - x_true) / np.linalg.norm(x_true))
print(f"condition number {kappa:.0e}: relative error {errors[0]:.1e} in float32, {errors[1]:.1e} in float64")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.)
def time_op(f, device, repeat=3):
"""
best time in seconds of f() over several runs, waiting for the GPU to finish
"""
f() # warm up
times = []
for _ in range(repeat):
if device.type == 'cuda':
torch.cuda.synchronize()
start = time.perf_counter()
f()
if device.type == 'cuda':
torch.cuda.synchronize()
times.append(time.perf_counter() - start)
return min(times)
cpu = torch.device('cpu')Here is the speed of matrix multiplication in billions of floating point operations per second (GFLOP/s), counting operations for the product of two matrices, on the CPU and on the GPU in single and double precision.
sizes = [64, 128, 256, 512, 1024, 2048, 4096]
runs = [("CPU, float32", cpu, torch.float32),
("GPU, float32", device, torch.float32),
("GPU, float64", device, torch.float64)]
for label, dev, dtype in runs:
rates = []
for n in sizes:
A = torch.randn(n, n, dtype=dtype, device=dev)
B = torch.randn(n, n, dtype=dtype, device=dev)
rates.append(2 * n**3 / time_op(lambda: A @ B, dev) / 1e9)
plt.loglog(sizes, rates, 'o-', label=label)
plt.xlabel('matrix size $n$')
plt.ylabel('GFLOP/s')
plt.title('matrix multiplication')
plt.legend()
plt.show()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.
n = 4096
A_cpu, x_cpu = torch.randn(n, n), torch.randn(n)
A_gpu, x_gpu = A_cpu.to(device), x_cpu.to(device)
timings = [("A @ x on the CPU", lambda: A_cpu @ x_cpu, cpu),
("A @ A on the CPU", lambda: A_cpu @ A_cpu, cpu),
("copy A to the GPU", lambda: A_cpu.to(device), device),
("A @ x on the GPU", lambda: A_gpu @ x_gpu, device),
("A @ A on the GPU", lambda: A_gpu @ A_gpu, device)]
for name, f, dev in timings:
print(f"{name:18} {1e3 * time_op(f, dev):8.2f} ms")Batches¶
Almost every routine in torch.linalg accepts a batch of matrices: a tensor of shape (*, m, n) is treated as a stack of 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 matrices, which leaves no doubt about which dimension is the batch.
k, n = 100_000, 6
A_np = rng.standard_normal((k, n, n)) + n * np.eye(n)
b_np = rng.standard_normal((k, n, 1))
A, b = torch.from_numpy(A_np), torch.from_numpy(b_np) # on the CPU
A_gpu, b_gpu = A.to(device), b.to(device)
timings = [("Python loop over NumPy", lambda: [np.linalg.solve(A_np[i], b_np[i]) for i in range(k)], cpu),
("one NumPy call", lambda: np.linalg.solve(A_np, b_np), cpu),
("one PyTorch call, CPU", lambda: torch.linalg.solve(A, b), cpu),
("one PyTorch call, GPU", lambda: torch.linalg.solve(A_gpu, b_gpu), device)]
for name, f, dev in timings:
print(f"{name:22} {1e3 * time_op(f, dev, repeat=1):8.1f} ms")
x_loop = np.stack([np.linalg.solve(A_np[i], b_np[i]) for i in range(k)])
x_gpu = torch.linalg.solve(A_gpu, b_gpu)
print(f"largest difference between the GPU and the loop: {np.abs(x_gpu.cpu().numpy() - x_loop).max():.1e}")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 matrices on the GPU, computed one at a time and as a batch:
k, n = 1000, 64
A = torch.randn(k, n, n, device=device)
B = torch.randn(k, n, n, device=device)
t_loop = time_op(lambda: [A[i] @ B[i] for i in range(k)], device)
t_batch = time_op(lambda: A @ B, device)
print(f"on {device.type}: loop {1e3 * t_loop:.2f} ms, batch {1e3 * t_batch:.2f} ms")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 with .
m, n, r = 2000, 1000, 10
A = torch.randn(m, r, dtype=torch.float64, device=device) @ torch.randn(r, n, dtype=torch.float64, device=device)
A += 1e-2 * torch.randn(m, n, dtype=torch.float64, device=device) # rank 10 plus noise
print(f"all singular values: {time_op(lambda: torch.linalg.svdvals(A), device, repeat=1):.3f} s")
print(f"randomized SVD: {time_op(lambda: torch.svd_lowrank(A, q=r + 5, niter=2), device, repeat=1):.3f} s")
s = torch.linalg.svdvals(A)
U, S, V = torch.svd_lowrank(A, q=r + 5, niter=2)
print(f"largest relative error in the top {r} singular values: {((S[:r] - s[:r]).abs() / s[:r]).max():.1e}")Sparse Tensors¶
torch.sparse stores sparse matrices in the COO and CSR formats of Sparse Matrices. A COO tensor is built from a tensor of row and column indices and a tensor of values:
i = torch.tensor([[0, 1, 1], # row indices
[2, 0, 2]]) # column indices
v = torch.tensor([3.0, 4.0, 5.0])
S = torch.sparse_coo_tensor(i, v, size=(2, 3), check_invariants=True)
S.to_dense()Differentiating Linear Algebra¶
Every routine in torch.linalg can be differentiated with the automatic differentiation of PyTorch Neural Networks. For example, if is symmetric and its smallest eigenvalue is simple, with unit eigenvector , then .
n = 5
M = torch.randn(n, n, dtype=torch.float64)
A = M @ M.T + torch.eye(n, dtype=torch.float64)
A.requires_grad_(True)
evals, evecs = torch.linalg.eigh(A)
evals[0].backward() # gradient of the smallest eigenvalue with respect to the entries of A
v = evecs[:, 0].detach()
torch.allclose(A.grad, torch.outer(v, v))