Skip to main content

ruxla_core/lax/
linalg.rs

1//! Linear algebra following `jax.lax.linalg`: decompositions of batches of
2//! matrices (`[..., m, n]`, batch dimensions first) of `f32`, `f64`, `c64`, or
3//! `c128`. For complex matrices, transposes are conjugate transposes
4//! (`cholesky` gives `x = l l^H`, `eigh` takes Hermitian matrices and gives
5//! real eigenvalues, and `svd` gives real singular values and `vt = v^H`), and
6//! eigenvectors and singular vectors are defined up to a phase rather than a
7//! sign.
8//!
9//! The functions bind the primitives as JAX's do (with the same
10//! symmetrization and masking around them), so traced programs have JAX's
11//! jaxprs. On the native backend they run the kernels of
12//! `ruxla_kernels::linalg`; compiled by XLA, ruxla's FFI handlers (or, in
13//! JAX, the LAPACK and cuSOLVER calls JAX itself makes).
14
15use ruxla_ir::Shape;
16
17use crate::backend::Backend;
18use crate::control::while_loop;
19use crate::value::{Array, Bool, I32, LinalgFloat, LinalgScalar};
20use crate::{jnp, lax};
21pub use ruxla_ir::{EighImplementation, SvdAlgorithm};
22
23pub use ruxla_kernels::linalg::TriangularSolveOptions;
24
25/// The singular value decomposition `(u, s, vt)` of [`svd`], with real
26/// singular values `s`.
27pub type Svd<B, T> = (
28    Array<B, T>,
29    Array<B, <T as crate::Element>::Real>,
30    Array<B, T>,
31);
32
33/// Checks that `x` is a batch of matrices, and returns `(rows, cols)`.
34#[track_caller]
35fn matrix_dims<B: Backend, T: LinalgScalar>(op: &str, x: &Array<B, T>) -> (usize, usize) {
36    let shape = x.shape();
37    let rank = shape.rank();
38    assert!(
39        rank >= 2,
40        "{op} needs a matrix or a batch of matrices, got shape [{shape}]"
41    );
42    (shape[rank - 2], shape[rank - 1])
43}
44
45/// `x` with its last two dimensions swapped (JAX's `_T`).
46pub(crate) fn mt<B: Backend, T: crate::Element>(x: &Array<B, T>) -> Array<B, T> {
47    let rank = x.ndim();
48    let mut perm: Vec<usize> = (0..rank).collect();
49    perm.swap(rank - 2, rank - 1);
50    x.transpose(&perm)
51}
52
53/// `(x + x^T) / 2` (JAX's `symmetrize`).
54/// The conjugate transpose of the last two dimensions (JAX's `_H`; the
55/// transpose for real matrices).
56pub(crate) fn adjoint<B: Backend, T: LinalgScalar>(x: &Array<B, T>) -> Array<B, T> {
57    let t = mt(x);
58    if T::DTYPE.is_complex() {
59        Array(B::a_conj::<T>(&t.0))
60    } else {
61        t
62    }
63}
64
65pub(crate) fn symmetrize<B: Backend, T: LinalgScalar>(x: &Array<B, T>) -> Array<B, T> {
66    let two = ruxla_kernels::cast::<f64, T>(2.0);
67    (x + adjoint(x)) / two
68}
69
70/// The mask `i + k >= j` of the matrices of `shape`, broadcast to the
71/// batch (JAX's `_tri` with `i64` indices).
72pub(crate) fn tri<B: Backend>(shape: &Shape, k: i64) -> Array<B, bool> {
73    let rank = shape.rank();
74    let (n, m) = (shape[rank - 2], shape[rank - 1]);
75    let i = lax::iota::<B, i64>([n, m], 0) + k;
76    let j = lax::iota::<B, i64>([n, m], 1);
77    let mask = i.ge(&j);
78    if rank == 2 {
79        mask
80    } else {
81        lax::broadcast_in_dim(&mask, shape.clone(), &[rank - 2, rank - 1])
82    }
83}
84
85/// The elements on and below diagonal `k` (JAX's `_tril`).
86pub(crate) fn tril<B: Backend, T: LinalgScalar>(x: &Array<B, T>, k: i64) -> Array<B, T> {
87    let shape = x.shape();
88    let mask = tri::<B>(&shape, k);
89    let zeros = crate::jnp::zeros::<B, T>(shape);
90    lax::select_array(&mask, x, &zeros)
91}
92
93/// The Cholesky factor `L` of each symmetric positive definite matrix
94/// (`x = L L^T`, `L` lower triangular), as `lax.linalg.cholesky`.
95///
96/// With `symmetrize_input`, `x` is replaced by `(x + x^T) / 2` first, which
97/// gives better derivatives; otherwise only its lower triangle is read.
98/// Matrices that are not positive definite give NaNs.
99///
100/// # Panics
101///
102/// Panics if `x` is not a batch of square matrices.
103///
104/// # Examples
105///
106/// ```
107/// use ruxla_core::{Array, Native, lax};
108///
109/// let a = Array::<Native, f64>::from_vec(vec![4.0, 2.0, 2.0, 5.0], [2, 2]);
110/// let l = lax::linalg::cholesky(&a, true);
111/// assert_eq!(l.to_vec(), [2.0, 0.0, 1.0, 2.0]);
112/// ```
113#[track_caller]
114pub fn cholesky<B: Backend, T: LinalgScalar>(
115    x: &Array<B, T>,
116    symmetrize_input: bool,
117) -> Array<B, T> {
118    matrix_dims("cholesky", x);
119    let x = if symmetrize_input {
120        symmetrize(x)
121    } else {
122        x.clone()
123    };
124    let l = Array(B::cholesky::<T>(&x.0));
125    tril(&l, 0)
126}
127
128/// Solves `op(a) x = b` (`left_side`) or `x op(a) = b` for `x`, where `a`
129/// is triangular, as `lax.linalg.triangular_solve` (whose defaults are
130/// those of [`TriangularSolveOptions::default`]). Only the triangle of `a`
131/// given by `lower` is read, without the diagonal for `unit_diagonal`.
132///
133/// # Panics
134///
135/// Panics if the shapes do not match (`a` is `[..., k, k]` and `b` is
136/// `[..., k, n]` on the left side or `[..., m, k]` on the right, with the
137/// same batch dimensions).
138///
139/// # Examples
140///
141/// ```
142/// use ruxla_core::{Array, Native, lax};
143/// use ruxla_core::lax::linalg::TriangularSolveOptions;
144///
145/// let a = Array::<Native, f32>::from_vec(vec![2.0, 0.0, 1.0, 4.0], [2, 2]);
146/// let b = Array::<Native, f32>::from_vec(vec![2.0, 9.0], [2, 1]);
147/// let options = TriangularSolveOptions {
148///     left_side: true,
149///     lower: true,
150///     ..Default::default()
151/// };
152/// let x = lax::linalg::triangular_solve(&a, &b, options);
153/// assert_eq!(x.to_vec(), [1.0, 2.0]);
154/// ```
155#[track_caller]
156pub fn triangular_solve<B: Backend, T: LinalgScalar>(
157    a: &Array<B, T>,
158    b: &Array<B, T>,
159    options: TriangularSolveOptions,
160) -> Array<B, T> {
161    Array(B::triangular_solve::<T>(&a.0, &b.0, options))
162}
163
164/// The LU factorization with partial pivoting of each matrix, as
165/// `lax.linalg.lu`: the factors (`L` below the diagonal, with an implicit
166/// unit diagonal, and `U`), the pivots (`i32[..., min(m, n)]`: row `i` was
167/// swapped with row `pivots[i]`), and the permutation (`i32[..., m]`), with
168/// `a[perm] = L U`.
169///
170/// # Panics
171///
172/// Panics if `x` is not a batch of matrices.
173///
174/// # Examples
175///
176/// ```
177/// use ruxla_core::{Array, Native, lax};
178///
179/// let a = Array::<Native, f64>::from_vec(vec![1.0, 2.0, 4.0, 2.0], [2, 2]);
180/// let (lu, pivots, perm) = lax::linalg::lu(&a);
181/// assert_eq!(lu.to_vec(), [4.0, 2.0, 0.25, 1.5]);
182/// assert_eq!(pivots.to_vec(), [1, 1]);
183/// assert_eq!(perm.to_vec(), [1, 0]);
184/// ```
185#[track_caller]
186pub fn lu<B: Backend, T: LinalgScalar>(
187    x: &Array<B, T>,
188) -> (Array<B, T>, Array<B, i32>, Array<B, i32>) {
189    matrix_dims("lu", x);
190    let (lu, pivots, perm) = B::lu::<T>(&x.0);
191    (Array(lu), Array(pivots), Array(perm))
192}
193
194/// Converts the pivots of [`lu`] to a permutation of `permutation_size`
195/// elements, as `lax.linalg.lu_pivots_to_permutation`.
196///
197/// # Panics
198///
199/// Panics if `pivots` is a scalar or has more pivots than
200/// `permutation_size`.
201#[track_caller]
202pub fn lu_pivots_to_permutation<B: Backend>(
203    pivots: &Array<B, i32>,
204    permutation_size: usize,
205) -> Array<B, i32> {
206    Array(B::lu_pivots_to_permutation(&pivots.0, permutation_size))
207}
208
209/// The QR decomposition of each matrix, as `lax.linalg.qr`: `q` with
210/// orthonormal columns and an upper triangular `r` (`x = q r`), with the
211/// signs of LAPACK's Householder reflectors. With `full_matrices`, `q` is
212/// `[..., m, m]` and `r` is `[..., m, n]`; otherwise `[..., m, k]` and
213/// `[..., k, n]` for `k = min(m, n)`.
214///
215/// # Panics
216///
217/// Panics if `x` is not a batch of matrices.
218///
219/// # Examples
220///
221/// ```
222/// use ruxla_core::{Array, Native, lax};
223///
224/// let a = Array::<Native, f64>::from_vec(vec![3.0, 4.0], [2, 1]);
225/// let (q, r) = lax::linalg::qr(&a, false);
226/// assert_eq!(r.to_vec(), [-5.0]);
227/// assert!((q.to_vec()[0] + 0.6).abs() < 1e-15);
228/// ```
229#[track_caller]
230pub fn qr<B: Backend, T: LinalgScalar>(
231    x: &Array<B, T>,
232    full_matrices: bool,
233) -> (Array<B, T>, Array<B, T>) {
234    matrix_dims("qr", x);
235    let (q, r) = B::qr::<T>(&x.0, full_matrices);
236    (Array(q), Array(r))
237}
238
239/// The QR decomposition with column pivoting of each matrix, as
240/// `lax.linalg.qr(x, pivoting=True)`: `(q, r, p)` with `x[..., p] = q r`,
241/// where the permutation `p` (`i32[..., n]`) moves the columns of largest
242/// remaining norm forward, as LAPACK's `geqp3`, so that the magnitudes of
243/// the diagonal of `r` do not increase (rank-revealing). The shapes of `q`
244/// and `r` are those of [`qr`].
245///
246/// # Examples
247///
248/// ```
249/// use ruxla_core::{Array, Native, lax};
250///
251/// let a = Array::<Native, f64>::from_vec(vec![1.0, 3.0, 0.0, 4.0], [2, 2]);
252/// let (_, r, p) = lax::linalg::qr_pivoting(&a, false);
253/// assert_eq!(p.to_vec(), [1, 0]);
254/// assert_eq!(r.to_vec()[0], -5.0);
255/// ```
256///
257/// # Panics
258///
259/// Panics if `x` is not a batch of matrices.
260#[track_caller]
261pub fn qr_pivoting<B: Backend, T: LinalgScalar>(
262    x: &Array<B, T>,
263    full_matrices: bool,
264) -> (Array<B, T>, Array<B, T>, Array<B, i32>) {
265    matrix_dims("qr", x);
266    let (q, r, p) = B::qr_pivoting::<T>(&x.0, full_matrices);
267    (Array(q), Array(r), Array(p))
268}
269
270/// The eigendecomposition of each symmetric (Hermitian) matrix, as
271/// `lax.linalg.eigh`: the eigenvectors `v` (one per column) and the real
272/// eigenvalues `w` in ascending order, with `x = v diag(w) v^H`.
273///
274/// With `symmetrize_input`, `x` is replaced by `(x + x^H) / 2` first;
275/// otherwise only the triangle given by `lower` is read (and the real part
276/// of the diagonal). The eigenvalues are always sorted (`sort_eigenvalues =
277/// false` allows any order). The sign (phase) of each eigenvector is chosen
278/// so that its component of largest magnitude is real and positive (LAPACK
279/// leaves it to its algorithm).
280///
281/// With `subset_by_index` `(start, end)`, only the eigenvalues of indices
282/// `start..end` (in ascending order) and their eigenvectors are returned
283/// (computed from the whole decomposition; JAX supports it on TPU only),
284/// and they are not differentiable. `implementation` chooses the algorithm
285/// as JAX's (`None` for the platform's default; natively, Jacobi rotations
286/// for [`EighImplementation::Jacobi`], the QR algorithm otherwise).
287///
288/// # Panics
289///
290/// Panics if `x` is not a batch of square matrices, or the range is out of
291/// bounds.
292#[track_caller]
293pub fn eigh<B: Backend, T: LinalgScalar>(
294    x: &Array<B, T>,
295    lower: bool,
296    symmetrize_input: bool,
297    sort_eigenvalues: bool,
298    subset_by_index: Option<(usize, usize)>,
299    implementation: Option<EighImplementation>,
300) -> (Array<B, T>, Array<B, T::Real>) {
301    matrix_dims("eigh", x);
302    let x = if symmetrize_input {
303        symmetrize(x)
304    } else {
305        x.clone()
306    };
307    let (v, w) = B::eigh::<T>(
308        &x.0,
309        lower,
310        sort_eigenvalues,
311        subset_by_index,
312        implementation,
313    );
314    (Array(v), Array(w))
315}
316
317/// The eigendecomposition of each general (nonsymmetric) square matrix, as
318/// `lax.linalg.eig`: the complex eigenvalues `w`, and, if requested, the
319/// left eigenvectors (`u^H x = w u^H`) and the right eigenvectors (`x v = w
320/// v`), one per column, with unit norm and the component of largest
321/// magnitude real, as LAPACK's `geev` gives them (the eigenvalues in the
322/// order of LAPACK's Schur form; see `ruxla_kernels::linalg::eig`).
323///
324/// The eigenvalues are differentiable; the eigenvectors only with
325/// `enable_eigvec_derivs` (valid for distinct eigenvalues), as in JAX.
326///
327/// # Examples
328///
329/// ```
330/// use ruxla_core::{Array, Native, lax};
331///
332/// // A rotation by 90 degrees: the eigenvalues are i and -i.
333/// let a = Array::<Native, f64>::from_vec(vec![0.0, -1.0, 1.0, 0.0], [2, 2]);
334/// let (w, _, _) = lax::linalg::eig(&a, false, false, false);
335/// let w = w.to_vec();
336/// assert_eq!((w[0].re, w[0].im, w[1].im), (0.0, 1.0, -1.0));
337/// ```
338///
339/// # Panics
340///
341/// Panics if `x` is not a batch of square matrices.
342#[allow(clippy::type_complexity)] // The optional eigenvectors.
343#[track_caller]
344pub fn eig<B: Backend, T: LinalgScalar>(
345    x: &Array<B, T>,
346    compute_left_eigenvectors: bool,
347    compute_right_eigenvectors: bool,
348    enable_eigvec_derivs: bool,
349) -> (
350    Array<B, T::Complex>,
351    Option<Array<B, T::Complex>>,
352    Option<Array<B, T::Complex>>,
353) {
354    matrix_dims("eig", x);
355    let (w, vl, vr) = B::eig::<T>(
356        &x.0,
357        compute_left_eigenvectors,
358        compute_right_eigenvectors,
359        enable_eigvec_derivs,
360    );
361    (Array(w), vl.map(Array), vr.map(Array))
362}
363
364/// The Schur decomposition `x = z t z^H` of each square matrix, as
365/// `lax.linalg.schur` (LAPACK's `gees`, without sorting): `t`, upper
366/// quasi-triangular for real matrices (with standardized 2 x 2 blocks for
367/// the complex conjugate eigenvalues) and upper triangular for complex
368/// ones, and, with `compute_schur_vectors`, the orthogonal (unitary) `z`.
369/// Not differentiable, as in JAX.
370///
371/// # Examples
372///
373/// ```
374/// use ruxla_core::{Array, Native, lax};
375///
376/// let a = Array::<Native, f64>::from_vec(vec![2.0, 1.0, 0.0, 3.0], [2, 2]);
377/// let (t, _) = lax::linalg::schur(&a, false);
378/// assert_eq!(t.to_vec(), [2.0, 1.0, 0.0, 3.0]);
379/// ```
380///
381/// # Panics
382///
383/// Panics if `x` is not a batch of square matrices.
384#[track_caller]
385pub fn schur<B: Backend, T: LinalgScalar>(
386    x: &Array<B, T>,
387    compute_schur_vectors: bool,
388) -> (Array<B, T>, Option<Array<B, T>>) {
389    matrix_dims("schur", x);
390    let (t, z) = B::schur::<T>(&x.0, compute_schur_vectors);
391    (Array(t), z.map(Array))
392}
393
394/// The reduction of each square matrix to upper Hessenberg form `x = q h
395/// q^H`, as `lax.linalg.hessenberg` (LAPACK's `gehrd`): `h` on and above
396/// the subdiagonal with the Householder reflectors of `q` below it, and
397/// their `n - 1` factors (for [`householder_product`] and [`ormqr`]). Not
398/// differentiable, as in JAX.
399///
400/// # Panics
401///
402/// Panics if `x` is not a batch of square matrices.
403#[track_caller]
404pub fn hessenberg<B: Backend, T: LinalgScalar>(x: &Array<B, T>) -> (Array<B, T>, Array<B, T>) {
405    matrix_dims("hessenberg", x);
406    let (h, taus) = B::hessenberg::<T>(&x.0);
407    (Array(h), Array(taus))
408}
409
410/// The first `n` columns of the product of the Householder reflectors below
411/// the diagonal of `a` (`[..., m, n]`, `m >= n`) with the factors `taus`
412/// (`[..., k]`), as `lax.linalg.householder_product` (LAPACK's `orgqr`).
413/// Not differentiable, as in JAX.
414///
415/// # Panics
416///
417/// Panics if the shapes do not match.
418#[track_caller]
419pub fn householder_product<B: Backend, T: LinalgScalar>(
420    a: &Array<B, T>,
421    taus: &Array<B, T>,
422) -> Array<B, T> {
423    Array(B::householder_product::<T>(&a.0, &taus.0))
424}
425
426/// `q c`, `q^H c` (`transpose`), `c q`, or `c q^H` (not `left`), where `q`
427/// is the product of the Householder reflectors of `a` with the factors
428/// `taus`, without forming `q`, as `lax.linalg.ormqr` (LAPACK's `ormqr`).
429/// Not differentiable, as in JAX.
430///
431/// # Panics
432///
433/// Panics if the shapes do not match.
434#[track_caller]
435pub fn ormqr<B: Backend, T: LinalgScalar>(
436    a: &Array<B, T>,
437    taus: &Array<B, T>,
438    c: &Array<B, T>,
439    left: bool,
440    transpose: bool,
441) -> Array<B, T> {
442    Array(B::ormqr::<T>(&a.0, &taus.0, &c.0, left, transpose))
443}
444
445/// The rank-1 update of a Cholesky factorization, as
446/// `lax.linalg.cholesky_update`: given the upper triangular `r` of
447/// `a = r^T r` and the vector `w`, the upper triangular factor of
448/// `a + w w^T` in `O(n^2)` (by Givens rotations, as JAX computes it on
449/// CPU; the diagonal may come out negative). Real matrices only, not
450/// differentiable, as in JAX.
451///
452/// # Examples
453///
454/// ```
455/// use ruxla_core::{Array, Native, lax::linalg::cholesky_update};
456///
457/// // a = r^T r = [[4, 2], [2, 5]]; a + w w^T = [[5, 4], [4, 9]].
458/// let r = Array::<Native, f64>::from_vec(vec![2.0, 1.0, 0.0, 2.0], [2, 2]);
459/// let w = Array::<Native, f64>::from_vec(vec![1.0, 2.0], [2]);
460/// let r = cholesky_update(&r, &w).to_vec();
461/// let a = [
462///     r[0] * r[0],
463///     r[0] * r[1],
464///     r[1] * r[1] + r[3] * r[3],
465/// ];
466/// for (got, expected) in a.iter().zip([5.0, 4.0, 9.0]) {
467///     assert!((got - expected).abs() < 1e-12);
468/// }
469/// ```
470///
471/// # Panics
472///
473/// Panics if `r` is not square or `w` does not match it.
474#[track_caller]
475pub fn cholesky_update<B: Backend, T: LinalgFloat>(
476    r: &Array<B, T>,
477    w: &Array<B, T>,
478) -> Array<B, T> {
479    Array(B::cholesky_update::<T>(&r.0, &w.0))
480}
481
482/// `alpha a a^T + beta c` for each `a` (`[..., m, n]`) and symmetric `c`
483/// (`[..., m, m]`), as `lax.linalg.symmetric_product` (with
484/// `symmetrize_output`, the upper triangle is replaced by the transpose of
485/// the lower one; JAX guarantees only the lower triangle otherwise, which
486/// cuBLAS's `syrk` computes on GPU). Real matrices only, not
487/// differentiable, as in JAX.
488///
489/// # Panics
490///
491/// Panics if the shapes do not match.
492#[track_caller]
493pub fn symmetric_product<B: Backend, T: LinalgFloat>(
494    a: &Array<B, T>,
495    c: &Array<B, T>,
496    alpha: f64,
497    beta: f64,
498    symmetrize_output: bool,
499) -> Array<B, T> {
500    let result = Array(B::symmetric_product::<T>(&a.0, &c.0, alpha, beta));
501    if !symmetrize_output {
502        return result;
503    }
504    // JAX: `tril(result) + tril(result, -1)^T`.
505    let upper = adjoint(&tril(&result, -1));
506    tril(&result, 0) + upper
507}
508
509/// The reduction of each Hermitian (symmetric) matrix to real tridiagonal
510/// form by a unitary similarity, as `lax.linalg.tridiagonal`, reading only
511/// the `lower` (or upper) triangle: `(a, d, e, taus)` with the diagonal `d`
512/// and the off-diagonal `e` (real), and in that triangle of `a` the
513/// tridiagonal form and the Householder reflectors (with the factors
514/// `taus`) below (above) the off-diagonal; the other triangle is that of
515/// the input. Not differentiable, as in JAX.
516///
517/// # Panics
518///
519/// Panics if `x` is not a batch of nonempty square matrices.
520#[track_caller]
521#[allow(clippy::type_complexity)] // The four results of `sytrd`.
522pub fn tridiagonal<B: Backend, T: LinalgScalar>(
523    x: &Array<B, T>,
524    lower: bool,
525) -> (
526    Array<B, T>,
527    Array<B, T::Real>,
528    Array<B, T::Real>,
529    Array<B, T>,
530) {
531    let (a, d, e, taus) = B::tridiagonal::<T>(&x.0, lower);
532    (Array(a), Array(d), Array(e), Array(taus))
533}
534
535/// The solution `x` of `A x = b` for each tridiagonal matrix `A`, as
536/// `lax.linalg.tridiagonal_solve`: `dl[..., i] = A[i, i - 1]` (`dl[..., 0]`
537/// is ignored), `d[..., i] = A[i, i]`, and `du[..., i] = A[i, i + 1]`
538/// (`du[..., m - 1]` is ignored), each `[..., m]`, and `b` is
539/// `[..., m, n]`. Gaussian elimination with partial pivoting (LAPACK's
540/// `gtsv`): singular systems give NaNs, unless `perturb_singular`, which
541/// perturbs tiny pivots so that numerically singular systems (as in inverse
542/// iteration) give finite solutions. Differentiable in all inputs.
543///
544/// # Examples
545///
546/// ```
547/// use ruxla_core::{Array, Native, lax::linalg::tridiagonal_solve};
548///
549/// // [[2, 1, 0], [1, 2, 1], [0, 1, 2]] x = [4, 8, 8]
550/// let dl = Array::<Native, f64>::from_vec(vec![0.0, 1.0, 1.0], [3]);
551/// let d = Array::<Native, f64>::from_vec(vec![2.0, 2.0, 2.0], [3]);
552/// let du = Array::<Native, f64>::from_vec(vec![1.0, 1.0, 0.0], [3]);
553/// let b = Array::<Native, f64>::from_vec(vec![4.0, 8.0, 8.0], [3, 1]);
554/// let x = tridiagonal_solve(&dl, &d, &du, &b, false);
555/// let x = x.to_vec();
556/// for (got, expected) in x.iter().zip([1.0, 2.0, 3.0]) {
557///     assert!((got - expected).abs() < 1e-12);
558/// }
559/// ```
560///
561/// # Panics
562///
563/// Panics if the shapes do not match.
564#[track_caller]
565pub fn tridiagonal_solve<B: Backend, T: LinalgScalar>(
566    dl: &Array<B, T>,
567    d: &Array<B, T>,
568    du: &Array<B, T>,
569    b: &Array<B, T>,
570    perturb_singular: bool,
571) -> Array<B, T> {
572    Array(B::tridiagonal_solve::<T>(
573        &dl.0,
574        &d.0,
575        &du.0,
576        &b.0,
577        perturb_singular,
578    ))
579}
580
581/// The singular value decomposition of each matrix, as `lax.linalg.svd`:
582/// `(u, s, vt)` with the real singular values `s` in descending order and
583/// `x = u diag(s) vt`. With `full_matrices`, `u` is `[..., m, m]` and `vt`
584/// is `[..., n, n]`; otherwise `[..., m, k]` and `[..., k, n]` for
585/// `k = min(m, n)`. The signs (phases) make the component of largest
586/// magnitude of each column of `u` real and positive.
587///
588/// With `subset_by_index` `(start, end)` (not with `full_matrices`), only
589/// the singular values of indices `start..end` and their vectors are
590/// returned (computed from the whole decomposition; JAX supports it on TPU
591/// only), and they are not differentiable. `algorithm` chooses the
592/// algorithm as JAX's (`None` for the platform's default; natively,
593/// one-sided Jacobi rotations for [`SvdAlgorithm::Jacobi`], the QR
594/// algorithm otherwise).
595///
596/// # Panics
597///
598/// Panics if `x` is not a batch of matrices, or the range is out of
599/// bounds or given with `full_matrices`.
600#[track_caller]
601pub fn svd<B: Backend, T: LinalgScalar>(
602    x: &Array<B, T>,
603    full_matrices: bool,
604    subset_by_index: Option<(usize, usize)>,
605    algorithm: Option<SvdAlgorithm>,
606) -> Svd<B, T> {
607    matrix_dims("svd", x);
608    let (s, uv) = B::svd::<T>(&x.0, full_matrices, true, subset_by_index, algorithm);
609    let (u, vt) = uv.expect("compute_uv");
610    (Array(u), Array(s), Array(vt))
611}
612
613/// The singular values of each matrix in descending order
614/// (`lax.linalg.svd` with `compute_uv=False`), only those of indices
615/// `start..end` with `subset_by_index` (differentiable), by `algorithm` (as
616/// in [`svd`]).
617///
618/// # Panics
619///
620/// Panics if `x` is not a batch of matrices, or the range is out of
621/// bounds.
622#[track_caller]
623pub fn svd_values<B: Backend, T: LinalgScalar>(
624    x: &Array<B, T>,
625    subset_by_index: Option<(usize, usize)>,
626    algorithm: Option<SvdAlgorithm>,
627) -> Array<B, T::Real> {
628    matrix_dims("svd", x);
629    // `full_matrices` does not matter without the vectors, but cannot be
630    // set together with a subset.
631    let full = subset_by_index.is_none();
632    let (s, _) = B::svd::<T>(&x.0, full, false, subset_by_index, algorithm);
633    Array(s)
634}
635
636/// The polar decomposition `x = u h` of a full-rank matrix (`m x n` with
637/// `m >= n`) by the QR-based dynamically weighted Halley iteration, as
638/// `lax.linalg.qdwh`: `(u, h, num_iters, is_converged)` with `u` (`m x n`)
639/// having orthonormal columns and `h` (`n x n`) Hermitian positive
640/// semidefinite. The iteration follows JAX's (`jax._src.tpu.linalg.qdwh`):
641/// the scaling by `1 / sqrt(|x|_1 |x|_inf)`, the weights of the steps
642/// computed in advance from the lower bound `eps` of the smallest singular
643/// value (QR steps while `c > 100`, then Cholesky steps), Halley's steps
644/// until `|u_k - u_{k-1}|_F <= (5 eps)^(1/3)` within `max_iterations` (10
645/// by default), and a Newton-Schulz refinement. `eps` defaults to the
646/// machine epsilon of `T`. With `dynamic_shape` `(m, n)`, `x` is a matrix
647/// padded from its true shape `m x n` (which may be traced values), as in
648/// JAX: the entries outside are taken as zeros and stay zeros. (JAX's unused
649/// `is_hermitian` is left out.)
650///
651/// # Examples
652///
653/// ```
654/// use ruxla_core::{Array, Native, jnp, lax::linalg::qdwh};
655///
656/// let x = Array::<Native, f64>::from_vec(vec![3.0, 1.0, 1.0, 2.0, 0.0, 1.0], [3, 2]);
657/// let (u, h, _, converged) = qdwh(&x, None, None, None);
658/// assert!(converged.value());
659/// let back = jnp::matmul(&u, &h).to_vec();
660/// for (got, expected) in back.iter().zip(x.to_vec()) {
661///     assert!((got - expected).abs() < 1e-12);
662/// }
663/// ```
664///
665/// # Panics
666///
667/// Panics if `x` is not a matrix with at least as many rows as columns.
668#[track_caller]
669#[allow(clippy::type_complexity)] // The four results of `qdwh`.
670pub fn qdwh<B: Backend, T: LinalgScalar>(
671    x: &Array<B, T>,
672    max_iterations: Option<usize>,
673    eps: Option<f64>,
674    dynamic_shape: Option<(I32<B>, I32<B>)>,
675) -> (Array<B, T>, Array<B, T>, I32<B>, Bool<B>) {
676    let dims = x.shape().dims().to_vec();
677    assert!(
678        dims.len() == 2 && dims[0] >= dims[1],
679        "qdwh: the input must be a matrix of M x N with M >= N, got {dims:?}"
680    );
681    let (m, n) = (dims[0], dims[1]);
682    let max_iterations = max_iterations.unwrap_or(10);
683    let eps = eps.unwrap_or_else(|| {
684        ruxla_kernels::cast::<T::Real, f64>(
685            <T::Real as ruxla_kernels::linalg::LinalgFloat>::EPSILON,
686        )
687    });
688    let t = |v: f64| ruxla_kernels::cast::<f64, T>(v);
689    let real = |v: f64| ruxla_kernels::cast::<f64, T::Real>(v);
690    let eye =
691        lax::convert_element_type::<B, bool, T>(&lax::iota::<B, i32>([n, n], 0).eq(lax::iota::<
692            B,
693            i32,
694        >(
695            [n, n], 1
696        )));
697
698    // JAX's `_mask`: the entries of an `r x c` array outside the true shape
699    // replaced by those of `alternative`.
700    let mask = |a: &Array<B, T>, rows: I32<B>, cols: I32<B>, alternative: &Array<B, T>| {
701        let dims = a.shape().dims().to_vec();
702        let inside = lax::iota::<B, i32>(dims.as_slice(), 0).lt(rows)
703            & lax::iota::<B, i32>(dims.as_slice(), 1).lt(cols);
704        jnp::where_(inside, a, alternative)
705    };
706    let zeros = |a: &Array<B, T>| a * t(0.0);
707    let x = &match dynamic_shape {
708        Some((rows, cols)) => mask(x, rows, cols, &zeros(x)),
709        None => x.clone(),
710    };
711    // `alpha >= |x|_2`, from the 1-norm and the infinity norm.
712    let magnitudes = jnp::abs(x);
713    let one_norm = jnp::max(jnp::sum(&magnitudes, 0i64), 0i64);
714    let inf_norm = jnp::max(jnp::sum(&magnitudes, 1i64), 0i64);
715    let alpha_inverse = lax::rsqrt(&one_norm) * lax::rsqrt(&inf_norm);
716    let alpha_inverse = jnp::where_(one_norm.eq(real(0.0)), real(1.0), &alpha_inverse);
717    let mut u = x * &lax::convert_element_type::<B, T::Real, T>(&alpha_inverse);
718
719    // The weights of the steps, computed in advance from the bound `l`.
720    let tol_l = 10.0 * eps / 2.0;
721    let tol_norm = real(tol_l.cbrt());
722    let mut l = eps;
723    let mut qr_coefs = Vec::new();
724    let mut chol_coefs = Vec::new();
725    let mut k = 0;
726    while l + tol_l < 1.0 && k < max_iterations {
727        k += 1;
728        let l2 = l * l;
729        let dd = (4.0 * (1.0 / l2 - 1.0) / l2).powf(1.0 / 3.0);
730        let sqd = (1.0 + dd).sqrt();
731        let a = sqd + (2.0 - dd + 2.0 * (2.0 - l2) / (l2 * sqd)).sqrt();
732        let b = (a - 1.0) * (a - 1.0) / 4.0;
733        let c = a + b - 1.0;
734        l = l * (a + b * l2) / (1.0 + c * l2);
735        let e = b / c;
736        if c > 100.0 {
737            let sqrt_c = c.sqrt();
738            qr_coefs.push(((a - e) / sqrt_c, sqrt_c, e));
739        } else {
740            chol_coefs.push((a - e, c, e));
741        }
742    }
743
744    // A QR step: `y = [sqrt(c) u; I] = q r`, `u = e u + (a - e) / sqrt(c)
745    // q1 q2^H`.
746    let qr_step = |u: &Array<B, T>, (a_minus_e_by_sqrt_c, sqrt_c, e): (f64, f64, f64)| {
747        let scaled = u * t(sqrt_c);
748        let (q1, q2) = match dynamic_shape {
749            None => {
750                let y = jnp::concatenate(&[scaled, eye.clone()], 0);
751                let (q, _) = qr(&y, false);
752                let q1 = lax::slice(&q, &[0, 0], &[m, n], None);
753                (q1, lax::slice(&q, &[m, 0], &[m + n, n], None))
754            }
755            Some((rows, cols)) => {
756                // JAX's `_dynamic_concat`: the identity written after the
757                // true rows.
758                let padded = lax::pad(&scaled, t(0.0), &[(0, n as i64, 0), (0, 0, 0)]);
759                let y = lax::dynamic_update_slice(&padded, &eye, &[rows, I32::new(0)]);
760                let (q, _) = qr(&y, false);
761                let q1 = lax::slice(&q, &[0, 0], &[m, n], None);
762                let q1 = mask(&q1, rows, cols, &zeros(&q1));
763                let q2 = lax::dynamic_slice(&q, &[rows, I32::new(0)], &[n, n]);
764                (q1, mask(&q2, cols, cols, &zeros(&q2)))
765            }
766        };
767        u * t(e) + jnp::matmul(&q1, &adjoint(&q2)) * t(a_minus_e_by_sqrt_c)
768    };
769    // A Cholesky step: `y y^H = c u^H u + I`, `u = e u + (a - e) u y^-H
770    // y^-1`.
771    let cholesky_step = |u: &Array<B, T>, (a_minus_e, c, e): (f64, f64, f64)| {
772        let gram = jnp::matmul(&adjoint(u), u) * t(c) + &eye;
773        // The identity in the padded corner keeps it positive definite.
774        let gram = match dynamic_shape {
775            Some((_, cols)) => mask(&gram, cols, cols, &eye),
776            None => gram,
777        };
778        let y = cholesky(&gram, false);
779        let solve = |b: &Array<B, T>, transpose_a: bool| {
780            triangular_solve(
781                &y,
782                b,
783                TriangularSolveOptions {
784                    left_side: true,
785                    lower: true,
786                    transpose_a,
787                    conjugate_a: true,
788                    unit_diagonal: false,
789                },
790            )
791        };
792        let z = conj(&solve(&mt(u), false));
793        let z = adjoint(&solve(&z, true));
794        u * t(e) + z * t(a_minus_e)
795    };
796    let changed = |u: &Array<B, T>, previous: &Array<B, T>| {
797        // `|d|^2` (JAX's `real(d conj(d))`, which only rounds differently).
798        let magnitudes = jnp::abs(u - previous);
799        let squares = &magnitudes * &magnitudes;
800        lax::sqrt(&jnp::sum(&squares, &[0i64, 1][..]))
801            .gt(tol_norm)
802            .to_scalar()
803    };
804
805    for &coefs in &qr_coefs {
806        u = qr_step(&u, coefs);
807    }
808    let mut not_converged = Bool::<B>::new(true);
809    for &coefs in &chol_coefs {
810        let previous = u.clone();
811        u = cholesky_step(&u, coefs);
812        not_converged = changed(&u, &previous);
813    }
814    // Halley's steps (`a, b, c = 3, 1, 3`) until convergence.
815    let halley = (3.0 - 1.0 / 3.0, 3.0, 1.0 / 3.0);
816    let start =
817        I32::<B>::new(i32::try_from(qr_coefs.len() + chol_coefs.len()).expect("iterations"));
818    let limit = i32::try_from(max_iterations).expect("max_iterations");
819    let (num_iters, u, not_converged) = while_loop(
820        |(k, _, not_converged): &(I32<B>, Array<B, T>, Bool<B>)| *not_converged & k.lt(limit),
821        |(k, u, _)| {
822            let next = cholesky_step(&u, halley);
823            let not_converged = changed(&next, &u);
824            (k + 1, next, not_converged)
825        },
826        (start, u, not_converged),
827    );
828
829    // The Newton-Schulz refinement, and `h = u^H x`, symmetrized.
830    let uh = adjoint(&u);
831    let u = &u * t(1.5) - jnp::matmul(&u, &jnp::matmul(&uh, &u)) * t(0.5);
832    let h = jnp::matmul(&adjoint(&u), x);
833    let h = (&h + &adjoint(&h)) / t(2.0);
834    (u, h, num_iters, !not_converged)
835}
836
837/// The complex conjugate (the value itself for real types).
838fn conj<B: Backend, T: LinalgScalar>(x: &Array<B, T>) -> Array<B, T> {
839    if T::DTYPE.is_complex() {
840        Array(B::a_conj::<T>(&x.0))
841    } else {
842        x.clone()
843    }
844}