1use 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
13pub 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
44pub 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
65pub 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
82pub 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 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 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
187fn 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
215fn 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
226fn 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 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 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
316pub fn check_op_vmap(info: &OpInfo, seed: u64, axis_size: usize) -> Vec<Failure> {
320 check_samples(info, seed, axis_size, None)
321}
322
323pub 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}