torch.linalg.inv(A, *, out=None) → Tensor

Computes the inverse of a square matrix if it exists. Throws a RuntimeError if the matrix is not invertible.

Letting K\mathbb{K} be R\mathbb{R} or C\mathbb{C}, for a matrix AKn×nA \in \mathbb{K}^{n \times n}, its inverse matrix A1Kn×nA^{-1} \in \mathbb{K}^{n \times n} (if it exists) is defined as

A1A=AA1=InA^{-1}A = AA^{-1} = \mathrm{I}_n

where In\mathrm{I}_n is the n-dimensional identity matrix.

The inverse matrix exists if and only if AA is invertible. In this case, the inverse is unique.

Supports input of float, double, cfloat and cdouble dtypes. Also supports batches of matrices, and if A is a batch of matrices then the output has the same batch dimensions.


When inputs are on a CUDA device, this function synchronizes that device with the CPU.


Consider using torch.linalg.solve() if possible for multiplying a matrix on the left by the inverse, as:

torch.linalg.solve(A, B) == A.inv() @ B

It is always prefered to use solve() when possible, as it is faster and more numerically stable than computing the inverse explicitly.

See also

torch.linalg.pinv() computes the pseudoinverse (Moore-Penrose inverse) of matrices of any shape.

torch.linalg.solve() computes A.inv() @ B with a numerically stable algorithm.


A (Tensor) – tensor of shape (*, n, n) where * is zero or more batch dimensions consisting of invertible matrices.

Keyword Arguments

out (Tensor, optional) – output tensor. Ignored if None. Default: None.


RuntimeError – if the matrix A or any matrix in the batch of matrices A is not invertible.


>>> x = torch.rand(4, 4)
>>> y = torch.linalg.inv(x)
>>> z = x @ y
>>> z
tensor([[ 1.0000, -0.0000, -0.0000,  0.0000],
        [ 0.0000,  1.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  1.0000,  0.0000],
        [ 0.0000, -0.0000, -0.0000,  1.0000]])
>>> torch.dist(z, torch.eye(4))

>>> # Batched inverse example
>>> x = torch.randn(2, 3, 4, 4)
>>> y = torch.linalg.inv(x)
>>> z = x @ y
>>> torch.dist(z, torch.eye(4).expand_as(x))

>>> x = torch.rand(4, 4, dtype=torch.cdouble)
>>> y = torch.linalg.inv(x)
>>> z = x @ y
>>> torch.dist(z, torch.eye(4, dtype=torch.cdouble))
tensor(7.5107e-16, dtype=torch.float64)


Access comprehensive developer documentation for PyTorch

View Docs


Get in-depth tutorials for beginners and advanced developers

View Tutorials


Find development resources and get your questions answered

View Resources