ruxla-kernels 0.1.0

Internal crate of ruxla (use the `ruxla` crate): semantics of ruxla's operations, shared by the native backend and the IR interpreter
Documentation
//! Products and updates of real matrices that JAX computes with its own
//! operations on CPU: `cholesky_update` (Givens rotations) and
//! `symmetric_product` (`alpha a a^T + beta c`).

use super::LinalgFloat;

/// The rank-1 update of each Cholesky factor (`[batch, n, n]`, upper
/// triangular `r` with `a = r^T r`) by the vector `w` (`[batch, n]`): the
/// upper triangular factor of `a + w w^T`, as JAX's `cholesky_update_p`
/// computes it on CPU (`_cholesky_update_jax_fn`): for each `k`, the Givens
/// rotation of `drotg(r[k, k], w[k])` applied to the row `r[k, :]` and `w`.
///
/// # Panics
///
/// Panics if the lengths of the buffers do not match the sizes.
pub fn cholesky_update<T: LinalgFloat>(r: &[T], w: &[T], batch: usize, n: usize) -> Vec<T> {
    assert_eq!(r.len(), batch * n * n, "cholesky_update: r");
    assert_eq!(w.len(), batch * n, "cholesky_update: w");
    let mut out = r.to_vec();
    let mut z = vec![T::ZERO; n];
    for b in 0..batch {
        let r = &mut out[b * n * n..(b + 1) * n * n];
        z.copy_from_slice(&w[b * n..(b + 1) * n]);
        for k in 0..n {
            let (c, s) = drotg(r[k * n + k], z[k]);
            for j in 0..n {
                let (x, y) = (r[k * n + j], z[j]);
                r[k * n + j] = c * x - s * y;
                z[j] = c * y + s * x;
            }
        }
    }
    out
}

/// The coefficients of the Givens rotation of JAX's `_drotg`: `(1, 0)` for
/// `y = 0`, otherwise `(x, -y) / |(x, y)|`, scaled by `max(|x|, |y|)` first.
fn drotg<T: LinalgFloat>(x: T, y: T) -> (T, T) {
    if y == T::ZERO {
        return (T::ONE, T::ZERO);
    }
    let (ax, ay) = (x.abs(), y.abs());
    let denominator = if ax > ay { ax } else { ay };
    let (x, y) = (x / denominator, y / denominator);
    let rh = T::ONE / (x * x + y * y).sqrt();
    (x * rh, -y * rh)
}

/// `alpha a a^T + beta c` for each `a` (`[batch, m, n]`) and `c`
/// (`[batch, m, m]`), as JAX's `symmetric_product_p` computes it on CPU
/// (the whole matrix; on GPU, cuBLAS's `syrk` gives the lower triangle).
///
/// # Panics
///
/// Panics if the lengths of the buffers do not match the sizes.
pub fn symmetric_product<T: LinalgFloat>(
    a: &[T],
    c: &[T],
    batch: usize,
    m: usize,
    n: usize,
    alpha: T,
    beta: T,
) -> Vec<T> {
    assert_eq!(a.len(), batch * m * n, "symmetric_product: a");
    assert_eq!(c.len(), batch * m * m, "symmetric_product: c");
    let mut out = vec![T::ZERO; batch * m * m];
    for b in 0..batch {
        let a = &a[b * m * n..(b + 1) * m * n];
        for i in 0..m {
            for j in 0..m {
                let mut s = T::ZERO;
                for k in 0..n {
                    s = s + a[i * n + k] * a[j * n + k];
                }
                let at = b * m * m + i * m + j;
                out[at] = alpha * s + beta * c[at];
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_updated_factor_reconstructs_the_updated_matrix() {
        let n = 3;
        let r = [2.0, 1.0, -1.0, 0.0, 1.5, 0.5, 0.0, 0.0, 1.0];
        let w = [0.5, -1.0, 2.0];
        let out = cholesky_update(&r, &w, 1, n);
        let rtr = |r: &[f64]| symmetric_product(&transpose(r, n), &[0.0; 9], 1, n, n, 1.0, 0.0);
        let expected = symmetric_product(&w, &rtr(&r), 1, n, 1, 1.0, 1.0);
        for (g, e) in rtr(&out).iter().zip(&expected) {
            assert!((g - e).abs() < 1e-12, "{g} vs {e}");
        }
        // Below the diagonal only the rounding of the rotations remains.
        for i in 0..n {
            for j in 0..i {
                assert!(out[i * n + j].abs() < 1e-12, "{out:?}");
            }
        }
    }

    fn transpose(x: &[f64], n: usize) -> Vec<f64> {
        (0..n * n).map(|k| x[(k % n) * n + k / n]).collect()
    }
}