Skip to main content

ruxla_kernels/linalg/
products.rs

1//! Products and updates of real matrices that JAX computes with its own
2//! operations on CPU: `cholesky_update` (Givens rotations) and
3//! `symmetric_product` (`alpha a a^T + beta c`).
4
5use super::LinalgFloat;
6
7/// The rank-1 update of each Cholesky factor (`[batch, n, n]`, upper
8/// triangular `r` with `a = r^T r`) by the vector `w` (`[batch, n]`): the
9/// upper triangular factor of `a + w w^T`, as JAX's `cholesky_update_p`
10/// computes it on CPU (`_cholesky_update_jax_fn`): for each `k`, the Givens
11/// rotation of `drotg(r[k, k], w[k])` applied to the row `r[k, :]` and `w`.
12///
13/// # Panics
14///
15/// Panics if the lengths of the buffers do not match the sizes.
16pub fn cholesky_update<T: LinalgFloat>(r: &[T], w: &[T], batch: usize, n: usize) -> Vec<T> {
17    assert_eq!(r.len(), batch * n * n, "cholesky_update: r");
18    assert_eq!(w.len(), batch * n, "cholesky_update: w");
19    let mut out = r.to_vec();
20    let mut z = vec![T::ZERO; n];
21    for b in 0..batch {
22        let r = &mut out[b * n * n..(b + 1) * n * n];
23        z.copy_from_slice(&w[b * n..(b + 1) * n]);
24        for k in 0..n {
25            let (c, s) = drotg(r[k * n + k], z[k]);
26            for j in 0..n {
27                let (x, y) = (r[k * n + j], z[j]);
28                r[k * n + j] = c * x - s * y;
29                z[j] = c * y + s * x;
30            }
31        }
32    }
33    out
34}
35
36/// The coefficients of the Givens rotation of JAX's `_drotg`: `(1, 0)` for
37/// `y = 0`, otherwise `(x, -y) / |(x, y)|`, scaled by `max(|x|, |y|)` first.
38fn drotg<T: LinalgFloat>(x: T, y: T) -> (T, T) {
39    if y == T::ZERO {
40        return (T::ONE, T::ZERO);
41    }
42    let (ax, ay) = (x.abs(), y.abs());
43    let denominator = if ax > ay { ax } else { ay };
44    let (x, y) = (x / denominator, y / denominator);
45    let rh = T::ONE / (x * x + y * y).sqrt();
46    (x * rh, -y * rh)
47}
48
49/// `alpha a a^T + beta c` for each `a` (`[batch, m, n]`) and `c`
50/// (`[batch, m, m]`), as JAX's `symmetric_product_p` computes it on CPU
51/// (the whole matrix; on GPU, cuBLAS's `syrk` gives the lower triangle).
52///
53/// # Panics
54///
55/// Panics if the lengths of the buffers do not match the sizes.
56pub fn symmetric_product<T: LinalgFloat>(
57    a: &[T],
58    c: &[T],
59    batch: usize,
60    m: usize,
61    n: usize,
62    alpha: T,
63    beta: T,
64) -> Vec<T> {
65    assert_eq!(a.len(), batch * m * n, "symmetric_product: a");
66    assert_eq!(c.len(), batch * m * m, "symmetric_product: c");
67    let mut out = vec![T::ZERO; batch * m * m];
68    for b in 0..batch {
69        let a = &a[b * m * n..(b + 1) * m * n];
70        for i in 0..m {
71            for j in 0..m {
72                let mut s = T::ZERO;
73                for k in 0..n {
74                    s = s + a[i * n + k] * a[j * n + k];
75                }
76                let at = b * m * m + i * m + j;
77                out[at] = alpha * s + beta * c[at];
78            }
79        }
80    }
81    out
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn the_updated_factor_reconstructs_the_updated_matrix() {
90        let n = 3;
91        let r = [2.0, 1.0, -1.0, 0.0, 1.5, 0.5, 0.0, 0.0, 1.0];
92        let w = [0.5, -1.0, 2.0];
93        let out = cholesky_update(&r, &w, 1, n);
94        let rtr = |r: &[f64]| symmetric_product(&transpose(r, n), &[0.0; 9], 1, n, n, 1.0, 0.0);
95        let expected = symmetric_product(&w, &rtr(&r), 1, n, 1, 1.0, 1.0);
96        for (g, e) in rtr(&out).iter().zip(&expected) {
97            assert!((g - e).abs() < 1e-12, "{g} vs {e}");
98        }
99        // Below the diagonal only the rounding of the rotations remains.
100        for i in 0..n {
101            for j in 0..i {
102                assert!(out[i * n + j].abs() < 1e-12, "{out:?}");
103            }
104        }
105    }
106
107    fn transpose(x: &[f64], n: usize) -> Vec<f64> {
108        (0..n * n).map(|k| x[(k % n) * n + k / n]).collect()
109    }
110}