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
//! Linear algebra following `jax.numpy.linalg` (and NumPy's semantics), on
//! matrices and batches of matrices (see [`lax::linalg`]
//! for the decompositions). The decompositions and solves (`cholesky`,
//! `solve`, `inv`, `qr`, `eigh`, `eigvalsh`, `svd`, `svdvals`) take `f32`,
//! `f64`, `c64`, and `c128`; `det`, `slogdet`, and `norm` take `f32` and
//! `f64`.

use ruxla_ir::{GatherDims, GatherScatterMode, Shape};

use crate::backend::Backend;
use crate::jnp;
use crate::lax;
use crate::lax::linalg::TriangularSolveOptions;
use crate::value::{Array, LinalgFloat, LinalgScalar, broadcast_shapes};

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

/// `shape` with its last `k` dimensions replaced by `tail`.
fn with_tail(batch: &Shape, tail: &[usize]) -> Shape {
    let mut d = batch.dims().to_vec();
    d.extend_from_slice(tail);
    Shape::from(d)
}

/// The leading (batch) dimensions of a batch of matrices.
fn batch_of(shape: &Shape, core: usize) -> Shape {
    Shape::from(shape.dims()[..shape.rank() - core].to_vec())
}

/// The rows of each matrix of `x` (`[..., m, k]`) permuted by `perm`
/// (`i32[..., m]`): row `i` of the result is row `perm[i]` of `x`.
fn permute_rows<B: Backend, T: LinalgScalar>(x: &Array<B, T>, perm: &Array<B, i32>) -> Array<B, T> {
    let shape = x.shape();
    let nb = shape.rank() - 2;
    let mut index_shape = perm.shape().dims().to_vec();
    index_shape.push(1);
    let indices = perm.reshape(index_shape);
    let batch: Vec<usize> = (0..nb).collect();
    let dims = GatherDims {
        offset_dims: vec![nb + 1],
        collapsed_slice_dims: vec![nb],
        start_index_map: vec![nb],
        operand_batching_dims: batch.clone(),
        start_indices_batching_dims: batch,
    };
    let mut sizes = vec![1; nb + 1];
    sizes.push(shape[nb + 1]);
    lax::gather(
        x,
        &indices,
        &dims,
        &sizes,
        GatherScatterMode::PromiseInBounds,
    )
}

/// Solves `a x = b` with the LU factors of `a` (JAX's `_lu_solve_core`
/// with `trans = 0`), for `b` of shape `[..., n, k]` with `a`'s batch.
fn lu_solve<B: Backend, T: LinalgScalar>(
    lu: &Array<B, T>,
    perm: &Array<B, i32>,
    b: &Array<B, T>,
) -> Array<B, T> {
    let x = permute_rows(b, perm);
    let x = lax::linalg::triangular_solve(
        lu,
        &x,
        TriangularSolveOptions {
            left_side: true,
            lower: true,
            unit_diagonal: true,
            ..Default::default()
        },
    );
    lax::linalg::triangular_solve(
        lu,
        &x,
        TriangularSolveOptions {
            left_side: true,
            lower: false,
            ..Default::default()
        },
    )
}

/// The Cholesky factor `L` (lower triangular, `a = L L^T`) of each
/// symmetric positive definite matrix, as `jnp.linalg.cholesky` (the input
/// is symmetrized first). Matrices that are not positive definite give
/// NaNs.
///
/// # Panics
///
/// Panics if `a` is not a batch of square matrices.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, jnp};
///
/// let a = Array::<Native, f64>::from_vec(vec![4.0, 2.0, 2.0, 5.0], [2, 2]);
/// assert_eq!(jnp::linalg::cholesky(&a).to_vec(), [2.0, 0.0, 1.0, 2.0]);
/// ```
#[track_caller]
pub fn cholesky<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> Array<B, T> {
    square("cholesky", a);
    lax::linalg::cholesky(a, true)
}

/// Solves `a x = b` for `x`, as `jnp.linalg.solve`: `b` of shape `[n]` is a
/// vector (the result is `[..., n]`), otherwise a batch of matrices
/// `[..., n, k]` whose batch dimensions broadcast with `a`'s. The solve
/// uses the LU factorization of `a`; singular matrices give infinities or
/// NaNs.
///
/// JAX differentiates the solve implicitly (`custom_linear_solve`); ruxla
/// differentiates through the factorization, which gives the same
/// derivatives.
///
/// # Panics
///
/// Panics if `a` is not a batch of square matrices or the shapes do not
/// match.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, jnp};
///
/// let a = Array::<Native, f64>::from_vec(vec![2.0, 1.0, 1.0, 3.0], [2, 2]);
/// let b = Array::<Native, f64>::from_vec(vec![3.0, 5.0], [2]);
/// let x = jnp::linalg::solve(&a, &b).to_vec();
/// assert!((x[0] - 0.8).abs() < 1e-12 && (x[1] - 1.4).abs() < 1e-12);
/// ```
#[track_caller]
pub fn solve<B: Backend, T: LinalgScalar>(a: &Array<B, T>, b: &Array<B, T>) -> Array<B, T> {
    let n = square("solve", a);
    let a_shape = a.shape();
    let b_shape = b.shape();
    let a_batch = batch_of(&a_shape, 2);
    if b_shape.rank() == 1 {
        assert_eq!(
            b_shape[0], n,
            "solve: shapes [{a_shape}] and [{b_shape}] do not match"
        );
        let b = b.reshape([n, 1]).broadcast_to(with_tail(&a_batch, &[n, 1]));
        let (lu, _, perm) = lax::linalg::lu(a);
        let x = lu_solve(&lu, &perm, &b);
        return x.reshape(with_tail(&a_batch, &[n]));
    }
    let rank = b_shape.rank();
    assert!(
        b_shape[rank - 2] == n,
        "solve: shapes [{a_shape}] and [{b_shape}] do not match"
    );
    let batch = broadcast_shapes(&a_batch, &batch_of(&b_shape, 2));
    let a = a.broadcast_to(with_tail(&batch, &[n, n]));
    let b = b.broadcast_to(with_tail(&batch, &[n, b_shape[rank - 1]]));
    let (lu, _, perm) = lax::linalg::lu(&a);
    lu_solve(&lu, &perm, &b)
}

/// The inverse of each square matrix, as `jnp.linalg.inv` (a solve with the
/// identity).
///
/// # Panics
///
/// Panics if `a` is not a batch of square matrices.
#[track_caller]
pub fn inv<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> Array<B, T> {
    let n = square("inv", a);
    let eye =
        lax::convert_element_type::<B, bool, T>(&lax::iota::<B, i32>([n, n], 0).eq(lax::iota::<
            B,
            i32,
        >(
            [n, n], 1
        )));
    let eye = eye.broadcast_to(a.shape());
    solve(a, &eye)
}

/// The diagonals of a batch of square matrices.
fn diagonal<B: Backend, T: LinalgFloat>(x: &Array<B, T>) -> Array<B, T> {
    let shape = x.shape();
    let rank = shape.rank();
    let n = shape[rank - 1];
    let eye = lax::iota::<B, i32>([n, n], 0).eq(lax::iota::<B, i32>([n, n], 1));
    let zero = ruxla_kernels::cast::<f64, T>(0.0);
    let on = jnp::where_(eye, x, zero);
    lax::reduce_sum(&on, &[rank - 1])
}

/// The sign and the natural logarithm of the absolute value of the
/// determinant of each square matrix, as `jnp.linalg.slogdet` (from the LU
/// factorization). Singular matrices give a sign of 0 and `-inf`.
///
/// # Panics
///
/// Panics if `a` is not a batch of square matrices.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, jnp};
///
/// let a = Array::<Native, f64>::from_vec(vec![0.0, 2.0, 3.0, 0.0], [2, 2]);
/// let (sign, logdet) = jnp::linalg::slogdet(&a);
/// assert_eq!(sign.to_vec(), [-1.0]);
/// assert!((logdet.to_vec()[0] - 6f64.ln()).abs() < 1e-12);
/// ```
#[track_caller]
pub fn slogdet<B: Backend, T: LinalgFloat>(a: &Array<B, T>) -> (Array<B, T>, Array<B, T>) {
    let n = square("slogdet", a);
    let (lu, pivots, _) = lax::linalg::lu(a);
    let diag = diagonal(&lu);
    let last = diag.ndim() - 1;
    let zero = ruxla_kernels::cast::<f64, T>(0.0);
    let is_zero = jnp::any(diag.eq(zero), last as i64);
    let iota = lax::iota::<B, i32>([n], 0).broadcast_to(pivots.shape());
    let swaps = lax::convert_element_type::<B, bool, i32>(&pivots.ne(&iota));
    let negative = lax::convert_element_type::<B, bool, i32>(&diag.lt(zero));
    let parity = jnp::sum(swaps, last as i64) + jnp::sum(negative, last as i64);
    let odd = lax::convert_element_type::<B, i32, T>(&jnp::fmod(&parity, 2i32));
    let one = ruxla_kernels::cast::<f64, T>(1.0);
    let two = ruxla_kernels::cast::<f64, T>(2.0);
    let sign = jnp::where_(&is_zero, zero, (odd * -two) + one);
    let neg_inf = ruxla_kernels::cast::<f64, T>(f64::NEG_INFINITY);
    let logdet = jnp::where_(
        &is_zero,
        neg_inf,
        jnp::sum(jnp::log(jnp::abs(&diag)), last as i64),
    );
    (sign, logdet)
}

/// The determinant of each square matrix, as `jnp.linalg.det`: the sign
/// times the exponential of the log-determinant from [`slogdet`] (JAX uses
/// closed forms for 2 x 2 and 3 x 3 matrices, which round differently).
///
/// # Panics
///
/// Panics if `a` is not a batch of square matrices.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, jnp};
///
/// let a = Array::<Native, f64>::from_vec(vec![1.0, 2.0, 3.0, 4.0], [2, 2]);
/// assert!((jnp::linalg::det(&a).to_vec()[0] + 2.0).abs() < 1e-12);
/// ```
#[track_caller]
pub fn det<B: Backend, T: LinalgFloat>(a: &Array<B, T>) -> Array<B, T> {
    let (sign, logdet) = slogdet(a);
    sign * jnp::exp(logdet)
}

/// The shape of `q` of [`qr`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum QrMode {
    /// `q` is `[..., m, k]` and `r` is `[..., k, n]`, for `k = min(m, n)`
    /// (NumPy's `"reduced"`, the default).
    #[default]
    Reduced,
    /// `q` is `[..., m, m]` and `r` is `[..., m, n]` (`"complete"`).
    Complete,
}

/// The QR decomposition of each matrix, as `jnp.linalg.qr` (NumPy's mode
/// `"r"` is the second result).
///
/// # Panics
///
/// Panics if `a` is not a batch of matrices.
#[track_caller]
pub fn qr<B: Backend, T: LinalgScalar>(
    a: &Array<B, T>,
    mode: QrMode,
) -> (Array<B, T>, Array<B, T>) {
    lax::linalg::qr(a, mode == QrMode::Complete)
}

/// The eigenvalues (ascending) and eigenvectors (columns) of each symmetric
/// matrix, as `jnp.linalg.eigh` (the input is symmetrized first).
///
/// # Panics
///
/// Panics if `a` is not a batch of square matrices.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, jnp};
///
/// let a = Array::<Native, f64>::from_vec(vec![2.0, 1.0, 1.0, 2.0], [2, 2]);
/// let (w, v) = jnp::linalg::eigh(&a);
/// assert!((w.to_vec()[0] - 1.0).abs() < 1e-12 && (w.to_vec()[1] - 3.0).abs() < 1e-12);
/// assert_eq!(v.shape().dims(), [2, 2]);
/// ```
#[track_caller]
pub fn eigh<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> (Array<B, T::Real>, Array<B, T>) {
    square("eigh", a);
    let (v, w) = lax::linalg::eigh(a, true, true, true, None, None);
    (w, v)
}

/// The eigenvalues (ascending) of each symmetric matrix, as
/// `jnp.linalg.eigvalsh`.
///
/// # Panics
///
/// Panics if `a` is not a batch of square matrices.
#[track_caller]
pub fn eigvalsh<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> Array<B, T::Real> {
    eigh(a).0
}

/// The singular value decomposition `(u, s, vh)` of each matrix, as
/// `jnp.linalg.svd` (see [`lax::linalg::svd`]).
///
/// # Panics
///
/// Panics if `a` is not a batch of matrices.
#[track_caller]
pub fn svd<B: Backend, T: LinalgScalar>(
    a: &Array<B, T>,
    full_matrices: bool,
) -> lax::linalg::Svd<B, T> {
    lax::linalg::svd(a, full_matrices, None, None)
}

/// The singular values of each matrix in descending order, as
/// `jnp.linalg.svdvals`.
///
/// # Panics
///
/// Panics if `a` is not a batch of matrices.
#[track_caller]
pub fn svdvals<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> Array<B, T::Real> {
    lax::linalg::svd_values(a, None, None)
}

/// The kind of norm of [`norm`] (NumPy's `ord`).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum NormOrd {
    /// `ord=None`: the 2-norm of vectors, the Frobenius norm of matrices.
    #[default]
    Default,
    /// `'fro'`: the Frobenius norm (matrices).
    Fro,
    /// `'nuc'`: the sum of the singular values (matrices).
    Nuc,
    /// `inf`: the largest absolute value (vectors), the largest absolute
    /// row sum (matrices).
    Inf,
    /// `-inf`: the smallest absolute value (vectors), the smallest absolute
    /// row sum (matrices).
    NegInf,
    /// A number: `sum(|x|^p)^(1/p)` for vectors (0 counts the nonzero
    /// elements); for matrices, 1 and -1 (the largest and smallest absolute
    /// column sums) and 2 and -2 (the largest and smallest singular values).
    P(f64),
}

/// The axes of [`norm`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NormAxes {
    /// `axis=None`: all axes (with [`NormOrd::Default`], the 2-norm of the
    /// flattened array of any rank; otherwise a vector or a matrix).
    #[default]
    All,
    /// One axis: vector norms.
    Vector(i64),
    /// Two axes (rows, columns): matrix norms.
    Matrix(i64, i64),
}

/// A norm of vectors or matrices, as `jnp.linalg.norm`.
///
/// # Panics
///
/// Panics if the axes are out of range, or if `ord` is not a norm of the
/// kind the axes select.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, jnp};
/// use ruxla_core::jnp::linalg::{NormAxes, NormOrd};
///
/// let x = Array::<Native, f64>::from_vec(vec![3.0, -4.0], [2]);
/// assert_eq!(jnp::linalg::norm(&x, NormOrd::Default, NormAxes::All, false).to_vec(), [5.0]);
/// assert_eq!(jnp::linalg::norm(&x, NormOrd::Inf, NormAxes::All, false).to_vec(), [4.0]);
/// ```
#[track_caller]
pub fn norm<B: Backend, T: LinalgFloat>(
    x: &Array<B, T>,
    ord: NormOrd,
    axes: NormAxes,
    keepdims: bool,
) -> Array<B, T> {
    let rank = x.ndim();
    let shape = x.shape();
    let axes: Vec<usize> = match axes {
        NormAxes::All if ord == NormOrd::Default => {
            let all: Vec<usize> = (0..rank).collect();
            let y = jnp::sqrt(lax::reduce_sum(&(x * x), &all));
            return keep(y, &shape, &all, keepdims);
        }
        NormAxes::All => (0..rank).collect(),
        NormAxes::Vector(a) => vec![jnp::normalize_axis(a, rank)],
        NormAxes::Matrix(r, c) => vec![jnp::normalize_axis(r, rank), jnp::normalize_axis(c, rank)],
    };
    let y = match axes.as_slice() {
        [a] => vector_norm(x, ord, *a),
        [r, c] => {
            assert!(r != c, "norm: the two axes must differ");
            matrix_norm(x, ord, *r, *c)
        }
        _ => panic!("norm: pass one axis for a vector norm or two for a matrix norm, got {axes:?}"),
    };
    let mut sorted = axes.clone();
    sorted.sort_unstable();
    keep(y, &shape, &sorted, keepdims)
}

/// `y` with the reduced `axes` of `shape` kept as dimensions of size 1.
fn keep<B: Backend, T: LinalgFloat>(
    y: Array<B, T>,
    shape: &Shape,
    axes: &[usize],
    keepdims: bool,
) -> Array<B, T> {
    if !keepdims {
        return y;
    }
    let dims: Vec<usize> = (0..shape.rank())
        .map(|d| if axes.contains(&d) { 1 } else { shape[d] })
        .collect();
    y.reshape(dims)
}

fn vector_norm<B: Backend, T: LinalgFloat>(
    x: &Array<B, T>,
    ord: NormOrd,
    axis: usize,
) -> Array<B, T> {
    let ax = axis as i64;
    let zero = ruxla_kernels::cast::<f64, T>(0.0);
    match ord {
        NormOrd::Default | NormOrd::P(2.0) => jnp::sqrt(jnp::sum(x * x, ax)),
        NormOrd::Inf => jnp::maximum(jnp::max(jnp::abs(x), ax), zero),
        NormOrd::NegInf => jnp::min(jnp::abs(x), ax),
        NormOrd::P(0.0) => jnp::sum(lax::convert_element_type::<B, bool, T>(&x.ne(zero)), ax),
        NormOrd::P(1.0) => jnp::sum(jnp::abs(x), ax),
        NormOrd::P(p) => {
            let p_t = ruxla_kernels::cast::<f64, T>(p);
            let inv = ruxla_kernels::cast::<f64, T>(1.0 / p);
            jnp::power(jnp::sum(jnp::power(jnp::abs(x), p_t), ax), inv)
        }
        NormOrd::Fro | NormOrd::Nuc => panic!("norm: {ord:?} is not a vector norm"),
    }
}

fn matrix_norm<B: Backend, T: LinalgFloat>(
    x: &Array<B, T>,
    ord: NormOrd,
    row: usize,
    col: usize,
) -> Array<B, T> {
    let zero = ruxla_kernels::cast::<f64, T>(0.0);
    // The axis left after reducing `first` (which shifts later axes).
    let after =
        |first: usize, second: usize| (if second > first { second - 1 } else { second }) as i64;
    match ord {
        NormOrd::Default | NormOrd::Fro => {
            let mut axes = [row, col];
            axes.sort_unstable();
            jnp::sqrt(lax::reduce_sum(&(x * x), &axes))
        }
        NormOrd::P(1.0) => {
            let sums = jnp::sum(jnp::abs(x), row as i64);
            jnp::maximum(jnp::max(sums, after(row, col)), zero)
        }
        NormOrd::P(-1.0) => {
            let sums = jnp::sum(jnp::abs(x), row as i64);
            jnp::min(sums, after(row, col))
        }
        NormOrd::Inf => {
            let sums = jnp::sum(jnp::abs(x), col as i64);
            jnp::maximum(jnp::max(sums, after(col, row)), zero)
        }
        NormOrd::NegInf => {
            let sums = jnp::sum(jnp::abs(x), col as i64);
            jnp::min(sums, after(col, row))
        }
        NormOrd::Nuc | NormOrd::P(2.0) | NormOrd::P(-2.0) => {
            // Move the axes last (`jnp.moveaxis(x, axis, (-2, -1))`).
            let rank = x.ndim();
            let mut perm: Vec<usize> = (0..rank).filter(|&d| d != row && d != col).collect();
            perm.push(row);
            perm.push(col);
            let s = lax::linalg::svd_values(&x.transpose(&perm), None, None);
            let last = (rank - 2) as i64;
            match ord {
                NormOrd::P(2.0) => jnp::maximum(jnp::max(&s, last), zero),
                NormOrd::P(_) => jnp::min(&s, last),
                _ => jnp::sum(&s, last),
            }
        }
        NormOrd::P(p) => panic!("norm: invalid order {p} for a matrix norm"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Native;
    use crate::lax::linalg::mt;
    use ruxla_ir::Precision;

    /// The batched matrix product `a @ b` of operands with the same batch
    /// dimensions.
    fn batched_matmul<B: Backend, T: LinalgFloat>(a: &Array<B, T>, b: &Array<B, T>) -> Array<B, T> {
        let rank = a.ndim();
        let batch: Vec<usize> = (0..rank - 2).collect();
        let dims = ruxla_ir::DotDims {
            lhs_contracting: vec![rank - 1],
            rhs_contracting: vec![rank - 2],
            lhs_batch: batch.clone(),
            rhs_batch: batch,
        };
        lax::dot_general_with::<B, T, T>(a, b, &dims, Precision::Highest)
    }

    fn arr(v: &[f64], shape: &[usize]) -> Array<Native, f64> {
        Array::from_vec(v.to_vec(), shape)
    }

    fn close(a: &[f64], b: &[f64]) {
        assert_eq!(a.len(), b.len());
        for (x, y) in a.iter().zip(b) {
            assert!((x - y).abs() < 1e-10, "{a:?} vs {b:?}");
        }
    }

    #[test]
    fn solves_and_inverses() {
        let a = arr(&[4.0, 1.0, 2.0, 1.0, 3.0, 0.0, 2.0, 0.0, 5.0], &[3, 3]);
        let x = arr(&[1.0, -2.0, 3.0, 0.5, 1.5, -1.0], &[3, 2]);
        let b = batched_matmul(&a, &x);
        close(&solve(&a, &b).to_vec(), &x.to_vec());
        let ai = inv(&a);
        let e = batched_matmul(&a, &ai);
        close(&e.to_vec(), &[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
        // A batch of `a` with one right-hand side broadcast.
        let a2 = jnp::stack(&[a.clone(), mt(&a)], 0);
        let b2 = arr(&[1.0, 2.0, 3.0], &[1, 3, 1]);
        assert_eq!(solve(&a2, &b2).shape().dims(), [2, 3, 1]);
        let v = solve(&a2, &arr(&[1.0, 2.0, 3.0], &[3]));
        assert_eq!(v.shape().dims(), [2, 3]);
    }

    #[test]
    fn determinants() {
        let a = arr(&[4.0, 1.0, 2.0, 1.0, 3.0, 0.0, 2.0, 0.0, 5.0], &[3, 3]);
        close(&det(&a).to_vec(), &[4.0 * 15.0 - 5.0 - 2.0 * 6.0]);
        let singular = arr(&[1.0, 2.0, 2.0, 4.0], &[2, 2]);
        let (sign, logdet) = slogdet(&singular);
        assert_eq!(sign.to_vec(), [0.0]);
        assert_eq!(logdet.to_vec(), [f64::NEG_INFINITY]);
    }

    #[test]
    fn norms() {
        let m = arr(&[1.0, -2.0, 3.0, 4.0, 5.0, -6.0], &[2, 3]);
        let n = |ord, axes| norm(&m, ord, axes, false).to_vec();
        close(&n(NormOrd::Default, NormAxes::All), &[91f64.sqrt()]);
        close(&n(NormOrd::P(1.0), NormAxes::All), &[9.0]);
        close(&n(NormOrd::Inf, NormAxes::All), &[15.0]);
        close(&n(NormOrd::NegInf, NormAxes::All), &[6.0]);
        close(&n(NormOrd::P(-1.0), NormAxes::All), &[5.0]);
        close(&n(NormOrd::P(1.0), NormAxes::Vector(1)), &[6.0, 15.0]);
        close(&n(NormOrd::P(0.0), NormAxes::Vector(0)), &[2.0, 2.0, 2.0]);
        close(
            &n(NormOrd::P(3.0), NormAxes::Vector(-1)),
            &[36f64.cbrt(), 405f64.cbrt()],
        );
        let s = svdvals(&m).to_vec();
        close(&n(NormOrd::P(2.0), NormAxes::All), &[s[0]]);
        close(&n(NormOrd::P(-2.0), NormAxes::All), &[s[1]]);
        close(&n(NormOrd::Nuc, NormAxes::Matrix(1, 0)), &[s[0] + s[1]]);
        assert_eq!(
            norm(&m, NormOrd::Fro, NormAxes::Matrix(0, 1), true)
                .shape()
                .dims(),
            [1, 1]
        );
    }
}