Skip to main content

ruxla_testing/
opinfo.rs

1//! OpInfo: declarative test samples for primitives, and the checks that run
2//! on all of them.
3
4use std::fmt;
5use std::path::PathBuf;
6use std::sync::Arc;
7
8use ruxla_ir::lowering::Target;
9use ruxla_ir::{AVal, Atom, DType, Eqn, Function, HostArray, Params, Prim, Value, Var};
10use ruxla_pjrt::{Client, Plugin};
11
12use crate::rng::Rng;
13
14/// One test case of a primitive: parameters and arguments.
15#[derive(Clone)]
16pub struct Sample {
17    /// A short description, shown in failure reports.
18    pub name: String,
19    /// The parameters.
20    pub params: Params,
21    /// The arguments.
22    pub args: Vec<HostArray>,
23    /// The expected results, if the sample knows them.
24    pub expected: Option<Vec<HostArray>>,
25}
26
27impl Sample {
28    /// Creates a sample without expected results.
29    pub fn new(name: impl Into<String>, params: Params, args: Vec<HostArray>) -> Self {
30        Self {
31            name: name.into(),
32            params,
33            args,
34            expected: None,
35        }
36    }
37
38    /// Sets the expected results.
39    pub fn expect(mut self, expected: Vec<HostArray>) -> Self {
40        self.expected = Some(expected);
41        self
42    }
43}
44
45impl fmt::Debug for Sample {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        let avals: Vec<String> = self.args.iter().map(|a| a.aval().to_string()).collect();
48        write!(f, "{}({})", self.name, avals.join(", "))
49    }
50}
51
52/// Creates the samples of a primitive for one element type.
53pub type SamplesFn = Arc<dyn Fn(&mut Rng, DType) -> Vec<Sample> + Send + Sync>;
54
55/// The test declaration of one primitive.
56#[derive(Clone)]
57pub struct OpInfo {
58    /// The primitive.
59    pub prim: Prim,
60    /// The element types whose samples must be accepted. Other types are
61    /// tried as well, and checked against XLA when the primitive accepts
62    /// them.
63    pub dtypes: Vec<DType>,
64    /// Creates the samples for one element type.
65    pub samples: SamplesFn,
66    /// A looser tolerance `(rtol, atol)` for floats against XLA than
67    /// [`xla_tolerance`], if needed.
68    pub xla_tolerance: Option<(f64, f64)>,
69    /// Whether only XLA runs the primitive (`extern_call`): the samples
70    /// then carry expected values, against which XLA is checked, and the
71    /// interpreter and the native backend are not checked.
72    pub xla_only: bool,
73}
74
75impl OpInfo {
76    /// Creates a declaration.
77    pub fn new(
78        prim: Prim,
79        dtypes: &[DType],
80        samples: impl Fn(&mut Rng, DType) -> Vec<Sample> + Send + Sync + 'static,
81    ) -> Self {
82        Self {
83            prim,
84            dtypes: dtypes.to_vec(),
85            samples: Arc::new(samples),
86            xla_tolerance: None,
87            xla_only: false,
88        }
89    }
90
91    /// Sets the tolerance for floats against XLA.
92    pub fn xla_tolerance(mut self, rtol: f64, atol: f64) -> Self {
93        self.xla_tolerance = Some((rtol, atol));
94        self
95    }
96
97    /// Marks the primitive as run only by XLA (see [`OpInfo::xla_only`]).
98    pub fn xla_only(mut self) -> Self {
99        self.xla_only = true;
100        self
101    }
102
103    /// The name of the primitive.
104    pub fn name(&self) -> &'static str {
105        self.prim.name()
106    }
107}
108
109impl fmt::Debug for OpInfo {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        f.debug_struct("OpInfo")
112            .field("prim", &self.prim.name())
113            .field("dtypes", &self.dtypes)
114            .finish_non_exhaustive()
115    }
116}
117
118/// Returns the tolerance `(rtol, atol)` for comparing results of a type
119/// with expected values.
120pub fn tolerance(dtype: DType) -> (f64, f64) {
121    match dtype.real_dtype() {
122        DType::F16 => (1e-3, 1e-3),
123        DType::BF16 => (1e-2, 1e-2),
124        DType::F32 => (1e-6, 1e-6),
125        DType::F64 => (1e-12, 1e-12),
126        _ => (0.0, 0.0),
127    }
128}
129
130/// Returns the tolerance `(rtol, atol)` for comparing XLA with the
131/// interpreter.
132///
133/// XLA computes transcendental functions with its own approximations, fuses
134/// multiplications and additions, and may reorder sums, so the last bits
135/// differ.
136pub fn xla_tolerance(dtype: DType) -> (f64, f64) {
137    match dtype.real_dtype() {
138        DType::F16 => (2e-3, 2e-3),
139        DType::BF16 => (2e-2, 2e-2),
140        DType::F32 => (1e-5, 1e-6),
141        DType::F64 => (1e-12, 1e-12),
142        _ => (0.0, 0.0),
143    }
144}
145
146/// Returns whether two values are equal within a tolerance. NaN equals NaN.
147///
148/// The parts of complex numbers are compared separately, relative to the
149/// larger part of the expected value.
150pub fn values_close(actual: Value, expected: Value, rtol: f64, atol: f64) -> bool {
151    let close = |a: f64, e: f64, scale: f64| {
152        (a.is_nan() && e.is_nan()) || a == e || (a - e).abs() <= atol + rtol * scale
153    };
154    match (actual, expected) {
155        (Value::Float(a), Value::Float(e)) => close(a, e, e.abs()),
156        (Value::Complex(ar, ai), Value::Complex(er, ei)) => {
157            // The larger finite part.
158            let finite = |x: f64| if x.is_finite() { x.abs() } else { 0.0 };
159            let scale = finite(er).max(finite(ei));
160            close(ar, er, scale) && close(ai, ei, scale)
161        }
162        (a, e) => a == e,
163    }
164}
165
166/// Compares two host arrays within a tolerance, describing the first
167/// difference.
168///
169/// # Errors
170///
171/// Returns a description of the first mismatch in shape, type, or value.
172pub fn compare(
173    actual: &HostArray,
174    expected: &HostArray,
175    rtol: f64,
176    atol: f64,
177) -> Result<(), String> {
178    if actual.aval() != expected.aval() {
179        return Err(format!(
180            "expected {}, got {}",
181            expected.aval(),
182            actual.aval()
183        ));
184    }
185    for i in 0..actual.size() {
186        let (a, e) = (actual.get(i), expected.get(i));
187        if !values_close(a, e, rtol, atol) {
188            return Err(format!("element {i}: expected {e:?}, got {a:?}"));
189        }
190    }
191    Ok(())
192}
193
194/// Compares two host arrays bit for bit.
195pub(crate) fn compare_bits(actual: &HostArray, expected: &HostArray) -> Result<(), String> {
196    if actual.aval() != expected.aval() {
197        return Err(format!(
198            "expected {}, got {}",
199            expected.aval(),
200            actual.aval()
201        ));
202    }
203    let size = actual.dtype().size_in_bytes();
204    let (a, e) = (actual.to_bytes(), expected.to_bytes());
205    // A NaN matches any NaN (the bits of a NaN that an operation makes are
206    // not specified, and depend on how the generic kernels are optimized in
207    // the crate that instantiates them).
208    let both_nan = |i: usize| match (actual.get(i), expected.get(i)) {
209        (Value::Float(x), Value::Float(y)) => x.is_nan() && y.is_nan(),
210        (Value::Complex(xr, xi), Value::Complex(yr, yi)) => {
211            (xr.to_bits() == yr.to_bits() || (xr.is_nan() && yr.is_nan()))
212                && (xi.to_bits() == yi.to_bits() || (xi.is_nan() && yi.is_nan()))
213        }
214        _ => false,
215    };
216    match (0..actual.size())
217        .find(|&i| a[i * size..(i + 1) * size] != e[i * size..(i + 1) * size] && !both_nan(i))
218    {
219        None => Ok(()),
220        Some(i) => Err(format!(
221            "element {i}: expected {:?}, got {:?}",
222            expected.get(i),
223            actual.get(i)
224        )),
225    }
226}
227
228/// A failed check.
229#[derive(Clone, Debug)]
230pub struct Failure {
231    /// The primitive.
232    pub op: &'static str,
233    /// The element type of the samples.
234    pub dtype: DType,
235    /// The sample.
236    pub sample: String,
237    /// What went wrong.
238    pub message: String,
239}
240
241impl fmt::Display for Failure {
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        write!(
244            f,
245            "{} [{}] {}: {}",
246            self.op, self.dtype, self.sample, self.message
247        )
248    }
249}
250
251/// Runs a closure, turning a panic into an error message.
252pub(crate) fn catch<T>(f: impl FnOnce() -> T) -> Result<T, String> {
253    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|e| {
254        e.downcast_ref::<String>()
255            .cloned()
256            .or_else(|| e.downcast_ref::<&str>().map(|s| (*s).to_string()))
257            .unwrap_or_else(|| String::from("panic"))
258    })
259}
260
261/// Builds a function that applies `prim` to arguments of the given types.
262///
263/// # Errors
264///
265/// Returns the error of `abstract_eval` if the primitive rejects them.
266pub fn single_equation(
267    prim: Prim,
268    params: &Params,
269    in_avals: &[AVal],
270) -> ruxla_ir::Result<Function> {
271    let out_avals = prim.abstract_eval(in_avals, params)?;
272    let invars: Vec<Var> = in_avals.iter().cloned().map(Var::new).collect();
273    let outputs: Vec<Var> = out_avals.into_iter().map(Var::new).collect();
274    Ok(Function {
275        eqns: vec![Eqn {
276            prim,
277            inputs: invars.iter().cloned().map(Atom::Var).collect(),
278            params: params.clone(),
279            outputs: outputs.clone(),
280            loc: None,
281        }],
282        invars,
283        outvars: outputs.into_iter().map(Atom::Var).collect(),
284        ..Function::default()
285    })
286}
287
288pub(crate) fn sample_function(info: &OpInfo, sample: &Sample) -> Result<Function, String> {
289    let avals: Vec<AVal> = sample.args.iter().map(HostArray::aval).collect();
290    let f =
291        single_equation(info.prim, &sample.params, &avals).map_err(|e| format!("rejected: {e}"))?;
292    f.check().map_err(|e| format!("ill-typed IR: {e}"))?;
293    Ok(f)
294}
295
296/// Checks every sample of `info` for its declared element types with the
297/// interpreter and the native backend, and returns the failures.
298///
299/// For each sample, it checks that:
300///
301/// 1. the primitive accepts the arguments, and the IR is well typed,
302/// 2. the interpreter's results have the types `abstract_eval` predicts,
303/// 3. the native backend gives the same results bit for bit,
304/// 4. the results match the sample's expected values, if any.
305pub fn check_op(info: &OpInfo, seed: u64) -> Vec<Failure> {
306    let mut failures = Vec::new();
307    let mut rng = Rng::new(seed);
308    for &dtype in &info.dtypes {
309        let mut fail = |sample: String, message: String| {
310            failures.push(Failure {
311                op: info.name(),
312                dtype,
313                sample,
314                message,
315            });
316        };
317        let samples = match catch(|| (info.samples)(&mut rng, dtype)) {
318            Ok(samples) => samples,
319            Err(message) => {
320                fail(String::from("(creating samples)"), message);
321                continue;
322            }
323        };
324        if samples.is_empty() {
325            fail(String::new(), String::from("no samples"));
326        }
327        for sample in samples {
328            if let Err(message) = check_sample(info, &sample) {
329                fail(format!("{sample:?}"), message);
330            }
331        }
332    }
333    failures
334}
335
336fn check_sample(info: &OpInfo, sample: &Sample) -> Result<(), String> {
337    let f = sample_function(info, sample)?;
338    if info.xla_only {
339        if sample.expected.is_none() {
340            return Err(String::from(
341                "samples of XLA-only primitives need expected values",
342            ));
343        }
344        return match ruxla_interp::eval(&f, &sample.args) {
345            Err(_) => Ok(()),
346            Ok(_) => Err(String::from("the interpreter runs an XLA-only primitive")),
347        };
348    }
349    let interp =
350        catch(|| ruxla_interp::eval(&f, &sample.args))?.map_err(|e| format!("interpreter: {e}"))?;
351    for (x, v) in interp.iter().zip(&f.outvars) {
352        if x.aval() != v.aval() {
353            return Err(format!(
354                "the interpreter gives {}, but abstract_eval predicts {}",
355                x.aval(),
356                v.aval()
357            ));
358        }
359    }
360    let native =
361        catch(|| ruxla_core::eval_native(&f, &sample.args))?.map_err(|e| format!("native: {e}"))?;
362    for (n, i) in native.iter().zip(&interp) {
363        compare_bits(n, i).map_err(|e| format!("native differs from the interpreter: {e}"))?;
364    }
365    if let Some(expected) = &sample.expected {
366        for (x, e) in interp.iter().zip(expected) {
367            let (rtol, atol) = tolerance(e.dtype());
368            compare(x, e, rtol, atol).map_err(|e| format!("wrong result: {e}"))?;
369        }
370    }
371    Ok(())
372}
373
374/// Returns a client of the PJRT CPU plugin, or `None` if the plugin is not
375/// available.
376///
377/// The plugin is taken from `RUXLA_PJRT_CPU_PLUGIN`, or from `.cache/pjrt/`
378/// in the workspace, where `scripts/fetch-pjrt-plugins.sh` puts it.
379pub fn pjrt_cpu_client() -> Option<Client> {
380    let path = std::env::var_os("RUXLA_PJRT_CPU_PLUGIN")
381        .map(PathBuf::from)
382        .unwrap_or_else(|| {
383            PathBuf::from(env!("CARGO_MANIFEST_DIR"))
384                .join("../../.cache/pjrt")
385                .join(ruxla_core::runtime::Platform::Cpu.plugin_file())
386        });
387    if !path.exists() {
388        return None;
389    }
390    let plugin = Plugin::load(&path).ok()?;
391    // The handlers of the custom calls of linear algebra.
392    ruxla_pjrt::linalg::register_handlers(plugin, "Host").ok()?;
393    plugin.client().ok()
394}
395
396/// Compiles a function with XLA, runs it on `args`, and returns its outputs.
397///
398/// # Errors
399///
400/// Returns a description of the failure, including the StableHLO module if
401/// it does not compile.
402pub fn run_with_xla(
403    client: &Client,
404    f: &Function,
405    args: &[HostArray],
406) -> Result<Vec<HostArray>, String> {
407    let module =
408        ruxla_stablehlo::lower(f, Target::Pjrt).map_err(|e| format!("lowering failed: {e}"))?;
409    let exe = client
410        .compile(&module)
411        .map_err(|e| format!("XLA rejected the module: {e}\n{module}"))?;
412    let buffers = args
413        .iter()
414        .map(|a| client.buffer_from_host_array(a))
415        .collect::<Result<Vec<_>, _>>()
416        .map_err(|e| e.to_string())?;
417    let outputs = exe
418        .execute(&buffers.iter().collect::<Vec<_>>())
419        .map_err(|e| e.to_string())?;
420    outputs
421        .iter()
422        .map(|b| b.to_host_array().map_err(|e| e.to_string()))
423        .collect()
424}
425
426/// The result of [`check_op_xla`].
427#[derive(Clone, Debug, Default)]
428pub struct XlaReport {
429    /// The failures.
430    pub failures: Vec<Failure>,
431    /// The element types that were checked (declared, or accepted by the
432    /// primitive).
433    pub dtypes: Vec<DType>,
434    /// The number of samples run.
435    pub samples: usize,
436}
437
438/// Checks the samples of `info` against XLA for every element type: the
439/// declared ones, and the others that the primitive accepts.
440pub fn check_op_xla(info: &OpInfo, seed: u64, client: &Client) -> XlaReport {
441    let mut report = XlaReport::default();
442    let mut rng = Rng::new(seed);
443    for dtype in DType::ALL {
444        let declared = info.dtypes.contains(&dtype);
445        let Ok(samples) = catch(|| (info.samples)(&mut rng, dtype)) else {
446            continue;
447        };
448        let mut checked = false;
449        for sample in samples {
450            let f = match sample_function(info, &sample) {
451                Ok(f) => f,
452                // Undeclared types may be rejected; `check_op` reports
453                // declared ones.
454                Err(_) => continue,
455            };
456            checked = true;
457            report.samples += 1;
458            let result = (|| {
459                let expected = if info.xla_only {
460                    sample.expected.clone().ok_or("no expected values")?
461                } else {
462                    catch(|| ruxla_interp::eval(&f, &sample.args))?
463                        .map_err(|e| format!("interpreter: {e}"))?
464                };
465                let actual = run_with_xla(client, &f, &sample.args)?;
466                for (a, e) in actual.iter().zip(&expected) {
467                    let (rtol, atol) = xla_tolerance(e.dtype());
468                    let (rtol, atol) = match info.xla_tolerance {
469                        Some((r, a)) if e.dtype().is_inexact() => (rtol.max(r), atol.max(a)),
470                        _ => (rtol, atol),
471                    };
472                    compare(a, e, rtol, atol)
473                        .map_err(|e| format!("XLA differs from the interpreter: {e}"))?;
474                }
475                Ok::<_, String>(())
476            })();
477            if let Err(message) = result {
478                report.failures.push(Failure {
479                    op: info.name(),
480                    dtype,
481                    sample: format!("{sample:?}"),
482                    message,
483                });
484            }
485        }
486        if checked || declared {
487            report.dtypes.push(dtype);
488        }
489    }
490    report
491}