ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
//! Linear algebra following `jax.lax.linalg`: decompositions of batches of
//! matrices (`[..., m, n]`, batch dimensions first) of `f32`, `f64`, `c64`, or
//! `c128`. For complex matrices, transposes are conjugate transposes
//! (`cholesky` gives `x = l l^H`, `eigh` takes Hermitian matrices and gives
//! real eigenvalues, and `svd` gives real singular values and `vt = v^H`), and
//! eigenvectors and singular vectors are defined up to a phase rather than a
//! sign.
//!
//! The functions bind the primitives as JAX's do (with the same
//! symmetrization and masking around them), so traced programs have JAX's
//! jaxprs. On the native backend they run the kernels of
//! `ruxla_kernels::linalg`; compiled by XLA, ruxla's FFI handlers (or, in
//! JAX, the LAPACK and cuSOLVER calls JAX itself makes).

use ruxla_ir::Shape;

use crate::backend::Backend;
use crate::control::while_loop;
use crate::value::{Array, Bool, I32, LinalgFloat, LinalgScalar};
use crate::{jnp, lax};
pub use ruxla_ir::{EighImplementation, SvdAlgorithm};

pub use ruxla_kernels::linalg::TriangularSolveOptions;

/// The singular value decomposition `(u, s, vt)` of [`svd`], with real
/// singular values `s`.
pub type Svd<B, T> = (
    Array<B, T>,
    Array<B, <T as crate::Element>::Real>,
    Array<B, T>,
);

/// Checks that `x` is a batch of matrices, and returns `(rows, cols)`.
#[track_caller]
fn matrix_dims<B: Backend, T: LinalgScalar>(op: &str, x: &Array<B, T>) -> (usize, usize) {
    let shape = x.shape();
    let rank = shape.rank();
    assert!(
        rank >= 2,
        "{op} needs a matrix or a batch of matrices, got shape [{shape}]"
    );
    (shape[rank - 2], shape[rank - 1])
}

/// `x` with its last two dimensions swapped (JAX's `_T`).
pub(crate) fn mt<B: Backend, T: crate::Element>(x: &Array<B, T>) -> Array<B, T> {
    let rank = x.ndim();
    let mut perm: Vec<usize> = (0..rank).collect();
    perm.swap(rank - 2, rank - 1);
    x.transpose(&perm)
}

/// `(x + x^T) / 2` (JAX's `symmetrize`).
/// The conjugate transpose of the last two dimensions (JAX's `_H`; the
/// transpose for real matrices).
pub(crate) fn adjoint<B: Backend, T: LinalgScalar>(x: &Array<B, T>) -> Array<B, T> {
    let t = mt(x);
    if T::DTYPE.is_complex() {
        Array(B::a_conj::<T>(&t.0))
    } else {
        t
    }
}

pub(crate) fn symmetrize<B: Backend, T: LinalgScalar>(x: &Array<B, T>) -> Array<B, T> {
    let two = ruxla_kernels::cast::<f64, T>(2.0);
    (x + adjoint(x)) / two
}

/// The mask `i + k >= j` of the matrices of `shape`, broadcast to the
/// batch (JAX's `_tri` with `i64` indices).
pub(crate) fn tri<B: Backend>(shape: &Shape, k: i64) -> Array<B, bool> {
    let rank = shape.rank();
    let (n, m) = (shape[rank - 2], shape[rank - 1]);
    let i = lax::iota::<B, i64>([n, m], 0) + k;
    let j = lax::iota::<B, i64>([n, m], 1);
    let mask = i.ge(&j);
    if rank == 2 {
        mask
    } else {
        lax::broadcast_in_dim(&mask, shape.clone(), &[rank - 2, rank - 1])
    }
}

/// The elements on and below diagonal `k` (JAX's `_tril`).
pub(crate) fn tril<B: Backend, T: LinalgScalar>(x: &Array<B, T>, k: i64) -> Array<B, T> {
    let shape = x.shape();
    let mask = tri::<B>(&shape, k);
    let zeros = crate::jnp::zeros::<B, T>(shape);
    lax::select_array(&mask, x, &zeros)
}

/// The Cholesky factor `L` of each symmetric positive definite matrix
/// (`x = L L^T`, `L` lower triangular), as `lax.linalg.cholesky`.
///
/// With `symmetrize_input`, `x` is replaced by `(x + x^T) / 2` first, which
/// gives better derivatives; otherwise only its lower triangle is read.
/// Matrices that are not positive definite give NaNs.
///
/// # Panics
///
/// Panics if `x` is not a batch of square matrices.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let a = Array::<Native, f64>::from_vec(vec![4.0, 2.0, 2.0, 5.0], [2, 2]);
/// let l = lax::linalg::cholesky(&a, true);
/// assert_eq!(l.to_vec(), [2.0, 0.0, 1.0, 2.0]);
/// ```
#[track_caller]
pub fn cholesky<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    symmetrize_input: bool,
) -> Array<B, T> {
    matrix_dims("cholesky", x);
    let x = if symmetrize_input {
        symmetrize(x)
    } else {
        x.clone()
    };
    let l = Array(B::cholesky::<T>(&x.0));
    tril(&l, 0)
}

/// Solves `op(a) x = b` (`left_side`) or `x op(a) = b` for `x`, where `a`
/// is triangular, as `lax.linalg.triangular_solve` (whose defaults are
/// those of [`TriangularSolveOptions::default`]). Only the triangle of `a`
/// given by `lower` is read, without the diagonal for `unit_diagonal`.
///
/// # Panics
///
/// Panics if the shapes do not match (`a` is `[..., k, k]` and `b` is
/// `[..., k, n]` on the left side or `[..., m, k]` on the right, with the
/// same batch dimensions).
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
/// use ruxla_core::lax::linalg::TriangularSolveOptions;
///
/// let a = Array::<Native, f32>::from_vec(vec![2.0, 0.0, 1.0, 4.0], [2, 2]);
/// let b = Array::<Native, f32>::from_vec(vec![2.0, 9.0], [2, 1]);
/// let options = TriangularSolveOptions {
///     left_side: true,
///     lower: true,
///     ..Default::default()
/// };
/// let x = lax::linalg::triangular_solve(&a, &b, options);
/// assert_eq!(x.to_vec(), [1.0, 2.0]);
/// ```
#[track_caller]
pub fn triangular_solve<B: Backend, T: LinalgScalar>(
    a: &Array<B, T>,
    b: &Array<B, T>,
    options: TriangularSolveOptions,
) -> Array<B, T> {
    Array(B::triangular_solve::<T>(&a.0, &b.0, options))
}

/// The LU factorization with partial pivoting of each matrix, as
/// `lax.linalg.lu`: the factors (`L` below the diagonal, with an implicit
/// unit diagonal, and `U`), the pivots (`i32[..., min(m, n)]`: row `i` was
/// swapped with row `pivots[i]`), and the permutation (`i32[..., m]`), with
/// `a[perm] = L U`.
///
/// # Panics
///
/// Panics if `x` is not a batch of matrices.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let a = Array::<Native, f64>::from_vec(vec![1.0, 2.0, 4.0, 2.0], [2, 2]);
/// let (lu, pivots, perm) = lax::linalg::lu(&a);
/// assert_eq!(lu.to_vec(), [4.0, 2.0, 0.25, 1.5]);
/// assert_eq!(pivots.to_vec(), [1, 1]);
/// assert_eq!(perm.to_vec(), [1, 0]);
/// ```
#[track_caller]
pub fn lu<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
) -> (Array<B, T>, Array<B, i32>, Array<B, i32>) {
    matrix_dims("lu", x);
    let (lu, pivots, perm) = B::lu::<T>(&x.0);
    (Array(lu), Array(pivots), Array(perm))
}

/// Converts the pivots of [`lu`] to a permutation of `permutation_size`
/// elements, as `lax.linalg.lu_pivots_to_permutation`.
///
/// # Panics
///
/// Panics if `pivots` is a scalar or has more pivots than
/// `permutation_size`.
#[track_caller]
pub fn lu_pivots_to_permutation<B: Backend>(
    pivots: &Array<B, i32>,
    permutation_size: usize,
) -> Array<B, i32> {
    Array(B::lu_pivots_to_permutation(&pivots.0, permutation_size))
}

/// The QR decomposition of each matrix, as `lax.linalg.qr`: `q` with
/// orthonormal columns and an upper triangular `r` (`x = q r`), with the
/// signs of LAPACK's Householder reflectors. With `full_matrices`, `q` is
/// `[..., m, m]` and `r` is `[..., m, n]`; otherwise `[..., m, k]` and
/// `[..., k, n]` for `k = min(m, n)`.
///
/// # Panics
///
/// Panics if `x` is not a batch of matrices.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let a = Array::<Native, f64>::from_vec(vec![3.0, 4.0], [2, 1]);
/// let (q, r) = lax::linalg::qr(&a, false);
/// assert_eq!(r.to_vec(), [-5.0]);
/// assert!((q.to_vec()[0] + 0.6).abs() < 1e-15);
/// ```
#[track_caller]
pub fn qr<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    full_matrices: bool,
) -> (Array<B, T>, Array<B, T>) {
    matrix_dims("qr", x);
    let (q, r) = B::qr::<T>(&x.0, full_matrices);
    (Array(q), Array(r))
}

/// The QR decomposition with column pivoting of each matrix, as
/// `lax.linalg.qr(x, pivoting=True)`: `(q, r, p)` with `x[..., p] = q r`,
/// where the permutation `p` (`i32[..., n]`) moves the columns of largest
/// remaining norm forward, as LAPACK's `geqp3`, so that the magnitudes of
/// the diagonal of `r` do not increase (rank-revealing). The shapes of `q`
/// and `r` are those of [`qr`].
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let a = Array::<Native, f64>::from_vec(vec![1.0, 3.0, 0.0, 4.0], [2, 2]);
/// let (_, r, p) = lax::linalg::qr_pivoting(&a, false);
/// assert_eq!(p.to_vec(), [1, 0]);
/// assert_eq!(r.to_vec()[0], -5.0);
/// ```
///
/// # Panics
///
/// Panics if `x` is not a batch of matrices.
#[track_caller]
pub fn qr_pivoting<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    full_matrices: bool,
) -> (Array<B, T>, Array<B, T>, Array<B, i32>) {
    matrix_dims("qr", x);
    let (q, r, p) = B::qr_pivoting::<T>(&x.0, full_matrices);
    (Array(q), Array(r), Array(p))
}

/// The eigendecomposition of each symmetric (Hermitian) matrix, as
/// `lax.linalg.eigh`: the eigenvectors `v` (one per column) and the real
/// eigenvalues `w` in ascending order, with `x = v diag(w) v^H`.
///
/// With `symmetrize_input`, `x` is replaced by `(x + x^H) / 2` first;
/// otherwise only the triangle given by `lower` is read (and the real part
/// of the diagonal). The eigenvalues are always sorted (`sort_eigenvalues =
/// false` allows any order). The sign (phase) of each eigenvector is chosen
/// so that its component of largest magnitude is real and positive (LAPACK
/// leaves it to its algorithm).
///
/// With `subset_by_index` `(start, end)`, only the eigenvalues of indices
/// `start..end` (in ascending order) and their eigenvectors are returned
/// (computed from the whole decomposition; JAX supports it on TPU only),
/// and they are not differentiable. `implementation` chooses the algorithm
/// as JAX's (`None` for the platform's default; natively, Jacobi rotations
/// for [`EighImplementation::Jacobi`], the QR algorithm otherwise).
///
/// # Panics
///
/// Panics if `x` is not a batch of square matrices, or the range is out of
/// bounds.
#[track_caller]
pub fn eigh<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    lower: bool,
    symmetrize_input: bool,
    sort_eigenvalues: bool,
    subset_by_index: Option<(usize, usize)>,
    implementation: Option<EighImplementation>,
) -> (Array<B, T>, Array<B, T::Real>) {
    matrix_dims("eigh", x);
    let x = if symmetrize_input {
        symmetrize(x)
    } else {
        x.clone()
    };
    let (v, w) = B::eigh::<T>(
        &x.0,
        lower,
        sort_eigenvalues,
        subset_by_index,
        implementation,
    );
    (Array(v), Array(w))
}

/// The eigendecomposition of each general (nonsymmetric) square matrix, as
/// `lax.linalg.eig`: the complex eigenvalues `w`, and, if requested, the
/// left eigenvectors (`u^H x = w u^H`) and the right eigenvectors (`x v = w
/// v`), one per column, with unit norm and the component of largest
/// magnitude real, as LAPACK's `geev` gives them (the eigenvalues in the
/// order of LAPACK's Schur form; see `ruxla_kernels::linalg::eig`).
///
/// The eigenvalues are differentiable; the eigenvectors only with
/// `enable_eigvec_derivs` (valid for distinct eigenvalues), as in JAX.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// // A rotation by 90 degrees: the eigenvalues are i and -i.
/// let a = Array::<Native, f64>::from_vec(vec![0.0, -1.0, 1.0, 0.0], [2, 2]);
/// let (w, _, _) = lax::linalg::eig(&a, false, false, false);
/// let w = w.to_vec();
/// assert_eq!((w[0].re, w[0].im, w[1].im), (0.0, 1.0, -1.0));
/// ```
///
/// # Panics
///
/// Panics if `x` is not a batch of square matrices.
#[allow(clippy::type_complexity)] // The optional eigenvectors.
#[track_caller]
pub fn eig<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    compute_left_eigenvectors: bool,
    compute_right_eigenvectors: bool,
    enable_eigvec_derivs: bool,
) -> (
    Array<B, T::Complex>,
    Option<Array<B, T::Complex>>,
    Option<Array<B, T::Complex>>,
) {
    matrix_dims("eig", x);
    let (w, vl, vr) = B::eig::<T>(
        &x.0,
        compute_left_eigenvectors,
        compute_right_eigenvectors,
        enable_eigvec_derivs,
    );
    (Array(w), vl.map(Array), vr.map(Array))
}

/// The Schur decomposition `x = z t z^H` of each square matrix, as
/// `lax.linalg.schur` (LAPACK's `gees`, without sorting): `t`, upper
/// quasi-triangular for real matrices (with standardized 2 x 2 blocks for
/// the complex conjugate eigenvalues) and upper triangular for complex
/// ones, and, with `compute_schur_vectors`, the orthogonal (unitary) `z`.
/// Not differentiable, as in JAX.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let a = Array::<Native, f64>::from_vec(vec![2.0, 1.0, 0.0, 3.0], [2, 2]);
/// let (t, _) = lax::linalg::schur(&a, false);
/// assert_eq!(t.to_vec(), [2.0, 1.0, 0.0, 3.0]);
/// ```
///
/// # Panics
///
/// Panics if `x` is not a batch of square matrices.
#[track_caller]
pub fn schur<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    compute_schur_vectors: bool,
) -> (Array<B, T>, Option<Array<B, T>>) {
    matrix_dims("schur", x);
    let (t, z) = B::schur::<T>(&x.0, compute_schur_vectors);
    (Array(t), z.map(Array))
}

/// The reduction of each square matrix to upper Hessenberg form `x = q h
/// q^H`, as `lax.linalg.hessenberg` (LAPACK's `gehrd`): `h` on and above
/// the subdiagonal with the Householder reflectors of `q` below it, and
/// their `n - 1` factors (for [`householder_product`] and [`ormqr`]). Not
/// differentiable, as in JAX.
///
/// # Panics
///
/// Panics if `x` is not a batch of square matrices.
#[track_caller]
pub fn hessenberg<B: Backend, T: LinalgScalar>(x: &Array<B, T>) -> (Array<B, T>, Array<B, T>) {
    matrix_dims("hessenberg", x);
    let (h, taus) = B::hessenberg::<T>(&x.0);
    (Array(h), Array(taus))
}

/// The first `n` columns of the product of the Householder reflectors below
/// the diagonal of `a` (`[..., m, n]`, `m >= n`) with the factors `taus`
/// (`[..., k]`), as `lax.linalg.householder_product` (LAPACK's `orgqr`).
/// Not differentiable, as in JAX.
///
/// # Panics
///
/// Panics if the shapes do not match.
#[track_caller]
pub fn householder_product<B: Backend, T: LinalgScalar>(
    a: &Array<B, T>,
    taus: &Array<B, T>,
) -> Array<B, T> {
    Array(B::householder_product::<T>(&a.0, &taus.0))
}

/// `q c`, `q^H c` (`transpose`), `c q`, or `c q^H` (not `left`), where `q`
/// is the product of the Householder reflectors of `a` with the factors
/// `taus`, without forming `q`, as `lax.linalg.ormqr` (LAPACK's `ormqr`).
/// Not differentiable, as in JAX.
///
/// # Panics
///
/// Panics if the shapes do not match.
#[track_caller]
pub fn ormqr<B: Backend, T: LinalgScalar>(
    a: &Array<B, T>,
    taus: &Array<B, T>,
    c: &Array<B, T>,
    left: bool,
    transpose: bool,
) -> Array<B, T> {
    Array(B::ormqr::<T>(&a.0, &taus.0, &c.0, left, transpose))
}

/// The rank-1 update of a Cholesky factorization, as
/// `lax.linalg.cholesky_update`: given the upper triangular `r` of
/// `a = r^T r` and the vector `w`, the upper triangular factor of
/// `a + w w^T` in `O(n^2)` (by Givens rotations, as JAX computes it on
/// CPU; the diagonal may come out negative). Real matrices only, not
/// differentiable, as in JAX.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax::linalg::cholesky_update};
///
/// // a = r^T r = [[4, 2], [2, 5]]; a + w w^T = [[5, 4], [4, 9]].
/// let r = Array::<Native, f64>::from_vec(vec![2.0, 1.0, 0.0, 2.0], [2, 2]);
/// let w = Array::<Native, f64>::from_vec(vec![1.0, 2.0], [2]);
/// let r = cholesky_update(&r, &w).to_vec();
/// let a = [
///     r[0] * r[0],
///     r[0] * r[1],
///     r[1] * r[1] + r[3] * r[3],
/// ];
/// for (got, expected) in a.iter().zip([5.0, 4.0, 9.0]) {
///     assert!((got - expected).abs() < 1e-12);
/// }
/// ```
///
/// # Panics
///
/// Panics if `r` is not square or `w` does not match it.
#[track_caller]
pub fn cholesky_update<B: Backend, T: LinalgFloat>(
    r: &Array<B, T>,
    w: &Array<B, T>,
) -> Array<B, T> {
    Array(B::cholesky_update::<T>(&r.0, &w.0))
}

/// `alpha a a^T + beta c` for each `a` (`[..., m, n]`) and symmetric `c`
/// (`[..., m, m]`), as `lax.linalg.symmetric_product` (with
/// `symmetrize_output`, the upper triangle is replaced by the transpose of
/// the lower one; JAX guarantees only the lower triangle otherwise, which
/// cuBLAS's `syrk` computes on GPU). Real matrices only, not
/// differentiable, as in JAX.
///
/// # Panics
///
/// Panics if the shapes do not match.
#[track_caller]
pub fn symmetric_product<B: Backend, T: LinalgFloat>(
    a: &Array<B, T>,
    c: &Array<B, T>,
    alpha: f64,
    beta: f64,
    symmetrize_output: bool,
) -> Array<B, T> {
    let result = Array(B::symmetric_product::<T>(&a.0, &c.0, alpha, beta));
    if !symmetrize_output {
        return result;
    }
    // JAX: `tril(result) + tril(result, -1)^T`.
    let upper = adjoint(&tril(&result, -1));
    tril(&result, 0) + upper
}

/// The reduction of each Hermitian (symmetric) matrix to real tridiagonal
/// form by a unitary similarity, as `lax.linalg.tridiagonal`, reading only
/// the `lower` (or upper) triangle: `(a, d, e, taus)` with the diagonal `d`
/// and the off-diagonal `e` (real), and in that triangle of `a` the
/// tridiagonal form and the Householder reflectors (with the factors
/// `taus`) below (above) the off-diagonal; the other triangle is that of
/// the input. Not differentiable, as in JAX.
///
/// # Panics
///
/// Panics if `x` is not a batch of nonempty square matrices.
#[track_caller]
#[allow(clippy::type_complexity)] // The four results of `sytrd`.
pub fn tridiagonal<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    lower: bool,
) -> (
    Array<B, T>,
    Array<B, T::Real>,
    Array<B, T::Real>,
    Array<B, T>,
) {
    let (a, d, e, taus) = B::tridiagonal::<T>(&x.0, lower);
    (Array(a), Array(d), Array(e), Array(taus))
}

/// The solution `x` of `A x = b` for each tridiagonal matrix `A`, as
/// `lax.linalg.tridiagonal_solve`: `dl[..., i] = A[i, i - 1]` (`dl[..., 0]`
/// is ignored), `d[..., i] = A[i, i]`, and `du[..., i] = A[i, i + 1]`
/// (`du[..., m - 1]` is ignored), each `[..., m]`, and `b` is
/// `[..., m, n]`. Gaussian elimination with partial pivoting (LAPACK's
/// `gtsv`): singular systems give NaNs, unless `perturb_singular`, which
/// perturbs tiny pivots so that numerically singular systems (as in inverse
/// iteration) give finite solutions. Differentiable in all inputs.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax::linalg::tridiagonal_solve};
///
/// // [[2, 1, 0], [1, 2, 1], [0, 1, 2]] x = [4, 8, 8]
/// let dl = Array::<Native, f64>::from_vec(vec![0.0, 1.0, 1.0], [3]);
/// let d = Array::<Native, f64>::from_vec(vec![2.0, 2.0, 2.0], [3]);
/// let du = Array::<Native, f64>::from_vec(vec![1.0, 1.0, 0.0], [3]);
/// let b = Array::<Native, f64>::from_vec(vec![4.0, 8.0, 8.0], [3, 1]);
/// let x = tridiagonal_solve(&dl, &d, &du, &b, false);
/// let x = x.to_vec();
/// for (got, expected) in x.iter().zip([1.0, 2.0, 3.0]) {
///     assert!((got - expected).abs() < 1e-12);
/// }
/// ```
///
/// # Panics
///
/// Panics if the shapes do not match.
#[track_caller]
pub fn tridiagonal_solve<B: Backend, T: LinalgScalar>(
    dl: &Array<B, T>,
    d: &Array<B, T>,
    du: &Array<B, T>,
    b: &Array<B, T>,
    perturb_singular: bool,
) -> Array<B, T> {
    Array(B::tridiagonal_solve::<T>(
        &dl.0,
        &d.0,
        &du.0,
        &b.0,
        perturb_singular,
    ))
}

/// The singular value decomposition of each matrix, as `lax.linalg.svd`:
/// `(u, s, vt)` with the real singular values `s` in descending order and
/// `x = u diag(s) vt`. With `full_matrices`, `u` is `[..., m, m]` and `vt`
/// is `[..., n, n]`; otherwise `[..., m, k]` and `[..., k, n]` for
/// `k = min(m, n)`. The signs (phases) make the component of largest
/// magnitude of each column of `u` real and positive.
///
/// With `subset_by_index` `(start, end)` (not with `full_matrices`), only
/// the singular values of indices `start..end` and their vectors are
/// returned (computed from the whole decomposition; JAX supports it on TPU
/// only), and they are not differentiable. `algorithm` chooses the
/// algorithm as JAX's (`None` for the platform's default; natively,
/// one-sided Jacobi rotations for [`SvdAlgorithm::Jacobi`], the QR
/// algorithm otherwise).
///
/// # Panics
///
/// Panics if `x` is not a batch of matrices, or the range is out of
/// bounds or given with `full_matrices`.
#[track_caller]
pub fn svd<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    full_matrices: bool,
    subset_by_index: Option<(usize, usize)>,
    algorithm: Option<SvdAlgorithm>,
) -> Svd<B, T> {
    matrix_dims("svd", x);
    let (s, uv) = B::svd::<T>(&x.0, full_matrices, true, subset_by_index, algorithm);
    let (u, vt) = uv.expect("compute_uv");
    (Array(u), Array(s), Array(vt))
}

/// The singular values of each matrix in descending order
/// (`lax.linalg.svd` with `compute_uv=False`), only those of indices
/// `start..end` with `subset_by_index` (differentiable), by `algorithm` (as
/// in [`svd`]).
///
/// # Panics
///
/// Panics if `x` is not a batch of matrices, or the range is out of
/// bounds.
#[track_caller]
pub fn svd_values<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    subset_by_index: Option<(usize, usize)>,
    algorithm: Option<SvdAlgorithm>,
) -> Array<B, T::Real> {
    matrix_dims("svd", x);
    // `full_matrices` does not matter without the vectors, but cannot be
    // set together with a subset.
    let full = subset_by_index.is_none();
    let (s, _) = B::svd::<T>(&x.0, full, false, subset_by_index, algorithm);
    Array(s)
}

/// The polar decomposition `x = u h` of a full-rank matrix (`m x n` with
/// `m >= n`) by the QR-based dynamically weighted Halley iteration, as
/// `lax.linalg.qdwh`: `(u, h, num_iters, is_converged)` with `u` (`m x n`)
/// having orthonormal columns and `h` (`n x n`) Hermitian positive
/// semidefinite. The iteration follows JAX's (`jax._src.tpu.linalg.qdwh`):
/// the scaling by `1 / sqrt(|x|_1 |x|_inf)`, the weights of the steps
/// computed in advance from the lower bound `eps` of the smallest singular
/// value (QR steps while `c > 100`, then Cholesky steps), Halley's steps
/// until `|u_k - u_{k-1}|_F <= (5 eps)^(1/3)` within `max_iterations` (10
/// by default), and a Newton-Schulz refinement. `eps` defaults to the
/// machine epsilon of `T`. With `dynamic_shape` `(m, n)`, `x` is a matrix
/// padded from its true shape `m x n` (which may be traced values), as in
/// JAX: the entries outside are taken as zeros and stay zeros. (JAX's unused
/// `is_hermitian` is left out.)
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, jnp, lax::linalg::qdwh};
///
/// let x = Array::<Native, f64>::from_vec(vec![3.0, 1.0, 1.0, 2.0, 0.0, 1.0], [3, 2]);
/// let (u, h, _, converged) = qdwh(&x, None, None, None);
/// assert!(converged.value());
/// let back = jnp::matmul(&u, &h).to_vec();
/// for (got, expected) in back.iter().zip(x.to_vec()) {
///     assert!((got - expected).abs() < 1e-12);
/// }
/// ```
///
/// # Panics
///
/// Panics if `x` is not a matrix with at least as many rows as columns.
#[track_caller]
#[allow(clippy::type_complexity)] // The four results of `qdwh`.
pub fn qdwh<B: Backend, T: LinalgScalar>(
    x: &Array<B, T>,
    max_iterations: Option<usize>,
    eps: Option<f64>,
    dynamic_shape: Option<(I32<B>, I32<B>)>,
) -> (Array<B, T>, Array<B, T>, I32<B>, Bool<B>) {
    let dims = x.shape().dims().to_vec();
    assert!(
        dims.len() == 2 && dims[0] >= dims[1],
        "qdwh: the input must be a matrix of M x N with M >= N, got {dims:?}"
    );
    let (m, n) = (dims[0], dims[1]);
    let max_iterations = max_iterations.unwrap_or(10);
    let eps = eps.unwrap_or_else(|| {
        ruxla_kernels::cast::<T::Real, f64>(
            <T::Real as ruxla_kernels::linalg::LinalgFloat>::EPSILON,
        )
    });
    let t = |v: f64| ruxla_kernels::cast::<f64, T>(v);
    let real = |v: f64| ruxla_kernels::cast::<f64, T::Real>(v);
    let eye =
        lax::convert_element_type::<B, bool, T>(&lax::iota::<B, i32>([n, n], 0).eq(lax::iota::<
            B,
            i32,
        >(
            [n, n], 1
        )));

    // JAX's `_mask`: the entries of an `r x c` array outside the true shape
    // replaced by those of `alternative`.
    let mask = |a: &Array<B, T>, rows: I32<B>, cols: I32<B>, alternative: &Array<B, T>| {
        let dims = a.shape().dims().to_vec();
        let inside = lax::iota::<B, i32>(dims.as_slice(), 0).lt(rows)
            & lax::iota::<B, i32>(dims.as_slice(), 1).lt(cols);
        jnp::where_(inside, a, alternative)
    };
    let zeros = |a: &Array<B, T>| a * t(0.0);
    let x = &match dynamic_shape {
        Some((rows, cols)) => mask(x, rows, cols, &zeros(x)),
        None => x.clone(),
    };
    // `alpha >= |x|_2`, from the 1-norm and the infinity norm.
    let magnitudes = jnp::abs(x);
    let one_norm = jnp::max(jnp::sum(&magnitudes, 0i64), 0i64);
    let inf_norm = jnp::max(jnp::sum(&magnitudes, 1i64), 0i64);
    let alpha_inverse = lax::rsqrt(&one_norm) * lax::rsqrt(&inf_norm);
    let alpha_inverse = jnp::where_(one_norm.eq(real(0.0)), real(1.0), &alpha_inverse);
    let mut u = x * &lax::convert_element_type::<B, T::Real, T>(&alpha_inverse);

    // The weights of the steps, computed in advance from the bound `l`.
    let tol_l = 10.0 * eps / 2.0;
    let tol_norm = real(tol_l.cbrt());
    let mut l = eps;
    let mut qr_coefs = Vec::new();
    let mut chol_coefs = Vec::new();
    let mut k = 0;
    while l + tol_l < 1.0 && k < max_iterations {
        k += 1;
        let l2 = l * l;
        let dd = (4.0 * (1.0 / l2 - 1.0) / l2).powf(1.0 / 3.0);
        let sqd = (1.0 + dd).sqrt();
        let a = sqd + (2.0 - dd + 2.0 * (2.0 - l2) / (l2 * sqd)).sqrt();
        let b = (a - 1.0) * (a - 1.0) / 4.0;
        let c = a + b - 1.0;
        l = l * (a + b * l2) / (1.0 + c * l2);
        let e = b / c;
        if c > 100.0 {
            let sqrt_c = c.sqrt();
            qr_coefs.push(((a - e) / sqrt_c, sqrt_c, e));
        } else {
            chol_coefs.push((a - e, c, e));
        }
    }

    // A QR step: `y = [sqrt(c) u; I] = q r`, `u = e u + (a - e) / sqrt(c)
    // q1 q2^H`.
    let qr_step = |u: &Array<B, T>, (a_minus_e_by_sqrt_c, sqrt_c, e): (f64, f64, f64)| {
        let scaled = u * t(sqrt_c);
        let (q1, q2) = match dynamic_shape {
            None => {
                let y = jnp::concatenate(&[scaled, eye.clone()], 0);
                let (q, _) = qr(&y, false);
                let q1 = lax::slice(&q, &[0, 0], &[m, n], None);
                (q1, lax::slice(&q, &[m, 0], &[m + n, n], None))
            }
            Some((rows, cols)) => {
                // JAX's `_dynamic_concat`: the identity written after the
                // true rows.
                let padded = lax::pad(&scaled, t(0.0), &[(0, n as i64, 0), (0, 0, 0)]);
                let y = lax::dynamic_update_slice(&padded, &eye, &[rows, I32::new(0)]);
                let (q, _) = qr(&y, false);
                let q1 = lax::slice(&q, &[0, 0], &[m, n], None);
                let q1 = mask(&q1, rows, cols, &zeros(&q1));
                let q2 = lax::dynamic_slice(&q, &[rows, I32::new(0)], &[n, n]);
                (q1, mask(&q2, cols, cols, &zeros(&q2)))
            }
        };
        u * t(e) + jnp::matmul(&q1, &adjoint(&q2)) * t(a_minus_e_by_sqrt_c)
    };
    // A Cholesky step: `y y^H = c u^H u + I`, `u = e u + (a - e) u y^-H
    // y^-1`.
    let cholesky_step = |u: &Array<B, T>, (a_minus_e, c, e): (f64, f64, f64)| {
        let gram = jnp::matmul(&adjoint(u), u) * t(c) + &eye;
        // The identity in the padded corner keeps it positive definite.
        let gram = match dynamic_shape {
            Some((_, cols)) => mask(&gram, cols, cols, &eye),
            None => gram,
        };
        let y = cholesky(&gram, false);
        let solve = |b: &Array<B, T>, transpose_a: bool| {
            triangular_solve(
                &y,
                b,
                TriangularSolveOptions {
                    left_side: true,
                    lower: true,
                    transpose_a,
                    conjugate_a: true,
                    unit_diagonal: false,
                },
            )
        };
        let z = conj(&solve(&mt(u), false));
        let z = adjoint(&solve(&z, true));
        u * t(e) + z * t(a_minus_e)
    };
    let changed = |u: &Array<B, T>, previous: &Array<B, T>| {
        // `|d|^2` (JAX's `real(d conj(d))`, which only rounds differently).
        let magnitudes = jnp::abs(u - previous);
        let squares = &magnitudes * &magnitudes;
        lax::sqrt(&jnp::sum(&squares, &[0i64, 1][..]))
            .gt(tol_norm)
            .to_scalar()
    };

    for &coefs in &qr_coefs {
        u = qr_step(&u, coefs);
    }
    let mut not_converged = Bool::<B>::new(true);
    for &coefs in &chol_coefs {
        let previous = u.clone();
        u = cholesky_step(&u, coefs);
        not_converged = changed(&u, &previous);
    }
    // Halley's steps (`a, b, c = 3, 1, 3`) until convergence.
    let halley = (3.0 - 1.0 / 3.0, 3.0, 1.0 / 3.0);
    let start =
        I32::<B>::new(i32::try_from(qr_coefs.len() + chol_coefs.len()).expect("iterations"));
    let limit = i32::try_from(max_iterations).expect("max_iterations");
    let (num_iters, u, not_converged) = while_loop(
        |(k, _, not_converged): &(I32<B>, Array<B, T>, Bool<B>)| *not_converged & k.lt(limit),
        |(k, u, _)| {
            let next = cholesky_step(&u, halley);
            let not_converged = changed(&next, &u);
            (k + 1, next, not_converged)
        },
        (start, u, not_converged),
    );

    // The Newton-Schulz refinement, and `h = u^H x`, symmetrized.
    let uh = adjoint(&u);
    let u = &u * t(1.5) - jnp::matmul(&u, &jnp::matmul(&uh, &u)) * t(0.5);
    let h = jnp::matmul(&adjoint(&u), x);
    let h = (&h + &adjoint(&h)) / t(2.0);
    (u, h, num_iters, !not_converged)
}

/// The complex conjugate (the value itself for real types).
fn conj<B: Backend, T: LinalgScalar>(x: &Array<B, T>) -> Array<B, T> {
    if T::DTYPE.is_complex() {
        Array(B::a_conj::<T>(&x.0))
    } else {
        x.clone()
    }
}