torch.inverse
function inverse<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(input: Tensor<S, D, Dev>): Tensor<S, D, Dev>Computes the matrix inverse: A^(-1) such that A @ A^(-1) = I.
Inverse matrix satisfying: A @ A^(-1) = A^(-1) @ A = I WARNING: Avoid using inverse to solve systems. Always prefer solve() for AX=B. Used mainly for:
- Computing pseudoinverse (via SVD)
- Analytical solutions where inverse is needed
- Computing determinant sign via LU diagonal product
- Matrix transformations in graphics/robotics
Much slower and less numerically stable than solve(). For systems AX = B, use solve(A, B) not inv(A) @ B.
- Square matrix required: Input must be n × n
- Invertibility required: det(A) ≠ 0 (must be non-singular)
- Numerical instability: Use solve() instead for systems
- O(n³) complexity: As expensive as LU decomposition
- Not for solving systems: NEVER use inv(A) B; use solve(A,B) instead
- Gradient support: Backprop through inverse is supported but can be numerically unstable
Parameters
inputTensor<S, D, Dev>- Square matrix (n × n) or batch (..., n, n) - must be invertible
Returns
Tensor<S, D, Dev>– Inverse matrix with same shape as inputExamples
// Identity inverse is identity
const I = torch.eye(3);
const I_inv = torch.inverse(I); // I_inv ≈ I
// Verify inverse property: A @ A^(-1) = I
const A = torch.randn(5, 5);
const A_inv = torch.inverse(A);
const product = A.matmul(A_inv);
// product ≈ I (within numerical precision)
// DO NOT DO THIS - inefficient and unstable!
// BAD: const X = torch.inverse(A).matmul(B);
// GOOD: const X = torch.linalg.solve(A, B);
// Analytical formula where inverse is needed
// Normal equations: (A^T A)^(-1) A^T B (less preferred than solve)
const A = torch.randn(100, 5);
const b = torch.randn(100);
const AtA = A.T.matmul(A);
const AtA_inv = torch.inverse(AtA);
// BETTER: use solve(AtA, A.T.matmul(b)) instead
// Batched inverse
const A_batch = torch.randn(32, 10, 10); // 32 matrices
const A_batch_inv = torch.inverse(A_batch); // [32, 10, 10]See Also
- PyTorch torch.inverse()
- solve - Linear system solver (PREFERRED over inverse!)
- det - Determinant (check invertibility)
- pinv - Pseudoinverse (uses SVD internally)
- lu_factor - LU decomposition (used internally)