Skip to main content

ruxla_testing/
ad.rs

1//! Checks of differentiation rules on the OpInfo samples: forward mode against
2//! finite differences, and reverse mode against forward mode with the
3//! inner-product test `<ct, J t> = <J^T ct, t>`.
4
5use ruxla_ir::{
6    AVal, Atom, DType, Eqn, Error, Function, GatherScatterMode, HostArray, Params, Var,
7};
8use ruxla_kernels::c128;
9
10use crate::opinfo::{Failure, OpInfo, catch, sample_function};
11use crate::rng::{Domain, Rng};
12
13/// The result of [`check_op_ad`].
14#[derive(Clone, Debug, Default)]
15pub struct AdReport {
16    /// The failures.
17    pub failures: Vec<Failure>,
18    /// The number of samples checked.
19    pub checked: usize,
20    /// Whether a rule was missing (the primitive is not differentiable yet).
21    pub unsupported: bool,
22    /// Whether only forward mode is supported (a transpose rule was
23    /// missing; the samples were checked in forward mode only).
24    pub forward_only: bool,
25    /// Whether only reverse mode is supported (forward-mode evaluation was
26    /// rejected, as for `custom_vjp_call`; reverse mode was checked against
27    /// finite differences).
28    pub reverse_only: bool,
29}
30
31/// What [`check_sample`] did.
32enum Outcome {
33    /// Nothing to differentiate.
34    Skipped,
35    /// Checked in both modes.
36    Checked,
37    /// Checked in forward mode; reverse mode is not supported.
38    ForwardOnly,
39    /// Checked in reverse mode against finite differences; forward mode is
40    /// not supported.
41    ReverseOnly,
42}
43
44/// The elements as complex numbers (the imaginary parts of real numbers
45/// are 0).
46fn c128s(x: &HostArray) -> Vec<c128> {
47    x.convert(DType::C128)
48        .to_vec::<c128>()
49        .expect("converted to c128")
50}
51
52/// The bilinear pairing `sum(re(a * b))` under which JAX's transposes are
53/// transposes (the dot product for real numbers; complex numbers are not
54/// conjugated).
55fn dot(a: &[HostArray], b: &[HostArray]) -> f64 {
56    a.iter()
57        .zip(b)
58        .map(|(x, y)| {
59            c128s(x)
60                .iter()
61                .zip(c128s(y))
62                .map(|(p, q)| p.re * q.re - p.im * q.im)
63                .sum::<f64>()
64        })
65        .sum()
66}
67
68/// `x + s * t` for float or complex arrays.
69fn axpy(x: &HostArray, s: f64, t: &HostArray) -> HostArray {
70    let v: Vec<c128> = c128s(x)
71        .iter()
72        .zip(c128s(t))
73        .map(|(a, b)| c128::new(a.re + s * b.re, a.im + s * b.im))
74        .collect();
75    HostArray::from_vec(v, x.shape().clone()).convert(x.dtype())
76}
77
78fn is_unsupported(e: &Error) -> bool {
79    matches!(e, Error::Unsupported { .. })
80}
81
82/// Checks the derivatives of the `f64` and `c128` samples of `info` (those
83/// that the primitive accepts, except `edge values`, which include points
84/// where functions are not differentiable).
85///
86/// Complex derivatives are checked as JAX defines them: forward mode
87/// against finite differences along complex tangents (the derivative as a
88/// map of the real and imaginary parts), and reverse mode with the pairing
89/// `sum(re(a * b))`.
90pub fn check_op_ad(info: &OpInfo, seed: u64) -> AdReport {
91    let mut report = AdReport::default();
92    if info.xla_only {
93        return report;
94    }
95    let mut rng = Rng::new(seed);
96    for dtype in [DType::F64, DType::C128] {
97        check_op_ad_dtype(info, dtype, &mut rng, &mut report);
98        if report.unsupported {
99            break;
100        }
101    }
102    report
103}
104
105fn check_op_ad_dtype(info: &OpInfo, dtype: DType, rng: &mut Rng, report: &mut AdReport) {
106    let Ok(samples) = catch(|| (info.samples)(rng, dtype)) else {
107        return;
108    };
109    for sample in samples {
110        // Points where functions are not differentiable, or where finite
111        // differences are meaningless.
112        let finite = sample.args.iter().all(|a| {
113            !a.dtype().is_inexact()
114                || c128s(a)
115                    .iter()
116                    .all(|v| v.re.is_finite() && v.im.is_finite())
117        });
118        // `lo > hi` in `clamp`, where JAX's rules differ from the function.
119        let unordered = info.prim == ruxla_prims::CLAMP && sample.name == "array bounds";
120        // Samples with `PromiseInBounds` have out-of-bounds indices on
121        // purpose (to check XLA's native behavior), which break the promise
122        // that JAX's rules rely on: gather clamps them but its transpose,
123        // a scatter, drops them, so the two are not transposes of each
124        // other (in JAX as well).
125        let broken_promise = matches!(
126            sample.params,
127            Params::Gather {
128                mode: GatherScatterMode::PromiseInBounds,
129                ..
130            } | Params::Scatter {
131                mode: GatherScatterMode::PromiseInBounds,
132                ..
133            }
134        );
135        // JAX has no VJP of max or min pooling with a window dilation
136        // (`_select_and_gather_add_transpose`); these samples are checked
137        // in forward mode by `windows_with_window_dilation_are_forward_only`.
138        let dilated_chooser = info.prim != ruxla_prims::REDUCE_WINDOW_SUM
139            && matches!(
140                &sample.params,
141                Params::ReduceWindow { window_dilation, .. }
142                    | Params::SelectAndGatherAdd { window_dilation, .. }
143                    if window_dilation.iter().any(|&d| d != 1)
144            );
145        // JAX does not differentiate the full `u` and `vt` of non-square
146        // matrices either.
147        let full_svd = matches!(
148            sample.params,
149            Params::Svd {
150                full_matrices: true,
151                compute_uv: true,
152                ..
153            }
154        ) && {
155            let d = sample.args[0].shape().dims();
156            d[d.len() - 2] != d[d.len() - 1]
157        };
158        // Nor partial eigendecompositions, nor the vectors of partial
159        // singular value decompositions.
160        let partial = matches!(
161            sample.params,
162            Params::Eigh {
163                subset_by_index: Some(_),
164                ..
165            } | Params::Svd {
166                compute_uv: true,
167                subset_by_index: Some(_),
168                ..
169            }
170        );
171        if sample.name.contains("edge")
172            || !finite
173            || unordered
174            || broken_promise
175            || dilated_chooser
176            || full_svd
177            || partial
178        {
179            continue;
180        }
181        let Ok(f) = sample_function(info, &sample) else {
182            continue;
183        };
184        let f = gauge_invariant(f);
185        match check_sample(&f, &sample.args, rng) {
186            Ok(Outcome::Checked) => report.checked += 1,
187            Ok(Outcome::ForwardOnly) => {
188                report.checked += 1;
189                report.forward_only = true;
190            }
191            Ok(Outcome::ReverseOnly) => {
192                report.checked += 1;
193                report.reverse_only = true;
194            }
195            Ok(Outcome::Skipped) => {}
196            Err(Err(e)) if is_unsupported(&e) => {
197                report.unsupported = true;
198                return;
199            }
200            Err(e) => report.failures.push(Failure {
201                op: info.name(),
202                dtype,
203                sample: format!("{sample:?}"),
204                message: match e {
205                    Ok(m) => m,
206                    Err(e) => e.to_string(),
207                },
208            }),
209        }
210    }
211}
212
213/// The eigenvectors and singular vectors of complex matrices are defined up
214/// to a phase per column, which the kernels fix one way (the component of
215/// largest magnitude real and positive) and JAX's differentiation rules
216/// another (`V^H dV` with a zero diagonal), as in JAX. Their derivatives are
217/// checked through quantities that do not depend on the phases: for
218/// `eigh`, the projectors `v_c v_c^H` of the columns (`[..., n, n, n]`) in
219/// place of `v`; for `svd`, the products `u_c v_c^H` (`[..., k, m, n]`) in
220/// place of `u` and `vt`. Other functions are returned as they are.
221fn gauge_invariant(mut f: Function) -> Function {
222    let [eqn] = &f.eqns[..] else {
223        return f;
224    };
225    let complex = eqn
226        .inputs
227        .first()
228        .is_some_and(|a| a.aval().dtype.is_complex());
229    let prim = eqn.prim;
230    if !complex || !(prim == ruxla_prims::EIGH || prim == ruxla_prims::SVD) {
231        return f;
232    }
233    if prim == ruxla_prims::SVD && eqn.outputs.len() < 3 {
234        return f;
235    }
236    let outs: Vec<Var> = eqn.outputs.clone();
237    let rank = outs[0].aval().shape.rank();
238    let product = |f: &mut Function, l: Atom, r: Atom, lb: usize, rb: usize| {
239        // `out[..., c, i, j] = l[..., i, c] * r[..., c or j, ...]`: a batch of
240        // outer products over the column `c`.
241        let nb = l.aval().shape.rank() - 2;
242        let batch: Vec<usize> = (0..nb).collect();
243        let mut lhs_batch = batch.clone();
244        lhs_batch.push(lb);
245        let mut rhs_batch = batch;
246        rhs_batch.push(rb);
247        let params = Params::DotGeneral {
248            dimension_numbers: ruxla_ir::DotDims {
249                lhs_contracting: Vec::new(),
250                rhs_contracting: Vec::new(),
251                lhs_batch,
252                rhs_batch,
253            },
254            precision: ruxla_ir::Precision::Highest,
255            preferred_element_type: None,
256        };
257        let aval = ruxla_prims::DOT_GENERAL
258            .abstract_eval(&[l.aval(), r.aval()], &params)
259            .expect("an outer product")
260            .remove(0);
261        let out = Var::new(aval);
262        f.eqns.push(Eqn {
263            prim: ruxla_prims::DOT_GENERAL,
264            inputs: vec![l, r],
265            params,
266            outputs: vec![out.clone()],
267            loc: None,
268        });
269        out
270    };
271    if prim == ruxla_prims::EIGH {
272        let (v, w) = (&outs[0], &outs[1]);
273        let conj = Var::new(v.aval().clone());
274        f.eqns.push(Eqn {
275            prim: ruxla_prims::CONJ,
276            inputs: vec![v.clone().into()],
277            params: Params::None,
278            outputs: vec![conj.clone()],
279            loc: None,
280        });
281        let nb = rank - 2;
282        let p = product(&mut f, v.clone().into(), conj.into(), nb + 1, nb + 1);
283        f.outvars = vec![p.into(), w.clone().into()];
284    } else {
285        let (s, u, vt) = (&outs[0], &outs[1], &outs[2]);
286        let nb = rank - 1;
287        let q = product(&mut f, u.clone().into(), vt.clone().into(), nb + 1, nb);
288        f.outvars = vec![s.clone().into(), q.into()];
289    }
290    f
291}
292
293/// Checks the derivatives of `f` at `args` (forward mode against finite
294/// differences, reverse mode with the inner-product test) with random
295/// tangents and cotangents from `seed`. Only outputs of type `f64` are
296/// compared with finite differences.
297///
298/// # Errors
299///
300/// Returns a message describing the mismatch, or the error of the
301/// transformations.
302pub fn check_function_ad(f: &Function, args: &[HostArray], seed: u64) -> Result<(), String> {
303    match check_sample(f, args, &mut Rng::new(seed)) {
304        Ok(Outcome::Checked) => Ok(()),
305        Ok(Outcome::Skipped) => Err(String::from("nothing to differentiate")),
306        Ok(Outcome::ForwardOnly) => Err(String::from("reverse mode is not supported")),
307        Ok(Outcome::ReverseOnly) => Err(String::from("forward mode is not supported")),
308        Err(Ok(m)) => Err(m),
309        Err(Err(e)) => Err(e.to_string()),
310    }
311}
312
313/// The error is a message, or an error of the transformations
314/// (`Unsupported` for a missing rule).
315fn check_sample(
316    f: &Function,
317    args: &[HostArray],
318    rng: &mut Rng,
319) -> Result<Outcome, Result<String, Error>> {
320    let diff: Vec<bool> = f
321        .invars
322        .iter()
323        .map(|v| v.aval().dtype.is_inexact())
324        .collect();
325    let out_diff: Vec<bool> = f
326        .outvars
327        .iter()
328        .map(|a| a.aval().dtype.is_inexact())
329        .collect();
330    if !diff.contains(&true) || !out_diff.contains(&true) {
331        return Ok(Outcome::Skipped);
332    }
333    let tangents: Vec<HostArray> = f
334        .invars
335        .iter()
336        .zip(&diff)
337        .filter(|(_, d)| **d)
338        .map(|(v, _)| {
339            let a: &AVal = v.aval();
340            rng.array(a.shape.clone(), a.dtype, Domain::Any)
341        })
342        .collect();
343    let eval = |g: &Function, a: &[HostArray]| ruxla_interp::eval(g, a).map_err(Err);
344
345    let n_out = f.outvars.len();
346    let eps = 1e-6;
347    let shifted = |s: f64| -> Vec<HostArray> {
348        let mut k = 0;
349        args.iter()
350            .zip(&diff)
351            .map(|(x, &d)| {
352                if d {
353                    k += 1;
354                    axpy(x, s, &tangents[k - 1])
355                } else {
356                    x.clone()
357                }
358            })
359            .collect()
360    };
361    let plus = eval(f, &shifted(eps))?;
362    let minus = eval(f, &shifted(-eps))?;
363    let fd = |i: usize| -> Vec<c128> {
364        c128s(&plus[i])
365            .iter()
366            .zip(c128s(&minus[i]))
367            .map(|(p, m)| c128::new((p.re - m.re) / (2.0 * eps), (p.im - m.im) / (2.0 * eps)))
368            .collect()
369    };
370
371    // Forward mode against central differences. A primitive that only
372    // reverse mode supports rejects the evaluation; its reverse mode is
373    // then checked against the finite differences.
374    let (g, nonzero) = ruxla_transforms::jvp(f, &diff, &out_diff).map_err(Err)?;
375    let mut jvp_args = args.to_vec();
376    jvp_args.extend(tangents.iter().cloned());
377    let (jt, nonzero, reverse_only) = match ruxla_interp::eval(&g, &jvp_args) {
378        Ok(out) => (out[n_out..].to_vec(), nonzero, false),
379        Err(e) if is_unsupported(&e) => {
380            let jt = (0..n_out)
381                .filter(|&i| out_diff[i])
382                .map(|i| {
383                    let a = f.outvars[i].aval();
384                    HostArray::from_vec(fd(i), a.shape.clone()).convert(a.dtype)
385                })
386                .collect();
387            (jt, out_diff.clone(), true)
388        }
389        Err(e) => return Err(Err(e)),
390    };
391    let mut k = 0;
392    for (i, &d) in out_diff.iter().enumerate() {
393        if reverse_only || !d || !nonzero[i] {
394            continue;
395        }
396        // Lower-precision outputs round away differences of `eps`.
397        if !matches!(f.outvars[i].aval().dtype, DType::F64 | DType::C128) {
398            k += 1;
399            continue;
400        }
401        let fd = fd(i);
402        let got = c128s(&jt[k]);
403        k += 1;
404        for (j, (a, e)) in got.iter().zip(&fd).enumerate() {
405            for (a, e) in [(a.re, e.re), (a.im, e.im)] {
406                let scale = e.abs().max(a.abs()).max(1.0);
407                if !((a - e).abs() <= 1e-5 * scale || (a.is_nan() && e.is_nan())) {
408                    return Err(Ok(format!(
409                        "output {i}, element {j}: JVP gives {a}, finite differences {e}"
410                    )));
411                }
412            }
413        }
414    }
415
416    // Reverse mode: <ct, J t> = <J^T ct, t>.
417    let v = match ruxla_transforms::vjp(f, &diff) {
418        Ok(v) => v,
419        Err(e) if is_unsupported(&e) && !reverse_only => return Ok(Outcome::ForwardOnly),
420        Err(e) => return Err(Err(e)),
421    };
422    let fwd = eval(&v.forward, args)?;
423    let residuals = fwd[n_out..].to_vec();
424    let cts: Vec<HostArray> = f
425        .outvars
426        .iter()
427        .zip(&out_diff)
428        .filter(|(_, d)| **d)
429        .map(|(a, _)| {
430            let a = a.aval();
431            rng.array(a.shape.clone(), a.dtype, Domain::Any)
432        })
433        .collect();
434    let mut back_args = residuals;
435    back_args.extend(cts.iter().cloned());
436    let jtct = eval(&v.backward, &back_args)?;
437    // J t for every float output (zeros where the tangent is zero).
438    let mut jt_all = Vec::new();
439    let mut k = 0;
440    for (i, &d) in out_diff.iter().enumerate() {
441        if d {
442            if nonzero[i] {
443                jt_all.push(jt[k].clone());
444                k += 1;
445            } else {
446                let a = f.outvars[i].aval();
447                jt_all.push(HostArray::zeros(a.shape.clone(), a.dtype));
448            }
449        }
450    }
451    let lhs = dot(&cts, &jt_all);
452    let rhs = dot(&jtct, &tangents);
453    // Lower-precision intermediate values round the two sides differently.
454    let tol = f
455        .outvars
456        .iter()
457        .map(|a| match a.aval().dtype {
458            DType::F16 => 1e-2,
459            DType::BF16 => 1e-1,
460            DType::F32 | DType::C64 => 1e-6,
461            _ => 1e-9,
462        })
463        .fold(if reverse_only { 1e-5 } else { 1e-9 }, f64::max);
464    if (lhs - rhs).abs() > tol * lhs.abs().max(rhs.abs()).max(1.0) {
465        return Err(Ok(format!(
466            "inner-product test: <ct, J t> = {lhs}, <J^T ct, t> = {rhs}"
467        )));
468    }
469    Ok(if reverse_only {
470        Outcome::ReverseOnly
471    } else {
472        Outcome::Checked
473    })
474}
475
476#[cfg(test)]
477mod tests {
478    use std::sync::Arc;
479
480    use ruxla_ir::{Atom, Literal, Params, Prim};
481    use ruxla_prims as p;
482
483    use super::*;
484    use crate::ops::Builder;
485
486    fn un(b: &mut Builder, prim: Prim, x: &Atom) -> Atom {
487        b.apply(prim, std::slice::from_ref(x), Params::None)
488            .remove(0)
489    }
490
491    fn bin(b: &mut Builder, prim: Prim, x: &Atom, y: &Atom) -> Atom {
492        b.apply(prim, &[x.clone(), y.clone()], Params::None)
493            .remove(0)
494    }
495
496    fn lit_i32(v: i32) -> Atom {
497        Atom::Lit(Literal::new(HostArray::scalar(v)))
498    }
499
500    /// A function that applies one equation to its inputs.
501    fn single(prim: Prim, in_avals: &[AVal], params: Params) -> Function {
502        let f = Builder::function(in_avals, |b, ins| b.apply(prim, ins, params));
503        Arc::unwrap_or_clone(f)
504    }
505
506    fn vec3() -> AVal {
507        AVal::new([3], DType::F64)
508    }
509
510    fn branches() -> Vec<Arc<Function>> {
511        let x = vec3();
512        vec![
513            Builder::function(&[x.clone(), x.clone()], |b, ins| {
514                let s = un(b, p::SIN, &ins[0]);
515                vec![bin(b, p::MUL, &s, &ins[1]), ins[0].clone()]
516            }),
517            Builder::function(&[x.clone(), x.clone()], |b, ins| {
518                let sq = bin(b, p::MUL, &ins[0], &ins[0]);
519                vec![bin(b, p::ADD, &sq, &ins[1]), ins[1].clone()]
520            }),
521            // The tangent of output 0 depends on other inputs here.
522            Builder::function(&[x.clone(), x], |b, ins| {
523                let e = un(b, p::EXP, &ins[0]);
524                vec![ins[1].clone(), e]
525            }),
526        ]
527    }
528
529    #[test]
530    fn cond_with_nonlinear_branches() {
531        let mut rng = Rng::new(1);
532        let f = single(
533            p::COND,
534            &[AVal::scalar(DType::I32), vec3(), vec3()],
535            Params::Cond {
536                branches: branches(),
537            },
538        );
539        for i in [0, 1, 2] {
540            let args = vec![
541                HostArray::scalar(i),
542                rng.array([3], DType::F64, Domain::Any),
543                rng.array([3], DType::F64, Domain::Any),
544            ];
545            check_function_ad(&f, &args, 2).unwrap_or_else(|e| panic!("index {i}: {e}"));
546        }
547    }
548
549    /// `h' = tanh(h * w + x)`, outputs `h' * h'` and `w`.
550    fn rnn_body() -> Arc<Function> {
551        let x = vec3();
552        Builder::function(&[x.clone(), x.clone(), x], |b, ins| {
553            let (w, h, x) = (&ins[0], &ins[1], &ins[2]);
554            let hw = bin(b, p::MUL, h, w);
555            let a = bin(b, p::ADD, &hw, x);
556            let h2 = un(b, p::TANH, &a);
557            let y = bin(b, p::MUL, &h2, &h2);
558            vec![h2, y, w.clone()]
559        })
560    }
561
562    #[test]
563    fn scan_with_a_nonlinear_body() {
564        let mut rng = Rng::new(3);
565        for (length, reverse) in [(4, false), (4, true), (1, false), (0, false)] {
566            let f = single(
567                p::SCAN,
568                &[vec3(), vec3(), AVal::new([length, 3], DType::F64)],
569                Params::Scan {
570                    body: rnn_body(),
571                    length,
572                    reverse,
573                    num_consts: 1,
574                    num_carry: 1,
575                },
576            );
577            let args = vec![
578                rng.array([3], DType::F64, Domain::Any),
579                rng.array([3], DType::F64, Domain::Any),
580                rng.array([length, 3], DType::F64, Domain::Any),
581            ];
582            check_function_ad(&f, &args, 4)
583                .unwrap_or_else(|e| panic!("length {length}, reverse {reverse}: {e}"));
584        }
585    }
586
587    #[test]
588    fn scan_containing_cond_with_an_integer_carry() {
589        // carry (i, h): h' = cond(i % 3, h, x), i' = i + 1; ys = h'.
590        let x = vec3();
591        let i = AVal::scalar(DType::I32);
592        let body = Builder::function(&[i.clone(), x.clone(), x.clone()], |b, ins| {
593            let (i, h, x) = (&ins[0], &ins[1], &ins[2]);
594            let k = bin(b, p::REM, i, &lit_i32(3));
595            let outs = b.apply(
596                p::COND,
597                &[k, h.clone(), x.clone()],
598                Params::Cond {
599                    branches: branches(),
600                },
601            );
602            let next = bin(b, p::ADD, i, &lit_i32(1));
603            vec![next, outs[0].clone(), outs[1].clone()]
604        });
605        let f = single(
606            p::SCAN,
607            &[i, x, AVal::new([5, 3], DType::F64)],
608            Params::Scan {
609                body,
610                length: 5,
611                reverse: false,
612                num_consts: 0,
613                num_carry: 2,
614            },
615        );
616        let mut rng = Rng::new(5);
617        let args = vec![
618            HostArray::scalar(0i32),
619            rng.array([3], DType::F64, Domain::Any),
620            rng.array([5, 3], DType::F64, Domain::Any),
621        ];
622        check_function_ad(&f, &args, 6).unwrap();
623    }
624
625    #[test]
626    fn while_is_differentiable_in_forward_mode() {
627        let i = AVal::scalar(DType::I32);
628        let x = vec3();
629        let cond = Builder::function(&[i.clone(), x.clone()], |b, ins| {
630            vec![bin(b, p::LT, &ins[0], &lit_i32(3))]
631        });
632        // x' = sin(x) * c
633        let body = Builder::function(&[x.clone(), i.clone(), x.clone()], |b, ins| {
634            let s = un(b, p::SIN, &ins[2]);
635            vec![
636                bin(b, p::ADD, &ins[1], &lit_i32(1)),
637                bin(b, p::MUL, &s, &ins[0]),
638            ]
639        });
640        let f = single(
641            p::WHILE,
642            &[x.clone(), i, x],
643            Params::While {
644                cond,
645                body,
646                cond_nconsts: 0,
647                body_nconsts: 1,
648            },
649        );
650        let mut rng = Rng::new(7);
651        let args = vec![
652            rng.array([3], DType::F64, Domain::Any),
653            HostArray::scalar(0i32),
654            rng.array([3], DType::F64, Domain::Any),
655        ];
656        assert_eq!(
657            check_function_ad(&f, &args, 8),
658            Err(String::from("reverse mode is not supported"))
659        );
660    }
661}