1use 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#[derive(Clone)]
16pub struct Sample {
17 pub name: String,
19 pub params: Params,
21 pub args: Vec<HostArray>,
23 pub expected: Option<Vec<HostArray>>,
25}
26
27impl Sample {
28 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 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
52pub type SamplesFn = Arc<dyn Fn(&mut Rng, DType) -> Vec<Sample> + Send + Sync>;
54
55#[derive(Clone)]
57pub struct OpInfo {
58 pub prim: Prim,
60 pub dtypes: Vec<DType>,
64 pub samples: SamplesFn,
66 pub xla_tolerance: Option<(f64, f64)>,
69 pub xla_only: bool,
73}
74
75impl OpInfo {
76 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 pub fn xla_tolerance(mut self, rtol: f64, atol: f64) -> Self {
93 self.xla_tolerance = Some((rtol, atol));
94 self
95 }
96
97 pub fn xla_only(mut self) -> Self {
99 self.xla_only = true;
100 self
101 }
102
103 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
118pub 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
130pub 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
146pub 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 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
166pub 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
194pub(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 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#[derive(Clone, Debug)]
230pub struct Failure {
231 pub op: &'static str,
233 pub dtype: DType,
235 pub sample: String,
237 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
251pub(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
261pub 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
296pub 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
374pub 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 ruxla_pjrt::linalg::register_handlers(plugin, "Host").ok()?;
393 plugin.client().ok()
394}
395
396pub 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#[derive(Clone, Debug, Default)]
428pub struct XlaReport {
429 pub failures: Vec<Failure>,
431 pub dtypes: Vec<DType>,
434 pub samples: usize,
436}
437
438pub 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 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}