Skip to main content

ruxla_env/
testing.rs

1//! Tools for testing environments: agreement of the native backend, the
2//! interpreter, and XLA, and of `vmap` with native loops.
3
4use ruxla_core::random;
5use ruxla_core::{Native, Trace, Tree, interpret, jit, leaves};
6use ruxla_ir::{HostArray, Value};
7
8use crate::{ActionValue, Environment, StepInput, StepOf};
9
10/// Where [`check_backends`] runs the traced environment besides the
11/// interpreter.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum Xla {
14    /// Only the native backend and the interpreter.
15    Skip,
16    /// Also XLA, through [`jit`] (needs a PJRT plugin).
17    Run,
18}
19
20/// Compares leaves: integers and booleans exactly, floats within a relative
21/// tolerance (NaN equals NaN).
22fn compare_leaves(what: &str, a: &[HostArray], b: &[HostArray], rtol: f64) -> Result<(), String> {
23    for (k, (x, y)) in a.iter().zip(b).enumerate() {
24        if x.aval() != y.aval() {
25            return Err(format!("{what}: leaf {k} is {} and {}", x.aval(), y.aval()));
26        }
27        for i in 0..x.size() {
28            let ok = match (x.get(i), y.get(i)) {
29                (Value::Float(p), Value::Float(q)) => {
30                    (p.is_nan() && q.is_nan()) || (p - q).abs() <= rtol * q.abs().max(1.0)
31                }
32                (p, q) => p == q,
33            };
34            if !ok {
35                return Err(format!(
36                    "{what}: leaf {k}, element {i}: {:?} vs {:?}",
37                    x.get(i),
38                    y.get(i)
39                ));
40            }
41        }
42    }
43    Ok(())
44}
45
46/// Runs `steps` steps of `env` with the same keys and actions natively, as
47/// IR with the interpreter, and optionally with XLA, comparing the results
48/// of every step.
49///
50/// The native backend and the interpreter share their kernels, so they must
51/// agree bit for bit; XLA must agree on integers and booleans and within a
52/// small tolerance on floats. Each step starts from the native state, so
53/// that differences in the last bits do not accumulate. Actions cycle
54/// through the action space with a pseudo-random pattern.
55///
56/// # Errors
57///
58/// Returns a description of the first difference.
59pub fn check_backends<E: Environment>(
60    env: &E,
61    steps: usize,
62    seed: i64,
63    xla: Xla,
64) -> Result<(), String>
65where
66    E::State<Native>: Send + Sync,
67    E::Params<Native>: Send + Sync,
68    E::Obs<Native>: Send + Sync,
69    E::State<Trace>: Send + Sync,
70    E::Obs<Trace>: Send + Sync,
71{
72    let params = env.default_params::<Native>();
73    let root = random::key::<Native>(seed);
74    let (_, mut state) = env.reset(random::fold_in(&root, u32::MAX), &params);
75    let step = |(k, s, a, p): StepInput<Trace, E>| env.step(k, &s, a, &p);
76    let jitted = jit(step);
77    let space = env.action_space();
78    for i in 0..steps {
79        let key = random::fold_in(&root, i as u32);
80        let action = <E::Action<Native> as ActionValue<Native>>::pattern(&space, i as u64);
81        let input = (key.clone(), state.clone(), action.clone(), params.clone());
82        let native: StepOf<Native, E> = env.step(key, &state, action, &params);
83        let expected = leaves(&native);
84        let ir = interpret(step, &input);
85        compare_leaves(
86            &format!("step {i}, interpreter"),
87            &leaves(&ir),
88            &expected,
89            0.0,
90        )?;
91        if xla == Xla::Run {
92            let out = jitted.try_call(&input).map_err(|e| e.to_string())?;
93            compare_leaves(&format!("step {i}, XLA"), &leaves(&out), &expected, 1e-5)?;
94        }
95        state = native.state;
96    }
97    Ok(())
98}
99
100/// Returns whether two pytrees of native values are equal bit for bit.
101pub fn trees_equal<T: Tree<Native>>(a: &T, b: &T) -> bool {
102    leaves(a)
103        .iter()
104        .zip(leaves(b).iter())
105        .all(|(x, y)| x.aval() == y.aval() && x.to_bytes() == y.to_bytes())
106}
107
108/// Checks that the batched IR of `reset` and `step` (ruxla's `vmap`, which
109/// JAX's `vmap` uses) gives the same results as running each of `n`
110/// environments natively: bit for bit with the interpreter, and within a
111/// small tolerance with XLA.
112///
113/// The environments start from different keys and take different actions
114/// for `steps` steps, so that some episodes end and reset.
115///
116/// # Errors
117///
118/// Returns a description of the first difference.
119pub fn check_vmap<E: Environment>(env: &E, n: usize, steps: usize, xla: Xla) -> Result<(), String>
120where
121    E::State<Native>: Send + Sync,
122    E::Params<Native>: Send + Sync,
123    E::Obs<Native>: Send + Sync,
124{
125    let params = env.default_params::<Native>();
126    let root = random::key::<Native>(17);
127    let keys: Vec<_> = (0..n).map(|i| random::fold_in(&root, i as u32)).collect();
128    let reset = ruxla_core::vmap(
129        |(k, p): (ruxla_core::random::Key<Trace>, E::Params<Trace>)| env.reset(k, &p),
130    );
131    let step = ruxla_core::vmap(|(k, s, a, p): crate::StepInput<Trace, E>| env.step(k, &s, a, &p));
132
133    let inputs: Vec<_> = keys.iter().map(|k| (k.clone(), params.clone())).collect();
134    let batched = reset.call(&inputs);
135    let mut states = Vec::with_capacity(n);
136    for (i, (b, k)) in batched.iter().zip(&keys).enumerate() {
137        let native = env.reset(k.clone(), &params);
138        compare_leaves(&format!("reset {i}"), &leaves(b), &leaves(&native), 0.0)?;
139        states.push(native.1);
140    }
141    let space = env.action_space();
142    for t in 0..steps {
143        let inputs: Vec<_> = (0..n)
144            .map(|i| {
145                let key = random::fold_in(&keys[i], t as u32);
146                let action = <E::Action<Native> as ActionValue<Native>>::pattern(
147                    &space,
148                    (t * 7 + i * 3) as u64,
149                );
150                (key, states[i].clone(), action, params.clone())
151            })
152            .collect();
153        let batched = step.call(&inputs);
154        let on_xla = match xla {
155            Xla::Run => Some(step.call_xla(&inputs).map_err(|e| e.to_string())?),
156            Xla::Skip => None,
157        };
158        for (i, (k, s, a, p)) in inputs.into_iter().enumerate() {
159            let native = env.step(k, &s, a, &p);
160            let expected = leaves(&native);
161            compare_leaves(
162                &format!("step {t}, env {i}, vmap"),
163                &leaves(&batched[i]),
164                &expected,
165                0.0,
166            )?;
167            if let Some(out) = &on_xla {
168                compare_leaves(
169                    &format!("step {t}, env {i}, vmap on XLA"),
170                    &leaves(&out[i]),
171                    &expected,
172                    1e-5,
173                )?;
174            }
175            states[i] = native.state;
176        }
177    }
178    Ok(())
179}