Skip to main content

ruxla_testing/
vmap.rs

1//! Checks of `vmap` against a loop: batching a function must give the same
2//! results as applying it to each example and stacking the results.
3
4use ruxla_ir::{Function, HostArray};
5use ruxla_pjrt::Client;
6
7use crate::opinfo::{
8    Failure, OpInfo, Sample, catch, compare, compare_bits, run_with_xla, sample_function,
9    xla_tolerance,
10};
11use crate::rng::Rng;
12
13/// Stacks arrays of the same type and shape along a new dimension `axis`.
14///
15/// # Panics
16///
17/// Panics if `xs` is empty, if the arrays differ in type or shape, or if
18/// `axis` is greater than their rank.
19pub fn stack(xs: &[HostArray], axis: usize) -> HostArray {
20    let first = &xs[0];
21    let dims = first.shape().dims();
22    assert!(axis <= dims.len(), "axis {axis} is out of range");
23    let size = first.dtype().size_in_bytes();
24    let outer: usize = dims[..axis].iter().product();
25    let inner: usize = dims[axis..].iter().product::<usize>() * size;
26    let bytes: Vec<Vec<u8>> = xs
27        .iter()
28        .map(|x| {
29            assert_eq!(x.aval(), first.aval(), "stacked arrays must agree");
30            x.to_bytes()
31        })
32        .collect();
33    let mut out = Vec::with_capacity(outer * inner * xs.len());
34    for o in 0..outer {
35        for b in &bytes {
36            out.extend_from_slice(&b[o * inner..(o + 1) * inner]);
37        }
38    }
39    let mut shape = dims.to_vec();
40    shape.insert(axis, xs.len());
41    HostArray::from_bytes(&out, shape, first.dtype()).expect("the bytes of the stacked arrays")
42}
43
44/// Checks that `vmap(f)` agrees with a loop over examples, for a function
45/// `f` and the arguments of each example (all with the same types).
46///
47/// `in_axes[i]` batches argument `i` along that dimension, or, if `None`,
48/// uses the argument of the first example for every example. The batched
49/// function must be well typed, and its results with the interpreter must
50/// equal, bit for bit, the stacked results of the interpreter on each
51/// example; the native backend ([`ruxla_core::eval_native`]) must give the
52/// same bits as the interpreter on the batched function.
53///
54/// # Errors
55///
56/// Returns a description of the first disagreement.
57pub fn check_vmap(
58    f: &Function,
59    examples: &[Vec<HostArray>],
60    in_axes: &[Option<usize>],
61) -> Result<(), String> {
62    run_vmap(f, examples, in_axes, None, false)
63}
64
65/// [`check_vmap`], and also runs the batched function with XLA, which must
66/// agree with the interpreter within [`xla_tolerance`] (or `tolerance` for
67/// floats, if it is looser).
68///
69/// # Errors
70///
71/// Returns a description of the first disagreement.
72pub fn check_vmap_xla(
73    client: &Client,
74    f: &Function,
75    examples: &[Vec<HostArray>],
76    in_axes: &[Option<usize>],
77    tolerance: Option<(f64, f64)>,
78) -> Result<(), String> {
79    run_vmap(f, examples, in_axes, Some((client, tolerance)), false)
80}
81
82/// [`check_vmap`] for a function that only XLA runs (`extern_call`): the
83/// batched function and the loop both run with XLA.
84///
85/// # Errors
86///
87/// Returns a description of the first disagreement.
88pub fn check_vmap_xla_only(
89    client: &Client,
90    f: &Function,
91    examples: &[Vec<HostArray>],
92    in_axes: &[Option<usize>],
93    tolerance: Option<(f64, f64)>,
94) -> Result<(), String> {
95    run_vmap(f, examples, in_axes, Some((client, tolerance)), true)
96}
97
98fn run_vmap(
99    f: &Function,
100    examples: &[Vec<HostArray>],
101    in_axes: &[Option<usize>],
102    xla: Option<(&Client, Option<(f64, f64)>)>,
103    xla_only: bool,
104) -> Result<(), String> {
105    let n = examples.len();
106    let (g, out_axes) =
107        ruxla_transforms::vmap(f, in_axes, n).map_err(|e| format!("vmap failed: {e}"))?;
108    g.check()
109        .map_err(|e| format!("vmap made an ill-typed function: {e}\n{g}"))?;
110
111    // Each example, with unbatched arguments taken from the first example.
112    let example_args = |i: usize| -> Vec<HostArray> {
113        examples[i]
114            .iter()
115            .zip(in_axes)
116            .enumerate()
117            .map(|(j, (x, axis))| match axis {
118                Some(_) => x.clone(),
119                None => examples[0][j].clone(),
120            })
121            .collect()
122    };
123    // The reference: the interpreter, or XLA for XLA-only functions.
124    let run = |f: &Function, args: &[HostArray]| -> Result<Vec<HostArray>, String> {
125        match xla {
126            Some((client, _)) if xla_only => run_with_xla(client, f, args),
127            _ => catch(|| ruxla_interp::eval(f, args))?.map_err(|e| e.to_string()),
128        }
129    };
130    let expected: Vec<Vec<HostArray>> = (0..n)
131        .map(|i| run(f, &example_args(i)))
132        .collect::<Result<_, _>>()
133        .map_err(|e| format!("the function fails on an example: {e}"))?;
134    let args: Vec<HostArray> = in_axes
135        .iter()
136        .enumerate()
137        .map(|(j, axis)| match axis {
138            Some(d) => {
139                let column: Vec<HostArray> = examples.iter().map(|e| e[j].clone()).collect();
140                stack(&column, *d)
141            }
142            None => examples[0][j].clone(),
143        })
144        .collect();
145    let actual = run(&g, &args).map_err(|e| format!("the batched function fails: {e}\n{g}"))?;
146
147    for (k, (out, axis)) in actual.iter().zip(&out_axes).enumerate() {
148        let wanted: Vec<HostArray> = match axis {
149            Some(d) => {
150                let column: Vec<HostArray> = expected.iter().map(|e| e[k].clone()).collect();
151                vec![stack(&column, *d)]
152            }
153            None => expected.iter().map(|e| e[k].clone()).collect(),
154        };
155        for want in &wanted {
156            compare_bits(out, want)
157                .map_err(|e| format!("output {k} differs from the loop: {e}\n{g}"))?;
158        }
159    }
160
161    if xla_only {
162        return Ok(());
163    }
164    let native = catch(|| ruxla_core::eval_native(&g, &args))?
165        .map_err(|e| format!("native backend: {e}\n{g}"))?;
166    for (k, (a, i)) in native.iter().zip(&actual).enumerate() {
167        compare_bits(a, i).map_err(|e| {
168            format!("output {k}: the native backend differs from the interpreter: {e}\n{g}")
169        })?;
170    }
171
172    if let Some((client, tolerance)) = xla {
173        let outs = run_with_xla(client, &g, &args)?;
174        for (k, (a, e)) in outs.iter().zip(&actual).enumerate() {
175            let (rtol, atol) = xla_tolerance(e.dtype());
176            let (rtol, atol) = match tolerance {
177                Some((r, a)) if e.dtype().is_inexact() => (rtol.max(r), atol.max(a)),
178                _ => (rtol, atol),
179            };
180            compare(a, e, rtol, atol)
181                .map_err(|e| format!("output {k}: XLA differs from the interpreter: {e}\n{g}"))?;
182        }
183    }
184    Ok(())
185}
186
187/// The choices of input axes for arguments of the given ranks: all batched
188/// at dimension 0, all batched at their last dimension, and two mixes with
189/// unbatched arguments (alternating `None` and a batched dimension).
190fn in_axes_choices(ranks: &[usize]) -> Vec<Vec<Option<usize>>> {
191    let mut choices: Vec<Vec<Option<usize>>> = vec![
192        ranks.iter().map(|_| Some(0)).collect(),
193        ranks.iter().map(|&r| Some(r)).collect(),
194        ranks
195            .iter()
196            .enumerate()
197            .map(|(i, _)| (i % 2 == 1).then_some(0))
198            .collect(),
199        ranks
200            .iter()
201            .enumerate()
202            .map(|(i, &r)| (i % 2 == 0).then_some(r))
203            .collect(),
204    ];
205    choices.retain(|c| c.iter().any(Option::is_some));
206    let mut unique: Vec<Vec<Option<usize>>> = Vec::new();
207    for c in choices {
208        if !unique.contains(&c) {
209            unique.push(c);
210        }
211    }
212    unique
213}
214
215/// Whether two samples can be examples of one batch: the same parameters
216/// and argument types.
217fn compatible(a: &Sample, b: &Sample) -> bool {
218    a.params == b.params
219        && a.args.len() == b.args.len()
220        && a.args
221            .iter()
222            .zip(&b.args)
223            .all(|(x, y)| x.aval() == y.aval())
224}
225
226/// Runs [`check_vmap`] (and [`check_vmap_xla`] with a client) on the samples
227/// of `info` for its declared element types, and returns the failures.
228///
229/// The `axis_size` examples of a sample are made from samples drawn with
230/// different seeds, so that random arguments differ between examples.
231/// Example `i` takes, if they are compatible (the same parameters and
232/// argument types), the next `i`-th sample (so that, for instance, `cond`
233/// gets different indices and `while` different trip counts), or else the
234/// same sample. Index arguments stay valid because each example is a sample.
235fn check_samples(
236    info: &OpInfo,
237    seed: u64,
238    axis_size: usize,
239    client: Option<&Client>,
240) -> Vec<Failure> {
241    let mut failures = Vec::new();
242    // XLA-only primitives are checked only with XLA.
243    if info.xla_only && client.is_none() {
244        return failures;
245    }
246    for &dtype in &info.dtypes {
247        let mut fail = |sample: String, message: String| {
248            failures.push(Failure {
249                op: info.name(),
250                dtype,
251                sample,
252                message,
253            });
254        };
255        let draws = catch(|| {
256            (0..axis_size as u64)
257                .map(|i| (info.samples)(&mut Rng::new(seed.wrapping_add(i * 7919)), dtype))
258                .collect::<Vec<_>>()
259        });
260        let draws = match draws {
261            Ok(d) if !d.is_empty() => d,
262            Ok(_) => continue,
263            Err(message) => {
264                fail(String::from("(creating samples)"), message);
265                continue;
266            }
267        };
268        let count = draws[0].len();
269        for (s, sample) in draws[0].iter().enumerate() {
270            // XLA's fused loops divide by multiplying with the reciprocal and
271            // flush subnormals to zero, so `x / y` near the ends of the range
272            // (such as `inf / 3e38`) differs once a transpose or broadcast is
273            // fused with it. `check_op_xla` covers these values unbatched.
274            if client.is_some() && sample.name == "edge values" {
275                continue;
276            }
277            let f = match sample_function(info, sample) {
278                Ok(f) => f,
279                Err(message) => {
280                    fail(format!("{sample:?}"), message);
281                    continue;
282                }
283            };
284            let examples: Vec<Vec<HostArray>> = draws
285                .iter()
286                .enumerate()
287                .map(|(i, samples)| {
288                    let candidates = [samples.get((s + i) % count), samples.get(s)];
289                    candidates
290                        .into_iter()
291                        .flatten()
292                        .find(|c| samples.len() == count && compatible(c, sample))
293                        .unwrap_or(sample)
294                        .args
295                        .clone()
296                })
297                .collect();
298            let ranks: Vec<usize> = sample.args.iter().map(|x| x.shape().rank()).collect();
299            for in_axes in in_axes_choices(&ranks) {
300                let result = match client {
301                    None => check_vmap(&f, &examples, &in_axes),
302                    Some(c) if info.xla_only => {
303                        check_vmap_xla_only(c, &f, &examples, &in_axes, info.xla_tolerance)
304                    }
305                    Some(c) => check_vmap_xla(c, &f, &examples, &in_axes, info.xla_tolerance),
306                };
307                if let Err(message) = result {
308                    fail(format!("{sample:?} with in_axes {in_axes:?}"), message);
309                }
310            }
311        }
312    }
313    failures
314}
315
316/// Checks `vmap` of every sample of `info` for its declared element types
317/// against a loop over `axis_size` examples, with the interpreter and the
318/// native backend, for several choices of input axes. Returns the failures.
319pub fn check_op_vmap(info: &OpInfo, seed: u64, axis_size: usize) -> Vec<Failure> {
320    check_samples(info, seed, axis_size, None)
321}
322
323/// [`check_op_vmap`], also running the batched functions with XLA.
324///
325/// Samples named `edge values` are left out: XLA computes the extremes of
326/// the range differently once the batching transposes or broadcasts are
327/// fused with the operation (see the source).
328pub fn check_op_vmap_xla(
329    info: &OpInfo,
330    seed: u64,
331    axis_size: usize,
332    client: &Client,
333) -> Vec<Failure> {
334    check_samples(info, seed, axis_size, Some(client))
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    #[test]
342    fn stack_inserts_a_dimension() {
343        let a = HostArray::from_vec(vec![1i32, 2, 3, 4], [2, 2]);
344        let b = HostArray::from_vec(vec![5i32, 6, 7, 8], [2, 2]);
345        let s = stack(&[a.clone(), b.clone()], 0);
346        assert_eq!(s.to_vec::<i32>().unwrap(), [1, 2, 3, 4, 5, 6, 7, 8]);
347        let s = stack(&[a.clone(), b.clone()], 1);
348        assert_eq!(s.shape().dims(), [2, 2, 2]);
349        assert_eq!(s.to_vec::<i32>().unwrap(), [1, 2, 5, 6, 3, 4, 7, 8]);
350        let s = stack(&[a, b], 2);
351        assert_eq!(s.to_vec::<i32>().unwrap(), [1, 5, 2, 6, 3, 7, 4, 8]);
352        let s = stack(&[HostArray::scalar(1.5f32), HostArray::scalar(2.5f32)], 0);
353        assert_eq!(s.to_vec::<f32>().unwrap(), [1.5, 2.5]);
354    }
355
356    #[test]
357    fn in_axes_include_unbatched_arguments() {
358        assert_eq!(
359            in_axes_choices(&[1, 0]),
360            [
361                vec![Some(0), Some(0)],
362                vec![Some(1), Some(0)],
363                vec![None, Some(0)],
364                vec![Some(1), None],
365            ]
366        );
367        assert_eq!(in_axes_choices(&[0]), [vec![Some(0)]]);
368    }
369}