Skip to main content

ruxla_nn/
init.rs

1//! Initializers with the definitions of `jax.nn.initializers`, computed
2//! natively (initialization runs once, so it is not traced).
3
4use ruxla_core::{Array, Element, Float, Key, Native, random};
5use ruxla_ir::Value;
6
7/// An orthogonal matrix of shape `[rows, cols]` scaled by `scale`
8/// (`jax.nn.initializers.orthogonal(scale)` for a matrix): the `Q` of the
9/// QR decomposition of a matrix of standard normal values, with the signs
10/// that make the diagonal of `R` positive (so `Q` does not depend on the QR
11/// algorithm, up to rounding).
12///
13/// # Examples
14///
15/// ```
16/// use ruxla_core::random;
17/// use ruxla_nn::init::orthogonal;
18///
19/// let q = orthogonal::<f32>(&random::key(0), 4, 3, 1.0);
20/// let v = q.to_vec();
21/// // The columns are orthonormal.
22/// let dot = |i: usize, j: usize| (0..4).map(|r| v[r * 3 + i] * v[r * 3 + j]).sum::<f32>();
23/// assert!((dot(0, 0) - 1.0).abs() < 1e-5 && dot(0, 1).abs() < 1e-5);
24/// ```
25pub fn orthogonal<T: Float>(
26    key: &Key<Native>,
27    rows: usize,
28    cols: usize,
29    scale: f64,
30) -> Array<Native, T> {
31    // JAX draws the matrix with more rows than columns, and transposes Q.
32    let (m, n) = if rows < cols {
33        (cols, rows)
34    } else {
35        (rows, cols)
36    };
37    let a: Vec<f64> = random::normal::<Native, T>(key, [m, n])
38        .to_vec()
39        .into_iter()
40        .map(|x| match x.to_value() {
41            Value::Float(f) => f,
42            v => panic!("expected a float, got {v:?}"),
43        })
44        .collect();
45    let q = reduced_q(&a, m, n);
46    let mut out = vec![T::default(); rows * cols];
47    for r in 0..rows {
48        for c in 0..cols {
49            let v = if rows < cols {
50                q[c * n + r]
51            } else {
52                q[r * n + c]
53            };
54            out[r * cols + c] = T::from_value(Value::Float(scale * v));
55        }
56    }
57    Array::from_vec(out, [rows, cols])
58}
59
60/// The `m x n` matrix `Q` (row-major) of the reduced QR decomposition of
61/// `a` (`m >= n`), with the diagonal of `R` made nonnegative, by Householder
62/// reflections.
63fn reduced_q(a: &[f64], m: usize, n: usize) -> Vec<f64> {
64    let mut r = a.to_vec();
65    let mut vs: Vec<Vec<f64>> = Vec::with_capacity(n);
66    for k in 0..n {
67        let norm = (k..m)
68            .map(|i| r[i * n + k] * r[i * n + k])
69            .sum::<f64>()
70            .sqrt();
71        let mut v: Vec<f64> = (k..m).map(|i| r[i * n + k]).collect();
72        let alpha = if v[0] >= 0.0 { -norm } else { norm };
73        v[0] -= alpha;
74        let vnorm = v.iter().map(|x| x * x).sum::<f64>().sqrt();
75        if vnorm > 0.0 {
76            for x in &mut v {
77                *x /= vnorm;
78            }
79            for j in 0..n {
80                let d: f64 = (k..m).map(|i| v[i - k] * r[i * n + j]).sum();
81                for i in k..m {
82                    r[i * n + j] -= 2.0 * v[i - k] * d;
83                }
84            }
85        }
86        vs.push(v);
87    }
88    // Q = H_0 H_1 ... H_{n-1} applied to the first n columns of I.
89    let mut q = vec![0.0; m * n];
90    for i in 0..n {
91        q[i * n + i] = 1.0;
92    }
93    for k in (0..n).rev() {
94        let v = &vs[k];
95        for j in 0..n {
96            let d: f64 = (k..m).map(|i| v[i - k] * q[i * n + j]).sum();
97            for i in k..m {
98                q[i * n + j] -= 2.0 * v[i - k] * d;
99            }
100        }
101    }
102    // Signs: make diag(R) nonnegative (`Q *= sign(diag(R))`).
103    for j in 0..n {
104        if r[j * n + j] < 0.0 {
105            for i in 0..m {
106                q[i * n + j] = -q[i * n + j];
107            }
108        }
109    }
110    q
111}
112
113/// Zeros of a shape (`jax.nn.initializers.zeros`).
114pub fn zeros<T: Element>(shape: &[usize]) -> Array<Native, T> {
115    Array::from_vec(vec![T::default(); shape.iter().product()], shape.to_vec())
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn q_times_r_gives_back_the_matrix() {
124        let a = [
125            2.0, -1.0, 0.5, 3.0, 1.0, 1.0, -2.0, 0.0, 4.0, 1.5, -0.5, 2.0,
126        ];
127        let (m, n) = (4, 3);
128        let q = reduced_q(&a, m, n);
129        // R = Q^T A is upper triangular with a nonnegative diagonal, and
130        // Q R = A.
131        let mut r = vec![0.0; n * n];
132        for i in 0..n {
133            for j in 0..n {
134                r[i * n + j] = (0..m).map(|k| q[k * n + i] * a[k * n + j]).sum();
135            }
136        }
137        for i in 0..n {
138            assert!(r[i * n + i] >= 0.0);
139            for j in 0..i {
140                assert!(r[i * n + j].abs() < 1e-12);
141            }
142        }
143        for i in 0..m {
144            for j in 0..n {
145                let v: f64 = (0..n).map(|k| q[i * n + k] * r[k * n + j]).sum();
146                assert!((v - a[i * n + j]).abs() < 1e-12);
147            }
148        }
149    }
150
151    #[test]
152    fn wide_matrices_have_orthonormal_rows() {
153        let q = orthogonal::<f64>(&random::key(3), 2, 5, 2.0).to_vec();
154        for i in 0..2 {
155            for j in 0..2 {
156                let d: f64 = (0..5).map(|c| q[i * 5 + c] * q[j * 5 + c]).sum();
157                let expected = if i == j { 4.0 } else { 0.0 };
158                assert!((d - expected).abs() < 1e-12);
159            }
160        }
161    }
162}