Skip to content
fn

qr

→Tensor
qr(A: Tensor, mode: str = 'reduced')

Implementing kernel

C++ engine symbols that back this Python API.

QR decomposition of a matrix.

Factorizes a matrix A∈Rm×nA \in \mathbb{R}^{m \times n} as

A = Q R,A \,=\, Q\,R,

where QQ has orthonormal columns (Q⊤Q=IQ^\top Q = I) and RR is upper-triangular. Used for orthogonalizing a basis, solving least-squares (min⁡∥Ax−b∥2\min \|Ax - b\|_2), and computing eigenvalues via QR iteration.

Parameters

Input matrix of shape (*, m, n).
mode(reduced, complete, r)= "reduced"
"reduced" (default): QQ is (m, k) and RR is (k, n) with k=min⁡(m,n)k = \min(m, n). "complete": QQ is (m, m) and RR is (m, n). "r": return only RR (Q is an empty tensor).

Returns

Tensor

Orthogonal factor.

Notes

Computed via Householder reflections (LAPACK geqrf). Cost is O(2mn2−23n3)O(2 m n^2 - \tfrac{2}{3} n^3) for m≥nm \ge n.

The diagonal of RR may carry arbitrary signs (LAPACK convention) — the factorization is unique only up to a diagonal sign matrix. Backward routes RR through a Cholesky of A⊤AA^\top A (sign-robust) and QQ through the Stiefel-manifold tangent projection. A wide input (m<nm < n) splits as A=[X∣Y]A = [X \mid Y], R=[U∣V]R = [U \mid V]: X=QUX = QU is differentiated as a square QR and V=Q⊤YV = Q^\top Y carries the rest. With mode="complete" and m>nm > n, the extra columns of QQ are not a function of AA, so a backward that reaches QQ raises RuntimeError (as the reference does); RR alone still differentiates.

Examples

>>> import lucid
>>> from lucid.linalg import qr
>>> A = lucid.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>> Q, R = qr(A)
>>> lucid.allclose(Q.T @ Q, lucid.eye(2), atol=1e-5)   # Q is orthonormal
True

Used by 3