matrix_exp and matrix_exp_frechet#
The matrix exponential extends e**x to square matrices:
exp(A) = I + A + A**2/2! + A**3/3! + .... It solves systems of linear
differential equations (x' = A x has the solution x(t) = exp(t A) x(0)),
turns rotation generators into rotations, and gives the transition
probabilities of continuous-time Markov chains. Its Frechet derivative says
how exp(A) changes when A moves a little in a direction E, which is
what a gradient through the matrix exponential needs. Implementations differ
widely: truncated Taylor or Pade series of any degree, with any number of
scaling and squaring steps.
In ExactRef, er.matrix_exp(A), also
er.linalg.matrix_function.matrix_exp, is the exponential of each
square matrix in A, as in torch.linalg.matrix_exp.
er.matrix_exp_frechet(A, E), also
er.linalg.matrix_function.matrix_exp_frechet, is its Frechet
derivative at A in the direction E. Both take real or complex inputs, and
the output can be any format of their kind. To check
another implementation's output against them, use covers(), as in
Checking PyTorch below.
Each result holds the reference, the exact answer rounded once to
the output format. Their tolerance, per element how far a correct
implementation's output can be from the reference, works differently from
the other operations'. It is a backward error: a correct result is
exp(A + dA) for a small dA, the exact exponential of a slightly changed
input, rounded to the compute format (the format an implementation
computes in: float32 by default for inputs narrower than float32, else the
input format) and then to the output format. ExactRef bounds the error this
way because matrix exponential algorithms share no required rounding step (a
boundary) it could bound one by one. Neither operation has a
normal answer, the exactly emulated output of an ordinary
implementation that normal() gives for the other operations.
Guarantees and limits gives
the bound on dA, the matrices it was measured on, and the implementations
known to exceed it.
Every input within the allowed dA of A maps to a result near exp(A).
A correct result is any of them, rounded to the output format.
Arguments#
Argument |
Meaning |
Default |
|---|---|---|
|
square matrices, shape |
required |
|
the direction, with |
required |
|
the output format, of the same kind as the inputs |
the input format |
|
the rounding mode of the reference and of a correct implementation's final rounding into the output format |
|
|
what a result past the output format's range becomes: |
each format's own rule |
|
the number of threads the call computes on; no result depends on it |
the performance cores on Apple Silicon, else the physical cores, as PyTorch picks |
Examples#
An orthogonal weight parametrization keeps a layer's weight orthogonal by
storing a skew-symmetric matrix A and using exp(A) as the weight. Here
the weight is 64 by 64, in float32:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# A skew-symmetric matrix: the lower triangle of s, minus its transpose
s = torch.randn(64, 64, generator=g) / 8
A = s.tril(-1) - s.tril(-1).T
# ExactRef's result for the weight exp(A)
m = er.matrix_exp(A)
# Row 0's first three entries, each the exact value rounded once to float32
print("rounded:", m.rounded.tolist()[0][:3])
# The largest tolerance of any entry
print("largest tolerance:", max(m.tolerance().scalars()))
# ulps=4 allows a dA 4 times as large
print("ulps=4:", max(m.tolerance(ulps=4).scalars()))
rounded: [0.5337195992469788, -0.17420010268688202, 0.013758311979472637]
largest tolerance: 0.00013517588376998901
ulps=4: 0.0005408450961112976
ulps (default 1) scales the allowed size of dA. For the other
operations, tolerance(standard="any_order") is a wider tolerance that
covers any order of additions; for the matrix exponential it gives the same
tolerance as the default.
Batches and complex matrices#
A continuous-time Markov chain with rate matrix Q moves from state i to
state j in time t with probability exp(Q t)[i, j]. DNA substitution
models use such a chain on the 4 nucleotides, and evaluate it for many
branch lengths t at once, as a batch:
# Rates between the nucleotides A, C, G, and T: transitions (A and G, C and T)
# twice as fast as the others, each row summing to 0
frequencies = [0.3, 0.2, 0.2, 0.3]
transitions = {(0, 2), (2, 0), (1, 3), (3, 1)}
Q = [[(2.0 if (i, j) in transitions else 1.0) * frequencies[j] if i != j else 0.0
for j in range(4)] for i in range(4)]
for i in range(4):
Q[i][i] = -sum(Q[i])
# Q t for 4 branch lengths, as one batch of 4x4 float64 matrices
lengths = [0.1, 0.5, 1.0, 2.0]
batch = torch.tensor([[[rate * t for rate in row] for row in Q] for t in lengths],
dtype=torch.float64)
# The transition probabilities for every branch length
P = er.matrix_exp(batch)
# The probability that an A is still an A after each branch
for t, matrix in zip(lengths, P.rounded.tolist()):
print(f"t={t}: P(A -> A) = {matrix[0][0]:.4f}")
t=0.1: P(A -> A) = 0.9157
t=0.5: P(A -> A) = 0.6709
t=1.0: P(A -> A) = 0.4996
t=2.0: P(A -> A) = 0.3605
Complex matrices work the same way. In quantum mechanics, exp(-i H t)
evolves a state under the Hamiltonian H. Here a particle hops between
neighbors on a chain of 16 sites:
# The chain's Hamiltonian: -1 between neighboring sites
H = torch.zeros(16, 16, dtype=torch.complex128)
for i in range(15):
H[i, i + 1] = H[i + 1, i] = -1
# exp(-i H t) for 4 times, as one batch of complex128 matrices
times = [0.5, 1.0, 2.0, 4.0]
U = er.matrix_exp(torch.stack([-1j * t * H for t in times]))
# The probability that a particle that starts at site 0 is there at time t
for t, matrix in zip(times, U.rounded.tolist()):
print(f"t={t}: {abs(matrix[0][0]) ** 2:.4f}")
t=0.5: 0.7746
t=1.0: 0.3326
t=2.0: 0.0011
t=4.0: 0.0034
Special values#
A training step that diverges can leave an infinity or a NaN in a parameter. Any non-finite entry makes the whole matrix NaN:
# The skew-symmetric matrix from the first example, with one infinite entry
broken = A.clone()
broken[3, 5] = float("inf")
# Is every entry of the exponential NaN?
print("all NaN:", all(value != value for value in er.matrix_exp(broken).rounded.scalars()))
all NaN: True
Limits#
ExactRef raises its working precision until it knows which way each entry
rounds, up to 8192 bits. An entry that needs more raises
er.ReferenceUnavailableError: one very close to where the rounding switches
from one output value to the next, the entries of an ill-conditioned matrix,
or an entry far below the largest entries of its row or column, such as
e**-20000 next to 1/20000 in exp([[-20000, 1], [0, 0]]). Past about
6600 by 6600 real, or 3300 by 3300 complex, matrices reach the cap at less
precision, and a matrix that is not diagonal with ||A||_inf of about
2**60 or more raises too. matrix_exp_frechet and the backward work on a
block matrix twice the size, so their size limits are half these.
Checking PyTorch#
To check an implementation, pass its output to covers(). Here it checks
PyTorch's weight from the first example, and a batch of 64 by 64 float64
matrices whose norms run from about 0.8 to 380, so that algorithms take from
none to many scaling and squaring steps:
# Could a correct implementation produce PyTorch's float32 weight? covers()
# answers per element, and all() asks whether every element is covered.
print("float32 covered:", m.covers(torch.linalg.matrix_exp(A)).all())
# Four random 64x64 float64 matrices, scaled to different norms
scales = torch.tensor([0.1, 1.0, 10.0, 50.0], dtype=torch.float64)[:, None, None]
matrices = torch.randn(4, 64, 64, generator=g, dtype=torch.float64) / 8 * scales
reference = er.matrix_exp(matrices)
print("float64 covered:", reference.covers(torch.linalg.matrix_exp(matrices)).all())
float32 covered: True
float64 covered: True
Backward#
er.matrix_exp.backward(A, grad) returns
grad_A = matrix_exp_frechet(A^H, grad), which is what PyTorch computes.
The result holds it as a named output, and gb["grad_A"] reads it as a
result of its own. Here it checks PyTorch's autograd for an orthogonal parametrization's
32 by 32 skew-symmetric matrix, given the gradient of the weight:
# The skew-symmetric matrix, and the gradient of the weight exp(A32)
s32 = torch.randn(32, 32, generator=g) / 8
A32 = s32.tril(-1) - s32.tril(-1).T
grad = torch.randn(32, 32, generator=g)
# PyTorch's autograd, on a copy that records gradients
A32_ = A32.clone().requires_grad_()
torch.linalg.matrix_exp(A32_).backward(grad)
# ExactRef's gradient, held by name
gb = er.matrix_exp.backward(A32, grad)
print("covered:", gb["grad_A"].covers(A32_.grad).all())
covered: True
matrix_exp_frechet#
matrix_exp_frechet(A, E) is the derivative of exp(A) in the direction
E: the top-right block of exp([[A, E], [0, A]]). It says how a result
changes when its input does. For the DNA model above, the direction E that
raises the rate from A to C by 1, and lowers A's diagonal entry to match,
gives how fast the transition probabilities from A change with that rate, at
branch length 1:
# The direction: A -> C up by 1, and A's diagonal down by 1, so the row still sums to 0
E = [[0.0] * 4 for _ in range(4)]
E[0][1], E[0][0] = 1.0, -1.0
# The derivative of exp(Q) in the direction E, at t = 1
Q64, E64 = (torch.tensor(m, dtype=torch.float64) for m in (Q, E))
L = er.matrix_exp_frechet(Q64, E64)
# How fast each probability from A changes: to A, C, G, and T
print("row A:", [f"{value:.4f}" for value in L.rounded.tolist()[0]])
row A: ['-0.3821', '0.3652', '-0.0337', '0.0506']
A faster A to C rate makes an A less likely to stay an A and more likely to
become a C, and changes the chances of G and T a little, through the paths
between the states. matrix_exp_frechet has no backward of its own.
Full specification#
er.matrix_exp#
- matrix_exp(A, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Exponential of each square matrix in
A(shape(..., n, n)), real or complex.Every entry is the exact value correctly rounded to
dtype, which must be of the input's kind (convert across kinds withasarray(x, d)first). Entries are rounded from certified enclosures (exactref's interval matrix exponential), refined until both ends round alike. Each part of an entry is rational or transcendental (Lindemann-Weierstrass). A transcendental part is never on a rounding boundary, so refining it ends; a rational part can be, so parts still unrounded after the first refinements are tested for being rational with exact arithmetic, and rational parts are rounded from their exact values. An exact zero is +0, or -0 when rounding toward -inf. Any non-finite entry makes the whole matrix NaN.tolerance()uses a backward-error model, because no internal boundary is shared by all algorithms (Taylor or Pade, any degree, any number of squarings): the computed result isexp(A + dA)with||dA||_inf <= ulps * (n + 16) * u * max(||A||_inf, 1)(ulpsdefaults to 1,uis the compute format's unit roundoff; n and 16 count the roundings of an algorithm's inner products and its others, and the floor of 1 covers the rounding of exp(A)'s identity part, which every algorithm makes), rounded to the compute format and then todtype. This is an assumption, measured on random Gaussian, symmetric, non-normal and skew-symmetric matrices (n = 2 to 64,||A||_inf0.03 to 512): Higham's 2005 scaling and squaring with its degree-13 Pade approximant, and PyTorch'smatrix_exp, stay within half of it. Outside it lie: near a multiple of the identity with eigenvalues near +-5.37 * 2**s, that Pade formula's own rounding (up to about 3 times) and PyTorch's float32 results (up to about 6 times, for negative eigenvalues); PyTorch's own results at small norms (float64 near 0.03, float32 up to 1); andscipy.linalg.expm1.18.1 for some float64 matrices from||A||_inf4. There the reference matches mpmath at high precision.Amay also be an earlier result, asResultdescribes: the model then holds for every A within its tolerance.Limits: an irrational part whose rounding needs more than 8192 bits of precision (one very close to a rounding boundary, the entries of an ill-conditioned matrix, or a part far below the largest entries of its row or column, such as e**-20000 next to 1/20000 in exp([[-20000, 1], [0, 0]]), even where it rounds to 0) raises ReferenceUnavailableError, and so does a part still undecided at the most precision the reference's products hold for the matrix's size, less than 8192 bits from about 6600 x 6600 real or 3300 x 3300 complex matrices; so does a matrix with ||A||_inf of 2**60 or more (or just below, where its bound reaches 2**60) that is not diagonal, whose exponential's exponents are past the reference's range.
er.matrix_exp.backward#
- backward(A, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
matrix_exp(A)for the output gradientgrad.grad_A = matrix_exp_frechet(A^H, grad)(^H: conjugate transpose), which is what PyTorch computes.gradmust have A's shape and dtype.Aandgradmay also be earlier results.Limits: an irrational part whose rounding needs more than 8192 bits of precision (one very close to a rounding boundary, the entries of an ill-conditioned matrix, or a part far below the largest entries of its row or column, such as e**-20000 next to 1/20000 in exp([[-20000, 1], [0, 0]]), even where it rounds to 0) raises ReferenceUnavailableError, and so does a part still undecided at the most precision the reference's products hold for the matrix's size, less than 8192 bits from about 6600 x 6600 real or 3300 x 3300 complex matrices; so does a matrix with ||A||_inf of 2**60 or more (or just below, where its bound reaches 2**60) that is not diagonal, whose exponential's exponents are past the reference's range; the sizes and the norm above are those of the block matrix [[A^H, grad'], [0, A^H]], 2n x 2n, grad' = grad scaled by a power of two to within a factor of 2 of max(||A||_inf, 1), or, where ||A||_inf reaches 2**57, only scaled down, below 2**57.
er.matrix_exp_frechet#
- matrix_exp_frechet(A, E, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Frechet derivative of the matrix exponential at
Ain the directionE.L = d/dt exp(A + t E)att = 0, for each square matrix inAandE(shape(..., n, n), the same for both), real or complex.Lis the top-right block ofexp([[A, E], [0, A]]), so this ismatrix_expof that 2n x 2n block matrix, restricted to the block (a proxy): every entry is correctly rounded once todtype(of the inputs' kind, as inmatrix_exp), andexactandtolerance()arematrix_exp's for those entries. The tolerance ismatrix_exp's backward-error model on the block matrix, which is how PyTorch computesmatrix_exp's backward.AandEmay also be earlier results.Limits: an irrational part whose rounding needs more than 8192 bits of precision (one very close to a rounding boundary, the entries of an ill-conditioned matrix, or a part far below the largest entries of its row or column, such as e**-20000 next to 1/20000 in exp([[-20000, 1], [0, 0]]), even where it rounds to 0) raises ReferenceUnavailableError, and so does a part still undecided at the most precision the reference's products hold for the matrix's size, less than 8192 bits from about 6600 x 6600 real or 3300 x 3300 complex matrices; so does a matrix with ||A||_inf of 2**60 or more (or just below, where its bound reaches 2**60) that is not diagonal, whose exponential's exponents are past the reference's range; the sizes and the norm above are those of the block matrix [[A, E'], [0, A]], 2n x 2n, E' = E scaled by a power of two to within a factor of 2 of max(||A||_inf, 1), or, where ||A||_inf reaches 2**57, only scaled down, below 2**57.
See also#
PyTorch equivalents:
torch.linalg.matrix_expand its gradient.The proofs: matrix_exp.md and matrix_exp_frechet.md.