Skip to main content

ruxla_testing/
ops.rs

1//! The OpInfo declarations of the primitives.
2
3use std::sync::Arc;
4
5use ruxla_ir::{
6    AVal, Atom, ConvDims, DType, DotDims, Eqn, FftType, Function, GatherDims, GatherScatterMode,
7    HostArray, Literal, Params, Precision, Prim, RoundingMethod, ScatterDims, SelectPrim, Shape,
8    Value, Var,
9};
10use ruxla_prims as p;
11
12use crate::opinfo::{OpInfo, Sample};
13use crate::rng::{Domain, Rng, edge_values, from_values};
14
15/// Shapes of elementwise samples, including a scalar and an empty array.
16const SHAPES: [&[usize]; 4] = [&[], &[5], &[2, 3], &[0, 2]];
17
18const FLOATS: [DType; 4] = [DType::F16, DType::BF16, DType::F32, DType::F64];
19const NUMERIC: [DType; 8] = [
20    DType::I8,
21    DType::I32,
22    DType::U8,
23    DType::U32,
24    DType::F16,
25    DType::BF16,
26    DType::F32,
27    DType::F64,
28];
29const INTS: [DType; 4] = [DType::I8, DType::I32, DType::U8, DType::U32];
30const LOGICAL: [DType; 4] = [DType::Bool, DType::I32, DType::U8, DType::I64];
31const ORDERED: [DType; 6] = [
32    DType::Bool,
33    DType::I32,
34    DType::U16,
35    DType::BF16,
36    DType::F32,
37    DType::F64,
38];
39const ORDERED_NUMBERS: [DType; 5] = [DType::I32, DType::U16, DType::BF16, DType::F32, DType::F64];
40const LAYOUT: [DType; 5] = [DType::Bool, DType::I32, DType::BF16, DType::F32, DType::C64];
41/// Numbers, including complex numbers.
42const NUMBERS: [DType; 10] = [
43    DType::I8,
44    DType::I32,
45    DType::U8,
46    DType::U32,
47    DType::F16,
48    DType::BF16,
49    DType::F32,
50    DType::F64,
51    DType::C64,
52    DType::C128,
53];
54/// Signed numbers, including complex numbers.
55const SIGNED_NUMBERS: [DType; 8] = [
56    DType::I8,
57    DType::I32,
58    DType::I64,
59    DType::F16,
60    DType::F32,
61    DType::F64,
62    DType::C64,
63    DType::C128,
64];
65const COMPLEX: [DType; 2] = [DType::C64, DType::C128];
66/// Floats and complex numbers.
67const INEXACT: [DType; 6] = [
68    DType::F16,
69    DType::BF16,
70    DType::F32,
71    DType::F64,
72    DType::C64,
73    DType::C128,
74];
75/// Types with equality (and `max` and `min`, lexicographic for complex
76/// numbers).
77const EQUALITY: [DType; 8] = [
78    DType::Bool,
79    DType::I32,
80    DType::U16,
81    DType::BF16,
82    DType::F32,
83    DType::F64,
84    DType::C64,
85    DType::C128,
86];
87
88/// Returns the OpInfo declarations of every primitive.
89pub fn op_infos() -> Vec<OpInfo> {
90    let mut infos = vec![
91        unary(p::NEG, &NUMBERS, Domain::Any),
92        unary(p::ABS, &SIGNED_NUMBERS, Domain::Any),
93        unary(p::SIGN, &SIGNED_NUMBERS, Domain::Any),
94        unary(p::NOT, &LOGICAL, Domain::Any),
95        unary(p::FLOOR, &FLOATS, Domain::Any),
96        unary(p::CEIL, &FLOATS, Domain::Any),
97        unary(p::EXP, &INEXACT, Domain::Any),
98        unary(p::EXPM1, &INEXACT, Domain::Any),
99        unary(p::LOG, &INEXACT, Domain::Positive),
100        unary(p::LOG1P, &INEXACT, Domain::Positive),
101        unary(p::SQRT, &INEXACT, Domain::Positive),
102        unary(p::RSQRT, &INEXACT, Domain::Positive),
103        unary(p::CBRT, &FLOATS, Domain::Any),
104        unary(p::SIN, &INEXACT, Domain::Any),
105        unary(p::COS, &INEXACT, Domain::Any),
106        unary(p::TAN, &INEXACT, Domain::Any),
107        unary(p::TANH, &INEXACT, Domain::Any),
108        unary(p::LOGISTIC, &INEXACT, Domain::Any),
109        unary(p::SQUARE, &NUMBERS, Domain::Any),
110        unary(p::ERF_INV, &FLOATS, Domain::Unit),
111        unary(p::LGAMMA, &FLOATS, Domain::Any),
112        digamma(),
113        unary(p::ERF, &FLOATS, Domain::Any),
114        unary(p::ERFC, &FLOATS, Domain::Any),
115        unary(p::BESSEL_I0E, &FLOATS, Domain::Any),
116        unary(p::BESSEL_I1E, &FLOATS, Domain::Any),
117        unary(p::IS_FINITE, &FLOATS, Domain::Any),
118        round(),
119        integer_pow(),
120        binary(p::ADD, &NUMBERS, Domain::Any),
121        binary(p::SUB, &NUMBERS, Domain::Any),
122        binary(p::MUL, &NUMBERS, Domain::Any),
123        binary(p::DIV, &NUMBERS, Domain::NonZero),
124        binary(p::REM, &NUMERIC, Domain::NonZero),
125        binary(p::POW, &INEXACT, Domain::Positive),
126        binary(p::MAX, &EQUALITY, Domain::Any),
127        binary(p::MIN, &EQUALITY, Domain::Any),
128        binary(p::ATAN2, &FLOATS, Domain::Any),
129        incomplete_gamma(p::IGAMMA),
130        incomplete_gamma(p::IGAMMAC),
131        incomplete_gamma(p::IGAMMA_GRAD_A),
132        incomplete_gamma(p::RANDOM_GAMMA_GRAD),
133        polygamma(),
134        zeta(),
135        betainc(),
136        binary(p::AND, &LOGICAL, Domain::Any),
137        binary(p::OR, &LOGICAL, Domain::Any),
138        binary(p::XOR, &LOGICAL, Domain::Any),
139        binary(p::SHIFT_LEFT, &INTS, Domain::Any),
140        binary(p::SHIFT_RIGHT_LOGICAL, &INTS, Domain::Any),
141        binary(p::SHIFT_RIGHT_ARITHMETIC, &INTS, Domain::Any),
142        binary(p::EQ, &EQUALITY, Domain::Any),
143        binary(p::NE, &EQUALITY, Domain::Any),
144        binary(p::LT, &ORDERED, Domain::Any),
145        binary(p::LE, &ORDERED, Domain::Any),
146        binary(p::GT, &ORDERED, Domain::Any),
147        binary(p::GE, &ORDERED, Domain::Any),
148        convert(),
149        bitcast(),
150        select_n(),
151        clamp(),
152        unary(p::REAL, &COMPLEX, Domain::Any),
153        unary(p::IMAG, &COMPLEX, Domain::Any),
154        binary(p::COMPLEX, &[DType::F32, DType::F64], Domain::Any),
155        unary(
156            p::CONJ,
157            &[DType::F32, DType::F64, DType::C64, DType::C128],
158            Domain::Any,
159        ),
160    ];
161    infos.extend(structural());
162    infos.extend(reductions());
163    infos.push(sort());
164    infos.push(threefry2x32());
165    infos.extend(cumulative());
166    infos.push(top_k());
167    infos.push(fft());
168    infos.push(dot_general());
169    infos.push(conv_general_dilated());
170    infos.extend(windows());
171    infos.extend(crate::ops_linalg::linalg());
172    infos.push(gather());
173    infos.extend(scatters());
174    infos.extend(control());
175    infos.extend(custom());
176    infos.push(extern_call());
177    infos.push(host_callback());
178    infos
179}
180
181/// A module like one written by `jax.export`: `main(x, y) = (x * y + x,
182/// max(x, y))` on `f32[3]`, with a location alias and module attributes.
183const EXTERN_MODULE: &str = r#"#loc1 = loc("x")
184module @jit_f attributes {mhlo.num_partitions = 1 : i32, mhlo.num_replicas = 1 : i32} {
185  func.func public @main(%arg0: tensor<3xf32> loc("x"), %arg1: tensor<3xf32> loc("y")) -> (tensor<3xf32> {jax.result_info = "result[0]"}, tensor<3xf32> {jax.result_info = "result[1]"}) {
186    %0 = stablehlo.multiply %arg0, %arg1 : tensor<3xf32>
187    %1 = call @helper(%0, %arg0) : (tensor<3xf32>, tensor<3xf32>) -> tensor<3xf32>
188    %2 = stablehlo.maximum %arg0, %arg1 : tensor<3xf32>
189    return %1, %2 : tensor<3xf32>, tensor<3xf32>
190  }
191  func.func private @helper(%a: tensor<3xf32>, %b: tensor<3xf32>) -> tensor<3xf32> {
192    %0 = stablehlo.add %a, %b : tensor<3xf32>
193    return %0 : tensor<3xf32>
194  }
195}
196"#;
197
198fn extern_call() -> OpInfo {
199    OpInfo::new(p::EXTERN_CALL, &[DType::F32], |rng, d| {
200        if d != DType::F32 {
201            return Vec::new();
202        }
203        let f32s = AVal::new([3], DType::F32);
204        let params = Params::Extern {
205            name: String::from("f"),
206            module: EXTERN_MODULE.into(),
207            inputs: vec![f32s.clone(), f32s.clone()],
208            outputs: vec![f32s.clone(), f32s],
209        };
210        (0..3)
211            .map(|i| {
212                let (x, y) = (
213                    rng.array([3], d, Domain::Any),
214                    rng.array([3], d, Domain::Any),
215                );
216                let (xv, yv) = (x.to_vec::<f32>().unwrap(), y.to_vec::<f32>().unwrap());
217                let first: Vec<f32> = xv.iter().zip(&yv).map(|(a, b)| a * b + a).collect();
218                let second: Vec<f32> = xv.iter().zip(&yv).map(|(a, b)| a.max(*b)).collect();
219                Sample::new(format!("call {i}"), params.clone(), vec![x, y]).expect(vec![
220                    HostArray::from_vec(first, [3]),
221                    HostArray::from_vec(second, [3]),
222                ])
223            })
224            .collect()
225    })
226    .xla_only()
227}
228
229/// `host_callback` with a Rust function of two results: `2 x + y` and the
230/// sum of `x` (in `f64`, rounded to the type).
231fn host_callback() -> OpInfo {
232    use ruxla_ir::callback::HostCallback;
233    OpInfo::new(p::HOST_CALLBACK, &[DType::F32, DType::F64], |rng, d| {
234        if !matches!(d, DType::F32 | DType::F64) {
235            return Vec::new();
236        }
237        let callback = HostCallback::new("affine_and_sum", move |args: &[HostArray]| {
238            let x = args[0]
239                .convert(DType::F64)
240                .to_vec::<f64>()
241                .map_err(|e| e.to_string())?;
242            let y = args[1]
243                .convert(DType::F64)
244                .to_vec::<f64>()
245                .map_err(|e| e.to_string())?;
246            let z: Vec<f64> = x.iter().zip(&y).map(|(a, b)| 2.0 * a + b).collect();
247            let s: f64 = x.iter().sum();
248            let dtype = args[0].dtype();
249            Ok(vec![
250                HostArray::from_vec(z, args[0].shape().clone()).convert(dtype),
251                HostArray::from_vec(vec![s], []).convert(dtype),
252            ])
253        });
254        [vec![3], vec![2, 4]]
255            .into_iter()
256            .map(|shape: Vec<usize>| {
257                let params = Params::HostCallback {
258                    callback: callback.clone(),
259                    outputs: vec![AVal::new(shape.clone(), d), AVal::new([], d)],
260                };
261                let (x, y) = (
262                    rng.array(shape.clone(), d, Domain::Any),
263                    rng.array(shape.clone(), d, Domain::Any),
264                );
265                Sample::new(format!("{shape:?}"), params, vec![x, y])
266            })
267            .collect()
268    })
269}
270
271/// Elementwise samples: random arguments of each shape in [`SHAPES`], and
272/// the edge values of the type (every pair of them for two operands).
273fn elementwise_samples(
274    rng: &mut Rng,
275    d: DType,
276    arity: usize,
277    domain: Domain,
278    params: &Params,
279) -> Vec<Sample> {
280    let mut samples: Vec<Sample> = SHAPES
281        .iter()
282        .map(|&shape| {
283            let args = (0..arity).map(|_| rng.array(shape, d, domain)).collect();
284            Sample::new(format!("{shape:?}"), params.clone(), args)
285        })
286        .collect();
287    let edge = edge_values(d);
288    let n = edge.size();
289    let values: Vec<Value> = (0..n).map(|i| edge.get(i)).collect();
290    let args = match arity {
291        1 => vec![edge],
292        _ => {
293            let x: Vec<Value> = values.iter().flat_map(|&v| vec![v; n]).collect();
294            let y: Vec<Value> = (0..n).flat_map(|_| values.iter().copied()).collect();
295            vec![from_values(&x, [n * n], d), from_values(&y, [n * n], d)]
296        }
297    };
298    samples.push(Sample::new("edge values", params.clone(), args));
299    samples
300}
301
302fn unary(prim: Prim, dtypes: &[DType], domain: Domain) -> OpInfo {
303    OpInfo::new(prim, dtypes, move |rng, d| {
304        elementwise_samples(rng, d, 1, domain, &Params::None)
305    })
306}
307
308fn binary(prim: Prim, dtypes: &[DType], domain: Domain) -> OpInfo {
309    OpInfo::new(prim, dtypes, move |rng, d| {
310        elementwise_samples(rng, d, 2, domain, &Params::None)
311    })
312}
313
314/// Samples of a special function: random arguments of each shape in
315/// [`SHAPES`], and every combination of the given edge values.
316fn special_samples(
317    rng: &mut Rng,
318    d: DType,
319    arity: usize,
320    domain: Domain,
321    edges: &[f64],
322) -> Vec<Sample> {
323    let mut samples: Vec<Sample> = SHAPES
324        .iter()
325        .map(|&shape| {
326            let args = (0..arity).map(|_| rng.array(shape, d, domain)).collect();
327            Sample::new(format!("{shape:?}"), Params::None, args)
328        })
329        .collect();
330    let n = edges.len();
331    let size = n.pow(arity as u32);
332    let args = (0..arity)
333        .map(|k| {
334            let stride = n.pow((arity - 1 - k) as u32);
335            let values: Vec<Value> = (0..size)
336                .map(|i| Value::Float(edges[(i / stride) % n]))
337                .collect();
338            from_values(&values, [size], d)
339        })
340        .collect();
341    samples.push(Sample::new("edge values", Params::None, args));
342    samples
343}
344
345/// The incomplete gamma functions. The edge values exclude huge pairs such
346/// as `(3e38, 3e38)`, for which the series converges only after about
347/// `1 / eps` iterations (as in JAX).
348fn incomplete_gamma(prim: Prim) -> OpInfo {
349    OpInfo::new(prim, &FLOATS, |rng, d| {
350        let edges = [
351            f64::NAN,
352            0.0,
353            -1.0,
354            1e-30,
355            0.5,
356            1.0,
357            2.5,
358            30.0,
359            f64::INFINITY,
360        ];
361        special_samples(rng, d, 2, Domain::Positive, &edges)
362    })
363}
364
365/// `digamma`. The edge values exclude zero (and values that round to zero),
366/// where the PJRT CPU plugin's XLA gives NaN instead of `-inf` (JAX's XLA
367/// gives `-inf`).
368fn digamma() -> OpInfo {
369    OpInfo::new(p::DIGAMMA, &FLOATS, |rng, d| {
370        let edges = [
371            f64::NAN,
372            f64::NEG_INFINITY,
373            f64::INFINITY,
374            -1.0,
375            -2.5,
376            1e-4,
377            0.5,
378            1.5,
379            30.0,
380            3.0e38,
381        ];
382        special_samples(rng, d, 1, Domain::Any, &edges)
383    })
384}
385
386/// The edge values of `polygamma` and `zeta`: not zero (see [`digamma`]),
387/// and not infinite exponents, for which XLA's results depend on flushing
388/// subnormal numbers to zero.
389const POLYGAMMA_EDGES: [f64; 8] = [f64::NAN, -1.0, -2.5, 0.5, 1.0, 2.0, 3.5, 30.0];
390
391/// `polygamma(n, x)`: natural numbers `n` (and one that is not).
392fn polygamma() -> OpInfo {
393    OpInfo::new(p::POLYGAMMA, &FLOATS, |rng, d| {
394        let mut samples = special_samples(rng, d, 2, Domain::Positive, &POLYGAMMA_EDGES);
395        for (i, shape) in [&[5][..], &[2, 3]].into_iter().enumerate() {
396            let size: usize = shape.iter().product();
397            let n: Vec<Value> = (0..size)
398                .map(|k| Value::Float(((k + i) % 4) as f64))
399                .collect();
400            samples.push(Sample::new(
401                format!("orders {shape:?}"),
402                Params::None,
403                vec![
404                    from_values(&n, shape, d),
405                    rng.array(shape, d, Domain::Positive),
406                ],
407            ));
408        }
409        samples
410    })
411}
412
413/// `zeta(x, q)`: mostly `x > 1`.
414fn zeta() -> OpInfo {
415    OpInfo::new(p::ZETA, &FLOATS, |rng, d| {
416        let mut samples = special_samples(rng, d, 2, Domain::Positive, &POLYGAMMA_EDGES);
417        for shape in [&[5][..], &[2, 3]] {
418            let x = rng.array(shape, d, Domain::Positive);
419            let x = from_values(
420                &(0..x.size())
421                    .map(|i| match x.get(i) {
422                        Value::Float(v) => Value::Float(v + 1.5),
423                        v => v,
424                    })
425                    .collect::<Vec<_>>(),
426                shape,
427                d,
428            );
429            samples.push(Sample::new(
430                format!("x > 1 {shape:?}"),
431                Params::None,
432                vec![x, rng.array(shape, d, Domain::Positive)],
433            ));
434        }
435        samples
436    })
437}
438
439/// `regularized_incomplete_beta(a, b, x)` with `x` in `(0, 1)`, and the
440/// edge values for each operand.
441fn betainc() -> OpInfo {
442    OpInfo::new(p::REGULARIZED_INCOMPLETE_BETA, &FLOATS, |rng, d| {
443        let mut samples: Vec<Sample> = SHAPES
444            .iter()
445            .map(|&shape| {
446                Sample::new(
447                    format!("{shape:?}"),
448                    Params::None,
449                    vec![
450                        rng.array(shape, d, Domain::Positive),
451                        rng.array(shape, d, Domain::Positive),
452                        rng.array(shape, d, Domain::Probability),
453                    ],
454                )
455            })
456            .collect();
457        let edge = edge_values(d);
458        let n = edge.size();
459        for k in 0..3 {
460            let mut args: Vec<HostArray> = vec![
461                rng.array([n], d, Domain::Positive),
462                rng.array([n], d, Domain::Positive),
463                rng.array([n], d, Domain::Probability),
464            ];
465            args[k] = edge.clone();
466            samples.push(Sample::new(format!("edge values {k}"), Params::None, args));
467        }
468        samples
469    })
470}
471
472fn round() -> OpInfo {
473    OpInfo::new(p::ROUND, &FLOATS, |rng, d| {
474        [RoundingMethod::AwayFromZero, RoundingMethod::ToNearestEven]
475            .into_iter()
476            .flat_map(|method| {
477                elementwise_samples(rng, d, 1, Domain::Any, &Params::Round { method })
478            })
479            .collect()
480    })
481}
482
483fn integer_pow() -> OpInfo {
484    OpInfo::new(p::INTEGER_POW, &NUMBERS, |rng, d| {
485        let mut ys = vec![0, 1, 2, 3, 5];
486        if d.is_float() {
487            ys.extend([-1, -2]);
488        }
489        ys.into_iter()
490            .flat_map(|y| elementwise_samples(rng, d, 1, Domain::Any, &Params::IntegerPow { y }))
491            .collect()
492    })
493}
494
495fn convert() -> OpInfo {
496    OpInfo::new(p::CONVERT_ELEMENT_TYPE, &DType::ALL, |rng, d| {
497        DType::ALL
498            .into_iter()
499            .flat_map(|to| {
500                let params = Params::Convert { new_dtype: to };
501                [
502                    Sample::new(
503                        format!("to {to}"),
504                        params.clone(),
505                        vec![rng.array([2, 3], d, Domain::Any)],
506                    ),
507                    Sample::new(format!("edge values to {to}"), params, vec![edge_values(d)]),
508                ]
509            })
510            .collect()
511    })
512}
513
514fn bitcast() -> OpInfo {
515    // As in JAX, booleans and complex numbers cannot be reinterpreted.
516    let bits = |d: DType| d != DType::Bool && !d.is_complex();
517    let dtypes: Vec<DType> = DType::ALL.into_iter().filter(|&d| bits(d)).collect();
518    OpInfo::new(p::BITCAST_CONVERT_TYPE, &dtypes, move |_, d| {
519        DType::ALL
520            .into_iter()
521            .filter(|&to| bits(to) && to.size_in_bytes() == d.size_in_bytes())
522            .map(|to| {
523                Sample::new(
524                    format!("to {to}"),
525                    Params::Convert { new_dtype: to },
526                    vec![edge_values(d)],
527                )
528            })
529            .collect()
530    })
531}
532
533fn select_n() -> OpInfo {
534    OpInfo::new(p::SELECT_N, &LAYOUT, |rng, d| {
535        let case = |rng: &mut Rng, shape: &[usize]| rng.array(shape, d, Domain::Any);
536        let which_i32 = from_values(&[-1, 0, 1, 2, 3, 7].map(Value::Int), [2, 3], DType::I32);
537        vec![
538            Sample::new(
539                "bool",
540                Params::None,
541                vec![
542                    rng.array([2, 3], DType::Bool, Domain::Any),
543                    case(rng, &[2, 3]),
544                    case(rng, &[2, 3]),
545                ],
546            ),
547            Sample::new(
548                "scalar bool",
549                Params::None,
550                vec![HostArray::scalar(true), case(rng, &[4]), case(rng, &[4])],
551            ),
552            Sample::new(
553                "scalars",
554                Params::None,
555                vec![HostArray::scalar(false), case(rng, &[]), case(rng, &[])],
556            ),
557            Sample::new(
558                "one case",
559                Params::None,
560                vec![rng.array([3], DType::Bool, Domain::Any), case(rng, &[3])],
561            ),
562            Sample::new(
563                "i32, three cases",
564                Params::None,
565                vec![
566                    which_i32,
567                    case(rng, &[2, 3]),
568                    case(rng, &[2, 3]),
569                    case(rng, &[2, 3]),
570                ],
571            ),
572            Sample::new(
573                "scalar i32",
574                Params::None,
575                vec![
576                    HostArray::scalar(1i32),
577                    case(rng, &[2]),
578                    case(rng, &[2]),
579                    case(rng, &[2]),
580                ],
581            ),
582        ]
583    })
584}
585
586fn clamp() -> OpInfo {
587    OpInfo::new(p::CLAMP, &NUMERIC, |rng, d| {
588        let scalar = |v: f64| from_values(&[Value::Float(v)], Shape::scalar(), d);
589        let edge = edge_values(d);
590        let n = edge.size();
591        vec![
592            Sample::new(
593                "scalar bounds",
594                Params::None,
595                vec![scalar(1.0), rng.array([2, 3], d, Domain::Any), scalar(5.0)],
596            ),
597            Sample::new(
598                "array bounds",
599                Params::None,
600                vec![
601                    rng.array([4], d, Domain::Any),
602                    rng.array([4], d, Domain::Any),
603                    rng.array([4], d, Domain::Any),
604                ],
605            ),
606            {
607                // `lo <= hi`, where JAX's derivative rules hold.
608                let a = rng
609                    .array([4], d, Domain::Any)
610                    .convert(DType::F64)
611                    .to_vec::<f64>()
612                    .expect("f64");
613                let b = rng
614                    .array([4], d, Domain::Any)
615                    .convert(DType::F64)
616                    .to_vec::<f64>()
617                    .expect("f64");
618                let lo: Vec<Value> = a
619                    .iter()
620                    .zip(&b)
621                    .map(|(x, y)| Value::Float(x.min(*y)))
622                    .collect();
623                let hi: Vec<Value> = a
624                    .iter()
625                    .zip(&b)
626                    .map(|(x, y)| Value::Float(x.max(*y)))
627                    .collect();
628                Sample::new(
629                    "ordered array bounds",
630                    Params::None,
631                    vec![
632                        from_values(&lo, Shape::from([4]), d),
633                        rng.array([4], d, Domain::Any),
634                        from_values(&hi, Shape::from([4]), d),
635                    ],
636                )
637            },
638            Sample::new(
639                "edge values",
640                Params::None,
641                vec![scalar(0.0), edge.clone(), scalar(2.0)],
642            ),
643            Sample::new(
644                "edge bounds",
645                Params::None,
646                vec![edge.clone(), rng.array([n], d, Domain::Any), edge],
647            ),
648        ]
649    })
650}
651
652fn structural() -> Vec<OpInfo> {
653    let s = |name: &str, params: Params, args: Vec<HostArray>| Sample::new(name, params, args);
654    vec![
655        OpInfo::new(p::BROADCAST_IN_DIM, &LAYOUT, move |rng, d| {
656            let bcast = |shape: &[usize], dims: &[usize]| Params::BroadcastInDim {
657                shape: Shape::from(shape.to_vec()),
658                broadcast_dimensions: dims.to_vec(),
659            };
660            vec![
661                s(
662                    "rows",
663                    bcast(&[2, 3], &[1]),
664                    vec![rng.array([3], d, Domain::Any)],
665                ),
666                s(
667                    "scalar",
668                    bcast(&[2, 2], &[]),
669                    vec![rng.array([], d, Domain::Any)],
670                ),
671                s(
672                    "size 1",
673                    bcast(&[2, 3, 4], &[0, 2]),
674                    vec![rng.array([2, 1], d, Domain::Any)],
675                ),
676                s(
677                    "empty",
678                    bcast(&[0, 3], &[1]),
679                    vec![rng.array([3], d, Domain::Any)],
680                ),
681            ]
682        }),
683        OpInfo::new(p::RESHAPE, &LAYOUT, move |rng, d| {
684            let reshape = |shape: &[usize]| Params::Reshape {
685                new_sizes: Shape::from(shape.to_vec()),
686            };
687            vec![
688                s(
689                    "2x3 to 3x2",
690                    reshape(&[3, 2]),
691                    vec![rng.array([2, 3], d, Domain::Any)],
692                ),
693                s(
694                    "6 to 1x2x3",
695                    reshape(&[1, 2, 3]),
696                    vec![rng.array([6], d, Domain::Any)],
697                ),
698                s("scalar", reshape(&[1]), vec![rng.array([], d, Domain::Any)]),
699                s(
700                    "empty",
701                    reshape(&[2, 0]),
702                    vec![rng.array([0, 2], d, Domain::Any)],
703                ),
704            ]
705        }),
706        OpInfo::new(p::TRANSPOSE, &LAYOUT, move |rng, d| {
707            let perm = |p: &[usize]| Params::Transpose {
708                permutation: p.to_vec(),
709            };
710            vec![
711                s("2d", perm(&[1, 0]), vec![rng.array([2, 3], d, Domain::Any)]),
712                s(
713                    "3d",
714                    perm(&[2, 0, 1]),
715                    vec![rng.array([2, 3, 4], d, Domain::Any)],
716                ),
717                s("scalar", perm(&[]), vec![rng.array([], d, Domain::Any)]),
718            ]
719        }),
720        OpInfo::new(p::SLICE, &LAYOUT, move |rng, d| {
721            let slice = |start: &[usize], limit: &[usize], strides: &[usize]| Params::Slice {
722                start_indices: start.to_vec(),
723                limit_indices: limit.to_vec(),
724                strides: strides.to_vec(),
725            };
726            vec![
727                s(
728                    "1d",
729                    slice(&[1], &[4], &[1]),
730                    vec![rng.array([5], d, Domain::Any)],
731                ),
732                s(
733                    "strided",
734                    slice(&[1, 0], &[6, 4], &[2, 3]),
735                    vec![rng.array([6, 4], d, Domain::Any)],
736                ),
737                s(
738                    "empty",
739                    slice(&[2], &[2], &[1]),
740                    vec![rng.array([5], d, Domain::Any)],
741                ),
742            ]
743        }),
744        OpInfo::new(p::DYNAMIC_SLICE, &LAYOUT, move |rng, d| {
745            let sizes = |s: &[usize]| Params::DynamicSlice {
746                slice_sizes: s.to_vec(),
747            };
748            let mut samples = Vec::new();
749            for start in [1i32, 4, -2] {
750                samples.push(s(
751                    &format!("start {start}"),
752                    sizes(&[2]),
753                    vec![rng.array([5], d, Domain::Any), HostArray::scalar(start)],
754                ));
755            }
756            samples.push(s(
757                "2d, i64 starts",
758                sizes(&[2, 2]),
759                vec![
760                    rng.array([3, 4], d, Domain::Any),
761                    HostArray::scalar(2i64),
762                    HostArray::scalar(1i64),
763                ],
764            ));
765            samples.push(s(
766                "u32 starts",
767                sizes(&[1, 3]),
768                vec![
769                    rng.array([3, 4], d, Domain::Any),
770                    HostArray::scalar(7u32),
771                    HostArray::scalar(0u32),
772                ],
773            ));
774            samples
775        }),
776        OpInfo::new(p::DYNAMIC_UPDATE_SLICE, &LAYOUT, move |rng, d| {
777            let mut samples = Vec::new();
778            for start in [1i32, 4, -2] {
779                samples.push(s(
780                    &format!("start {start}"),
781                    Params::None,
782                    vec![
783                        rng.array([5], d, Domain::Any),
784                        rng.array([2], d, Domain::Any),
785                        HostArray::scalar(start),
786                    ],
787                ));
788            }
789            samples.push(s(
790                "2d",
791                Params::None,
792                vec![
793                    rng.array([3, 4], d, Domain::Any),
794                    rng.array([2, 2], d, Domain::Any),
795                    HostArray::scalar(2i64),
796                    HostArray::scalar(-1i64),
797                ],
798            ));
799            samples
800        }),
801        OpInfo::new(p::CONCATENATE, &LAYOUT, move |rng, d| {
802            vec![
803                s(
804                    "dim 1",
805                    Params::Concatenate { dimension: 1 },
806                    vec![
807                        rng.array([2, 1], d, Domain::Any),
808                        rng.array([2, 3], d, Domain::Any),
809                        rng.array([2, 0], d, Domain::Any),
810                    ],
811                ),
812                s(
813                    "dim 0",
814                    Params::Concatenate { dimension: 0 },
815                    vec![
816                        rng.array([2], d, Domain::Any),
817                        rng.array([3], d, Domain::Any),
818                    ],
819                ),
820            ]
821        }),
822        OpInfo::new(p::PAD, &LAYOUT, move |rng, d| {
823            let pad = |c: &[(i64, i64, usize)]| Params::Pad {
824                padding_config: c.to_vec(),
825            };
826            vec![
827                s(
828                    "edges",
829                    pad(&[(1, 2, 0)]),
830                    vec![
831                        rng.array([3], d, Domain::Any),
832                        rng.array([], d, Domain::Any),
833                    ],
834                ),
835                s(
836                    "negative and interior",
837                    pad(&[(-1, 1, 1)]),
838                    vec![
839                        rng.array([4], d, Domain::Any),
840                        rng.array([], d, Domain::Any),
841                    ],
842                ),
843                s(
844                    "2d",
845                    pad(&[(0, 1, 1), (2, -1, 0)]),
846                    vec![
847                        rng.array([2, 3], d, Domain::Any),
848                        rng.array([], d, Domain::Any),
849                    ],
850                ),
851            ]
852        }),
853        OpInfo::new(p::REV, &LAYOUT, move |rng, d| {
854            let rev = |dims: &[usize]| Params::Rev {
855                dimensions: dims.to_vec(),
856            };
857            vec![
858                s("1d", rev(&[0]), vec![rng.array([5], d, Domain::Any)]),
859                s("2d", rev(&[0, 1]), vec![rng.array([2, 3], d, Domain::Any)]),
860                s(
861                    "one of two",
862                    rev(&[1]),
863                    vec![rng.array([2, 3], d, Domain::Any)],
864                ),
865            ]
866        }),
867        OpInfo::new(p::IOTA, &NUMERIC, move |_, d| {
868            let iota = |shape: &[usize], dimension: usize| Params::Iota {
869                dtype: d,
870                shape: Shape::from(shape.to_vec()),
871                dimension,
872            };
873            vec![
874                s("1d", iota(&[5], 0), vec![]),
875                s("2d", iota(&[2, 3], 1), vec![]),
876                s("empty", iota(&[0, 3], 0), vec![]),
877            ]
878        }),
879    ]
880}
881
882const SORTED: [DType; 8] = [
883    DType::Bool,
884    DType::I8,
885    DType::I32,
886    DType::U32,
887    DType::F16,
888    DType::BF16,
889    DType::F32,
890    DType::F64,
891];
892
893/// Samples of `sort`: one operand, keys with values, two keys, along each
894/// dimension. Samples with equal keys (ties, `-0.0` and `0.0`, NaNs) are
895/// named `edge`: their derivatives are not defined.
896fn sort() -> OpInfo {
897    OpInfo::new(p::SORT, &SORTED, |rng, d| {
898        let s = |dimension: usize, num_keys: usize| Params::Sort {
899            dimension,
900            is_stable: true,
901            num_keys,
902        };
903        let iota = |n: usize| HostArray::from_vec((0..n as i32).collect::<Vec<_>>(), [n]);
904        let mut samples = vec![
905            Sample::new("1-D", s(0, 1), vec![rng.array([7], d, Domain::Any)]),
906            Sample::new(
907                "2-D along 0",
908                s(0, 1),
909                vec![rng.array([3, 4], d, Domain::Any)],
910            ),
911            Sample::new(
912                "2-D along 1",
913                s(1, 1),
914                vec![rng.array([3, 4], d, Domain::Any)],
915            ),
916            Sample::new(
917                "3-D along 1",
918                s(1, 1),
919                vec![rng.array([2, 3, 2], d, Domain::Any)],
920            ),
921            Sample::new("empty", s(1, 1), vec![rng.array([0, 3], d, Domain::Any)]),
922            Sample::new(
923                "unstable",
924                Params::Sort {
925                    dimension: 0,
926                    is_stable: false,
927                    num_keys: 1,
928                },
929                vec![rng.array([6], d, Domain::Any)],
930            ),
931            Sample::new(
932                "key and value",
933                s(0, 1),
934                vec![
935                    rng.array([5], d, Domain::Any),
936                    rng.array([5], DType::F64, Domain::Any),
937                ],
938            ),
939            Sample::new(
940                "key and indices along 1",
941                s(1, 1),
942                vec![
943                    rng.array([2, 4], d, Domain::Any),
944                    rng.array([2, 4], DType::I32, Domain::Any),
945                ],
946            ),
947            Sample::new(
948                "two keys along 0",
949                s(0, 2),
950                vec![
951                    rng.array([4, 2], d, Domain::Any),
952                    rng.array([4, 2], d, Domain::Any),
953                    rng.array([4, 2], d, Domain::Any),
954                ],
955            ),
956            Sample::new(
957                "two keys along 1",
958                s(1, 2),
959                vec![
960                    rng.array([2, 5], d, Domain::Any),
961                    rng.array([2, 5], DType::I32, Domain::Any),
962                ],
963            ),
964        ];
965        // Ties keep their order; the second key breaks them.
966        let ties = from_values(&[1, 0, 1, 0, 1, 0].map(Value::Int), [6], d);
967        samples.push(Sample::new(
968            "edge: ties",
969            s(0, 1),
970            vec![ties.clone(), iota(6)],
971        ));
972        let second = from_values(&[3, 1, 2, 2, 0, 1].map(Value::Int), [6], DType::I32);
973        samples.push(Sample::new(
974            "edge: ties broken by a second key",
975            s(0, 2),
976            vec![ties, second, iota(6)],
977        ));
978        let edge = edge_values(d);
979        let n = edge.size();
980        samples.push(Sample::new("edge values", s(0, 1), vec![edge, iota(n)]));
981        if d.is_float() {
982            let (nan, inf) = (f64::NAN, f64::INFINITY);
983            let v = [
984                1.0, -nan, 0.0, -0.0, -inf, nan, inf, -0.0, 0.0, nan, -1.0, -nan,
985            ];
986            let x = HostArray::from_vec(v.to_vec(), [12]).convert(d);
987            samples.push(Sample::new(
988                "edge: NaN and zeros",
989                s(0, 1),
990                vec![x, iota(12)],
991            ));
992        }
993        samples
994    })
995}
996
997/// Values for products of many elements: near 1 for floats (so that
998/// products neither overflow nor vanish), in `[-1, 1]` for integers.
999fn near_one(rng: &mut Rng, shape: &[usize], d: DType) -> HostArray {
1000    if !d.is_float() {
1001        return rng.array(shape.to_vec(), d, Domain::Unit);
1002    }
1003    let n: usize = shape.iter().product();
1004    let v: Vec<Value> = (0..n)
1005        .map(|_| Value::Float(rng.uniform(0.9, 1.1)))
1006        .collect();
1007    from_values(&v, shape.to_vec(), d)
1008}
1009
1010/// Samples of the cumulative reductions: along each dimension, forward and
1011/// in reverse, empty, and lines longer than the blocks (16) into which XLA
1012/// rewrites long scans on CPU, in one and two levels. Samples with NaN and
1013/// infinities (and ties, whose derivatives are not defined) are named
1014/// `edge`.
1015fn cumulative() -> Vec<OpInfo> {
1016    let info = |prim: Prim, dtypes: &[DType]| {
1017        let prod = prim == p::CUMPROD;
1018        OpInfo::new(prim, dtypes, move |rng, d| {
1019            let c = |axis: usize, reverse: bool| Params::Cumulative { axis, reverse };
1020            let arr = |rng: &mut Rng, shape: &[usize]| {
1021                if prod && shape.iter().product::<usize>() > 16 {
1022                    near_one(rng, shape, d)
1023                } else {
1024                    rng.array(shape.to_vec(), d, Domain::Any)
1025                }
1026            };
1027            let mut samples = vec![
1028                Sample::new("1-D", c(0, false), vec![arr(rng, &[7])]),
1029                Sample::new("1-D reverse", c(0, true), vec![arr(rng, &[7])]),
1030                Sample::new("2-D along 0", c(0, false), vec![arr(rng, &[3, 4])]),
1031                Sample::new("2-D along 1 reverse", c(1, true), vec![arr(rng, &[3, 4])]),
1032                Sample::new("3-D along 1", c(1, false), vec![arr(rng, &[2, 3, 2])]),
1033                Sample::new("empty axis", c(1, false), vec![arr(rng, &[2, 0])]),
1034                Sample::new("empty", c(1, true), vec![arr(rng, &[0, 3])]),
1035                Sample::new("blocks", c(0, false), vec![arr(rng, &[40])]),
1036                Sample::new("blocks reverse", c(0, true), vec![arr(rng, &[37])]),
1037                Sample::new(
1038                    "nested blocks along 0 reverse",
1039                    c(0, true),
1040                    vec![arr(rng, &[300, 2])],
1041                ),
1042                Sample::new(
1043                    "nested blocks along 1",
1044                    c(1, false),
1045                    vec![arr(rng, &[2, 300])],
1046                ),
1047            ];
1048            if d.is_float() {
1049                let (nan, inf) = (f64::NAN, f64::INFINITY);
1050                let v = [1.0, -0.0, 0.5, nan, 2.0, -1.0, -inf, 3.0, inf, -2.0];
1051                let x = from_values(&v.map(Value::Float), [10], d);
1052                samples.push(Sample::new("edge: NaN", c(0, false), vec![x.clone()]));
1053                samples.push(Sample::new("edge: NaN reverse", c(0, true), vec![x]));
1054                for v in [inf, -inf] {
1055                    let x = from_values(&[1.0, v, -2.0, 0.5, v].map(Value::Float), [5], d);
1056                    samples.push(Sample::new(format!("edge: {v}"), c(0, false), vec![x]));
1057                }
1058                let x = from_values(&[-0.0, 0.0, -0.0, 1.0, 1.0].map(Value::Float), [5], d);
1059                samples.push(Sample::new("edge: zeros and ties", c(0, true), vec![x]));
1060            } else {
1061                samples.push(Sample::new(
1062                    "edge values",
1063                    c(0, false),
1064                    vec![edge_values(d)],
1065                ));
1066                samples.push(Sample::new(
1067                    "edge values reverse",
1068                    c(0, true),
1069                    vec![edge_values(d)],
1070                ));
1071            }
1072            samples
1073        })
1074        // XLA computes exponentials and logarithms with its own
1075        // approximations, and 16-bit floats in `f32`.
1076        .xla_tolerance(4e-3, 1e-5)
1077    };
1078    vec![
1079        info(p::CUMSUM, &NUMBERS),
1080        info(p::CUMPROD, &NUMBERS),
1081        info(p::CUMMAX, &NUMERIC),
1082        info(p::CUMMIN, &NUMERIC),
1083        info(p::CUMLOGSUMEXP, &FLOATS),
1084    ]
1085}
1086
1087/// Samples of `top_k`: along the last and other dimensions, `k` from 0 to
1088/// the size, empty, ties (which keep their order), and floats with NaNs of
1089/// both signs and zeros of both signs (ordered by their bits).
1090/// Samples of `fft`: complex transforms of complex operands, real
1091/// transforms of `f32` and `f64`, and inverse real transforms of complex
1092/// operands, of one to three axes, of lengths that are powers of two and
1093/// not, including an empty batch.
1094fn fft() -> OpInfo {
1095    OpInfo::new(
1096        p::FFT,
1097        &[DType::F32, DType::F64, DType::C64, DType::C128],
1098        |rng, d| {
1099            let p = |fft_type: FftType, fft_lengths: &[usize]| Params::Fft {
1100                fft_type,
1101                fft_lengths: fft_lengths.to_vec(),
1102            };
1103            // (operand shape, lengths) of the forward transforms.
1104            let forward: [(&[usize], &[usize]); 7] = [
1105                (&[8], &[8]),
1106                (&[7], &[7]),
1107                (&[1], &[1]),
1108                (&[3, 5], &[5]),
1109                (&[2, 4, 6], &[4, 6]),
1110                (&[2, 3, 4, 5], &[3, 4, 5]),
1111                (&[0, 4], &[4]),
1112            ];
1113            // (operand shape, lengths) of the inverse real transforms.
1114            let inverse_real: [(&[usize], &[usize]); 5] = [
1115                (&[5], &[8]),
1116                (&[3, 4], &[6]),
1117                (&[4], &[7]),
1118                (&[2, 3, 4], &[3, 6]),
1119                (&[2, 3, 2, 3], &[3, 2, 5]),
1120            ];
1121            let mut samples = Vec::new();
1122            let types: &[FftType] = if d.is_complex() {
1123                &[FftType::Fft, FftType::Ifft]
1124            } else {
1125                &[FftType::Rfft]
1126            };
1127            for &t in types {
1128                for (shape, lengths) in forward {
1129                    samples.push(Sample::new(
1130                        format!("{} {lengths:?}", t.name()),
1131                        p(t, lengths),
1132                        vec![rng.array(shape, d, Domain::Any)],
1133                    ));
1134                }
1135            }
1136            if d.is_complex() {
1137                for (shape, lengths) in inverse_real {
1138                    samples.push(Sample::new(
1139                        format!("IRFFT {lengths:?}"),
1140                        p(FftType::Irfft, lengths),
1141                        vec![rng.array(shape, d, Domain::Any)],
1142                    ));
1143                }
1144            }
1145            samples
1146        },
1147    )
1148    // XLA computes `complex64` transforms in `f32`, and ruxla in `f64`.
1149    .xla_tolerance(1e-4, 1e-4)
1150}
1151
1152fn top_k() -> OpInfo {
1153    OpInfo::new(p::TOP_K, &SORTED, |rng, d| {
1154        let t = |k: usize, axis: usize| Params::TopK {
1155            k,
1156            axis,
1157            is_stable: true,
1158        };
1159        let mut samples = vec![
1160            Sample::new("1-D", t(3, 0), vec![rng.array([7], d, Domain::Any)]),
1161            Sample::new("k = 1", t(1, 0), vec![rng.array([5], d, Domain::Any)]),
1162            Sample::new("k = size", t(6, 0), vec![rng.array([6], d, Domain::Any)]),
1163            Sample::new("k = 0", t(0, 0), vec![rng.array([4], d, Domain::Any)]),
1164            Sample::new("2-D", t(2, 1), vec![rng.array([3, 5], d, Domain::Any)]),
1165            Sample::new("along 0", t(2, 0), vec![rng.array([5, 3], d, Domain::Any)]),
1166            Sample::new(
1167                "3-D along 1",
1168                t(3, 1),
1169                vec![rng.array([2, 4, 3], d, Domain::Any)],
1170            ),
1171            Sample::new("empty", t(2, 1), vec![rng.array([0, 4], d, Domain::Any)]),
1172        ];
1173        if matches!(d, DType::F32 | DType::F64) {
1174            // Distinct values, whose order does not depend on stability.
1175            samples.push(Sample::new(
1176                "unstable",
1177                Params::TopK {
1178                    k: 4,
1179                    axis: 0,
1180                    is_stable: false,
1181                },
1182                vec![rng.array([6], d, Domain::Any)],
1183            ));
1184        }
1185        let ties = from_values(&[1, 0, 1, 0, 1, 0].map(Value::Int), [6], d);
1186        samples.push(Sample::new("edge: ties", t(4, 0), vec![ties]));
1187        let edge = edge_values(d);
1188        let n = edge.size();
1189        samples.push(Sample::new("edge values", t(n, 0), vec![edge]));
1190        if d.is_float() {
1191            let (nan, inf) = (f64::NAN, f64::INFINITY);
1192            let v = [
1193                1.0, -nan, 0.0, -0.0, -inf, nan, inf, -0.0, 0.0, nan, -1.0, -nan,
1194            ];
1195            let x = from_values(&v.map(Value::Float), [12], d);
1196            samples.push(Sample::new(
1197                "edge: NaN and zeros",
1198                t(12, 0),
1199                vec![x.clone()],
1200            ));
1201            samples.push(Sample::new("edge: NaN and zeros, k = 5", t(5, 0), vec![x]));
1202        }
1203        samples
1204    })
1205}
1206
1207fn reductions() -> Vec<OpInfo> {
1208    let reduce = |prim: Prim, dtypes: &[DType]| {
1209        OpInfo::new(prim, dtypes, |rng, d| {
1210            let r = |axes: &[usize]| Params::Reduce {
1211                axes: axes.to_vec(),
1212            };
1213            let mut samples = vec![
1214                Sample::new("axis 0", r(&[0]), vec![rng.array([2, 3], d, Domain::Any)]),
1215                Sample::new("axis 1", r(&[1]), vec![rng.array([2, 3], d, Domain::Any)]),
1216                Sample::new("all", r(&[0, 1]), vec![rng.array([2, 3], d, Domain::Any)]),
1217                Sample::new("none", r(&[]), vec![rng.array([], d, Domain::Any)]),
1218                Sample::new("empty", r(&[0]), vec![rng.array([0, 2], d, Domain::Any)]),
1219            ];
1220            if d.is_float() {
1221                // Each NaN or infinity separately, among ordinary values.
1222                for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
1223                    let x = from_values(&[1.0, v, -2.0, 0.5].map(Value::Float), [2, 2], d);
1224                    samples.push(Sample::new(format!("with {v}"), r(&[1]), vec![x]));
1225                }
1226            } else {
1227                samples.push(Sample::new("edge values", r(&[0]), vec![edge_values(d)]));
1228            }
1229            samples
1230        })
1231        // Sums are accumulated in a different order.
1232        .xla_tolerance(2e-3, 1e-5)
1233    };
1234    let arg = |prim: Prim| {
1235        OpInfo::new(prim, &ORDERED_NUMBERS, |rng, d| {
1236            let a = |axis: usize, index_dtype: DType| Params::ArgMinMax { axis, index_dtype };
1237            let mut samples = vec![
1238                Sample::new(
1239                    "axis 0",
1240                    a(0, DType::I32),
1241                    vec![rng.array([2, 3], d, Domain::Any)],
1242                ),
1243                Sample::new(
1244                    "axis 1",
1245                    a(1, DType::I64),
1246                    vec![rng.array([2, 3], d, Domain::Any)],
1247                ),
1248                Sample::new(
1249                    "ties",
1250                    a(0, DType::I32),
1251                    vec![from_values(&[1, 3, 3, 1].map(Value::Int), [4], d)],
1252                ),
1253                Sample::new("edge values", a(0, DType::I32), vec![edge_values(d)]),
1254            ];
1255            if d.is_float() {
1256                let x = from_values(&[1.0, f64::NAN, 5.0, f64::NAN].map(Value::Float), [4], d);
1257                samples.push(Sample::new("NaN", a(0, DType::I32), vec![x]));
1258            }
1259            samples
1260        })
1261    };
1262    let sums: Vec<DType> = NUMBERS.to_vec();
1263    vec![
1264        reduce(p::REDUCE_SUM, &sums),
1265        reduce(p::REDUCE_MAX, &ORDERED),
1266        reduce(p::REDUCE_MIN, &ORDERED),
1267        arg(p::ARGMAX),
1268        arg(p::ARGMIN),
1269    ]
1270}
1271
1272fn dot_general() -> OpInfo {
1273    OpInfo::new(p::DOT_GENERAL, &NUMBERS, |rng, d| {
1274        let dot = |lc: &[usize], rc: &[usize], lb: &[usize], rb: &[usize], pref: Option<DType>| {
1275            Params::DotGeneral {
1276                dimension_numbers: DotDims {
1277                    lhs_contracting: lc.to_vec(),
1278                    rhs_contracting: rc.to_vec(),
1279                    lhs_batch: lb.to_vec(),
1280                    rhs_batch: rb.to_vec(),
1281                },
1282                precision: Precision::Highest,
1283                preferred_element_type: pref,
1284            }
1285        };
1286        let a = |rng: &mut Rng, shape: &[usize]| rng.array(shape, d, Domain::Any);
1287        let mut samples = vec![
1288            Sample::new(
1289                "matmul",
1290                dot(&[1], &[0], &[], &[], None),
1291                vec![a(rng, &[2, 3]), a(rng, &[3, 4])],
1292            ),
1293            Sample::new(
1294                "batched",
1295                dot(&[2], &[1], &[0], &[0], None),
1296                vec![a(rng, &[2, 2, 3]), a(rng, &[2, 3, 2])],
1297            ),
1298            Sample::new(
1299                "vectors",
1300                dot(&[0], &[0], &[], &[], None),
1301                vec![a(rng, &[3]), a(rng, &[3])],
1302            ),
1303            Sample::new(
1304                "outer",
1305                dot(&[], &[], &[], &[], None),
1306                vec![a(rng, &[2]), a(rng, &[3])],
1307            ),
1308            Sample::new(
1309                "empty",
1310                dot(&[1], &[0], &[], &[], None),
1311                vec![a(rng, &[2, 0]), a(rng, &[0, 3])],
1312            ),
1313        ];
1314        let wider = match d {
1315            DType::I8 | DType::U8 => Some(DType::I32),
1316            DType::F16 | DType::BF16 => Some(DType::F32),
1317            _ => None,
1318        };
1319        if let Some(to) = wider {
1320            samples.push(Sample::new(
1321                format!("as {to}"),
1322                dot(&[1], &[0], &[], &[], Some(to)),
1323                vec![a(rng, &[2, 3]), a(rng, &[3, 4])],
1324            ));
1325        }
1326        samples
1327    })
1328    // Products are accumulated in a different order.
1329    .xla_tolerance(2e-3, 1e-5)
1330}
1331
1332/// The element types of convolutions.
1333const CONV: [DType; 6] = [
1334    DType::I8,
1335    DType::I32,
1336    DType::F16,
1337    DType::BF16,
1338    DType::F32,
1339    DType::F64,
1340];
1341
1342fn conv_general_dilated() -> OpInfo {
1343    OpInfo::new(p::CONV_GENERAL_DILATED, &CONV, |rng, d| {
1344        /// The window, layout, and groups of a sample.
1345        struct C<'a> {
1346            strides: &'a [usize],
1347            padding: &'a [(i64, i64)],
1348            lhs_dilation: &'a [usize],
1349            rhs_dilation: &'a [usize],
1350            dims: ConvDims,
1351            groups: (usize, usize),
1352            preferred: Option<DType>,
1353        }
1354        let conv = |c: C<'_>| Params::ConvGeneralDilated {
1355            window_strides: c.strides.to_vec(),
1356            padding: c.padding.to_vec(),
1357            lhs_dilation: c.lhs_dilation.to_vec(),
1358            rhs_dilation: c.rhs_dilation.to_vec(),
1359            dimension_numbers: c.dims,
1360            feature_group_count: c.groups.0,
1361            batch_group_count: c.groups.1,
1362            precision: Precision::Highest,
1363            preferred_element_type: c.preferred,
1364        };
1365        let simple = |strides: &'static [usize], padding: &'static [(i64, i64)]| C {
1366            strides,
1367            padding,
1368            lhs_dilation: &[1, 1][..strides.len()],
1369            rhs_dilation: &[1, 1][..strides.len()],
1370            dims: ConvDims::canonical(strides.len() + 2),
1371            groups: (1, 1),
1372            preferred: None,
1373        };
1374        // NHWC, HWIO, NHWC (as Flax lays them out).
1375        let nhwc = ConvDims {
1376            lhs_spec: vec![0, 3, 1, 2],
1377            rhs_spec: vec![3, 2, 0, 1],
1378            out_spec: vec![0, 3, 1, 2],
1379        };
1380        let a = |rng: &mut Rng, shape: &[usize]| rng.array(shape, d, Domain::Any);
1381        let mut samples = vec![
1382            Sample::new(
1383                "1-D",
1384                conv(simple(&[1], &[(0, 0)])),
1385                vec![a(rng, &[2, 3, 5]), a(rng, &[4, 3, 2])],
1386            ),
1387            Sample::new(
1388                "1-D strides and padding",
1389                conv(simple(&[2], &[(1, 2)])),
1390                vec![a(rng, &[2, 3, 5]), a(rng, &[4, 3, 3])],
1391            ),
1392            Sample::new(
1393                "2-D NCHW",
1394                conv(simple(&[2, 1], &[(1, 1), (0, 1)])),
1395                vec![a(rng, &[2, 3, 5, 4]), a(rng, &[4, 3, 3, 2])],
1396            ),
1397            Sample::new(
1398                "2-D NHWC same",
1399                conv(C {
1400                    dims: nhwc.clone(),
1401                    ..simple(&[1, 1], &[(1, 1), (0, 1)])
1402                }),
1403                vec![a(rng, &[2, 4, 3, 3]), a(rng, &[3, 2, 3, 2])],
1404            ),
1405            Sample::new(
1406                "dilations and negative padding",
1407                conv(C {
1408                    lhs_dilation: &[2, 1],
1409                    rhs_dilation: &[1, 2],
1410                    ..simple(&[1, 2], &[(1, -1), (2, 0)])
1411                }),
1412                vec![a(rng, &[1, 2, 4, 5]), a(rng, &[3, 2, 2, 2])],
1413            ),
1414            Sample::new(
1415                "feature groups",
1416                conv(C {
1417                    groups: (2, 1),
1418                    ..simple(&[1, 1], &[(0, 0), (1, 0)])
1419                }),
1420                vec![a(rng, &[2, 4, 3, 3]), a(rng, &[6, 2, 2, 2])],
1421            ),
1422            Sample::new(
1423                "depthwise NHWC",
1424                conv(C {
1425                    dims: nhwc.clone(),
1426                    groups: (3, 1),
1427                    ..simple(&[2, 1], &[(1, 1), (1, 1)])
1428                }),
1429                vec![a(rng, &[1, 4, 4, 3]), a(rng, &[3, 3, 1, 6])],
1430            ),
1431            Sample::new(
1432                "batch groups",
1433                conv(C {
1434                    groups: (1, 2),
1435                    ..simple(&[1], &[(1, 0)])
1436                }),
1437                vec![a(rng, &[4, 2, 4]), a(rng, &[6, 2, 2])],
1438            ),
1439            Sample::new(
1440                "no spatial dimensions",
1441                conv(simple(&[], &[])),
1442                vec![a(rng, &[2, 3]), a(rng, &[4, 3])],
1443            ),
1444            Sample::new(
1445                "empty",
1446                conv(simple(&[1], &[(0, 0)])),
1447                vec![a(rng, &[2, 3, 2]), a(rng, &[4, 3, 3])],
1448            ),
1449        ];
1450        let wider = match d {
1451            DType::I8 => Some(DType::I32),
1452            DType::F16 | DType::BF16 => Some(DType::F32),
1453            _ => None,
1454        };
1455        if let Some(to) = wider {
1456            samples.push(Sample::new(
1457                format!("as {to}"),
1458                conv(C {
1459                    preferred: Some(to),
1460                    ..simple(&[1], &[(1, 1)])
1461                }),
1462                vec![a(rng, &[2, 3, 5]), a(rng, &[4, 3, 2])],
1463            ));
1464        }
1465        if d.is_float() {
1466            // NaN and infinities in the input (an infinite kernel would
1467            // multiply padding, which XLA's CPU backend computes as `0 * w`
1468            // in some cases and skips in others).
1469            let x = from_values(
1470                &[1.0, f64::NAN, -2.0, f64::INFINITY, 0.5, f64::NEG_INFINITY].map(Value::Float),
1471                [1, 1, 6],
1472                d,
1473            );
1474            samples.push(Sample::new(
1475                "edge values",
1476                conv(simple(&[1], &[(1, 1)])),
1477                vec![x, a(rng, &[2, 1, 2])],
1478            ));
1479        }
1480        samples
1481    })
1482    // Products are accumulated in a different order.
1483    .xla_tolerance(2e-3, 1e-5)
1484}
1485
1486/// The parameters of a windowed reduction.
1487fn window(
1488    dimensions: &[usize],
1489    strides: &[usize],
1490    padding: &[(i64, i64)],
1491    base_dilation: &[usize],
1492    window_dilation: &[usize],
1493) -> Params {
1494    Params::ReduceWindow {
1495        window_dimensions: dimensions.to_vec(),
1496        window_strides: strides.to_vec(),
1497        padding: padding.to_vec(),
1498        base_dilation: base_dilation.to_vec(),
1499        window_dilation: window_dilation.to_vec(),
1500    }
1501}
1502
1503/// Each NaN or infinity among ordinary values (`[2, 3]`), or the edge
1504/// values of an integer type.
1505fn window_edge_values(d: DType) -> HostArray {
1506    if d.is_float() {
1507        from_values(
1508            &[1.0, f64::NAN, -2.0, f64::INFINITY, 0.5, f64::NEG_INFINITY].map(Value::Float),
1509            [2, 3],
1510            d,
1511        )
1512    } else {
1513        let e = edge_values(d);
1514        let n = e.size();
1515        e.reshape([1, n])
1516    }
1517}
1518
1519fn windows() -> Vec<OpInfo> {
1520    let reduce = |prim: Prim, dtypes: &[DType]| {
1521        OpInfo::new(prim, dtypes, |rng, d| {
1522            let a = |rng: &mut Rng, shape: &[usize]| rng.array(shape, d, Domain::Any);
1523            let edge = window_edge_values(d);
1524            let edge_len = edge.shape()[1];
1525            vec![
1526                Sample::new(
1527                    "1-D",
1528                    window(&[2], &[1], &[(0, 0)], &[1], &[1]),
1529                    vec![a(rng, &[6])],
1530                ),
1531                Sample::new(
1532                    "2-D strides and padding",
1533                    window(&[2, 2], &[1, 2], &[(0, 1), (0, 0)], &[1, 1], &[1, 1]),
1534                    vec![a(rng, &[4, 6])],
1535                ),
1536                Sample::new(
1537                    "pooling NHWC",
1538                    window(
1539                        &[1, 2, 2, 1],
1540                        &[1, 2, 2, 1],
1541                        &[(0, 0), (0, 1), (1, 0), (0, 0)],
1542                        &[1; 4],
1543                        &[1; 4],
1544                    ),
1545                    vec![a(rng, &[2, 4, 3, 2])],
1546                ),
1547                Sample::new(
1548                    "base dilation",
1549                    window(&[2, 3], &[1, 2], &[(1, 0), (0, 1)], &[2, 1], &[1, 1]),
1550                    vec![a(rng, &[3, 5])],
1551                ),
1552                Sample::new(
1553                    "window dilation",
1554                    window(&[2, 2], &[1, 1], &[(0, 0), (1, 1)], &[1, 2], &[2, 1]),
1555                    vec![a(rng, &[4, 4])],
1556                ),
1557                Sample::new("scalar", window(&[], &[], &[], &[], &[]), vec![a(rng, &[])]),
1558                Sample::new(
1559                    "empty",
1560                    window(&[1, 2], &[1, 1], &[(0, 0), (0, 0)], &[1, 1], &[1, 1]),
1561                    vec![a(rng, &[0, 3])],
1562                ),
1563                Sample::new(
1564                    "edge values",
1565                    window(&[1, 2], &[1, 1], &[(0, 0), (1, 0)], &[1, 1], &[1, 1]),
1566                    vec![edge],
1567                ),
1568                Sample::new(
1569                    "edge values, window over all",
1570                    window(&[2, edge_len], &[1, 1], &[(0, 0), (0, 0)], &[1, 1], &[1, 1]),
1571                    vec![window_edge_values(d)],
1572                ),
1573            ]
1574        })
1575        // Sums are accumulated in a different order.
1576        .xla_tolerance(2e-3, 1e-5)
1577    };
1578    let scatter = OpInfo::new(
1579        p::SELECT_AND_SCATTER_ADD,
1580        &[DType::I32, DType::F16, DType::F32, DType::F64],
1581        |rng, d| {
1582            let a = |rng: &mut Rng, shape: &[usize]| rng.array(shape, d, Domain::Any);
1583            let s = |select_prim, dims: &[usize], strides: &[usize], padding: &[(i64, i64)]| {
1584                Params::SelectAndScatterAdd {
1585                    select_prim,
1586                    window_dimensions: dims.to_vec(),
1587                    window_strides: strides.to_vec(),
1588                    padding: padding.to_vec(),
1589                }
1590            };
1591            let edge = window_edge_values(d);
1592            let (rows, cols) = (edge.shape()[0], edge.shape()[1]);
1593            vec![
1594                Sample::new(
1595                    "1-D",
1596                    s(SelectPrim::Ge, &[2], &[2], &[(0, 0)]),
1597                    vec![a(rng, &[3]), a(rng, &[6])],
1598                ),
1599                Sample::new(
1600                    "2-D padded",
1601                    s(SelectPrim::Ge, &[2, 2], &[1, 2], &[(0, 1), (0, 0)]),
1602                    vec![a(rng, &[4, 3]), a(rng, &[4, 6])],
1603                ),
1604                Sample::new(
1605                    "overlapping minima",
1606                    s(SelectPrim::Le, &[3], &[1], &[(1, 1)]),
1607                    vec![a(rng, &[5]), a(rng, &[5])],
1608                ),
1609                Sample::new(
1610                    "edge values",
1611                    s(SelectPrim::Ge, &[1, 2], &[1, 1], &[(0, 0), (1, 1)]),
1612                    vec![a(rng, &[rows, cols + 1]), edge],
1613                ),
1614            ]
1615        },
1616    );
1617    let gather = OpInfo::new(p::SELECT_AND_GATHER_ADD, &FLOATS, |rng, d| {
1618        let a = |rng: &mut Rng, shape: &[usize]| rng.array(shape, d, Domain::Any);
1619        let g = |select_prim, w: Params| {
1620            let Params::ReduceWindow {
1621                window_dimensions,
1622                window_strides,
1623                padding,
1624                base_dilation,
1625                window_dilation,
1626            } = w
1627            else {
1628                unreachable!()
1629            };
1630            Params::SelectAndGatherAdd {
1631                select_prim,
1632                window_dimensions,
1633                window_strides,
1634                padding,
1635                base_dilation,
1636                window_dilation,
1637            }
1638        };
1639        vec![
1640            Sample::new(
1641                "1-D",
1642                g(SelectPrim::Ge, window(&[2], &[1], &[(0, 0)], &[1], &[1])),
1643                vec![a(rng, &[6]), a(rng, &[6])],
1644            ),
1645            Sample::new(
1646                "2-D padded minima",
1647                g(
1648                    SelectPrim::Le,
1649                    window(&[2, 2], &[1, 2], &[(0, 1), (0, 0)], &[1, 1], &[1, 1]),
1650                ),
1651                vec![a(rng, &[4, 6]), a(rng, &[4, 6])],
1652            ),
1653            Sample::new(
1654                "base dilation",
1655                g(
1656                    SelectPrim::Ge,
1657                    window(&[2, 3], &[1, 2], &[(1, 0), (0, 1)], &[2, 1], &[1, 1]),
1658                ),
1659                vec![a(rng, &[3, 5]), a(rng, &[3, 5])],
1660            ),
1661            Sample::new(
1662                "window dilation",
1663                g(
1664                    SelectPrim::Ge,
1665                    window(&[2, 2], &[1, 1], &[(0, 0), (1, 1)], &[1, 1], &[2, 1]),
1666                ),
1667                vec![a(rng, &[4, 4]), a(rng, &[4, 4])],
1668            ),
1669            Sample::new(
1670                "edge values",
1671                g(
1672                    SelectPrim::Ge,
1673                    window(&[1, 2], &[1, 1], &[(0, 0), (1, 0)], &[1, 1], &[1, 1]),
1674                ),
1675                vec![a(rng, &[2, 3]), window_edge_values(d)],
1676            ),
1677        ]
1678    });
1679    vec![
1680        reduce(p::REDUCE_WINDOW_SUM, &NUMBERS),
1681        reduce(p::REDUCE_WINDOW_MAX, &ORDERED_NUMBERS),
1682        reduce(p::REDUCE_WINDOW_MIN, &ORDERED_NUMBERS),
1683        scatter,
1684        gather,
1685    ]
1686}
1687
1688fn gather() -> OpInfo {
1689    OpInfo::new(p::GATHER, &LAYOUT, |rng, d| {
1690        let rows = GatherDims {
1691            offset_dims: vec![1],
1692            collapsed_slice_dims: vec![0],
1693            start_index_map: vec![0],
1694            ..GatherDims::default()
1695        };
1696        let batched = GatherDims {
1697            collapsed_slice_dims: vec![1],
1698            start_index_map: vec![1],
1699            operand_batching_dims: vec![0],
1700            start_indices_batching_dims: vec![0],
1701            ..GatherDims::default()
1702        };
1703        let params = |dims: &GatherDims, sizes: &[usize], mode| Params::Gather {
1704            dimension_numbers: dims.clone(),
1705            slice_sizes: sizes.to_vec(),
1706            mode,
1707            indices_are_sorted: false,
1708            unique_indices: false,
1709        };
1710        let idx = |v: &[i64], shape: &[usize], t: DType| {
1711            from_values(
1712                &v.iter().map(|&i| Value::Int(i)).collect::<Vec<_>>(),
1713                shape.to_vec(),
1714                t,
1715            )
1716        };
1717        let mut samples = Vec::new();
1718        for mode in [GatherScatterMode::Clip, GatherScatterMode::PromiseInBounds] {
1719            samples.push(Sample::new(
1720                format!("rows {mode:?}"),
1721                params(&rows, &[1, 3], mode),
1722                vec![
1723                    rng.array([5, 3], d, Domain::Any),
1724                    idx(&[0, 4, -1, 7], &[4, 1], DType::I32),
1725                ],
1726            ));
1727        }
1728        samples.push(Sample::new(
1729            "batched",
1730            params(&batched, &[1, 1], GatherScatterMode::Clip),
1731            vec![
1732                rng.array([2, 5], d, Domain::Any),
1733                idx(&[3, 9], &[2, 1], DType::U8),
1734            ],
1735        ));
1736        samples.push(Sample::new(
1737            "window",
1738            params(&rows, &[1, 2], GatherScatterMode::Clip),
1739            vec![
1740                rng.array([5, 3], d, Domain::Any),
1741                idx(&[1, 2], &[2, 1], DType::I64),
1742            ],
1743        ));
1744        samples.push(Sample::new(
1745            "empty",
1746            params(&rows, &[1, 3], GatherScatterMode::Clip),
1747            vec![
1748                rng.array([5, 3], d, Domain::Any),
1749                idx(&[], &[0, 1], DType::I32),
1750            ],
1751        ));
1752        samples
1753    })
1754}
1755
1756fn scatters() -> Vec<OpInfo> {
1757    let info = |prim: Prim, dtypes: &[DType], replace: bool| {
1758        OpInfo::new(prim, dtypes, move |rng, d| {
1759            let dims = ScatterDims {
1760                update_window_dims: vec![1],
1761                inserted_window_dims: vec![0],
1762                scatter_dims_to_operand_dims: vec![0],
1763                ..ScatterDims::default()
1764            };
1765            let params = |mode| Params::Scatter {
1766                dimension_numbers: dims.clone(),
1767                mode,
1768                indices_are_sorted: false,
1769                unique_indices: false,
1770            };
1771            let idx = |v: &[i64]| {
1772                from_values(
1773                    &v.iter().map(|&i| Value::Int(i)).collect::<Vec<_>>(),
1774                    [v.len(), 1],
1775                    DType::I32,
1776                )
1777            };
1778            // Replacing with repeated indices is unspecified, so those
1779            // samples have unique indices (after clamping).
1780            let (drop, clip): (&[i64], &[i64]) = if replace {
1781                (&[0, 2, 3, 7], &[0, 2, 9])
1782            } else {
1783                (&[0, 2, 2, 7], &[4, 0, 9, -3])
1784            };
1785            vec![
1786                Sample::new(
1787                    "drop",
1788                    params(GatherScatterMode::FillOrDrop),
1789                    vec![
1790                        rng.array([5, 3], d, Domain::Any),
1791                        idx(drop),
1792                        rng.array([drop.len(), 3], d, Domain::Any),
1793                    ],
1794                ),
1795                Sample::new(
1796                    "clip",
1797                    params(GatherScatterMode::Clip),
1798                    vec![
1799                        rng.array([5, 3], d, Domain::Any),
1800                        idx(clip),
1801                        rng.array([clip.len(), 3], d, Domain::Any),
1802                    ],
1803                ),
1804            ]
1805        })
1806        // Repeated indices combine in a different order.
1807        .xla_tolerance(2e-3, 1e-5)
1808    };
1809    vec![
1810        info(p::SCATTER, &LAYOUT, true),
1811        info(p::SCATTER_ADD, &NUMBERS, false),
1812        info(p::SCATTER_MUL, &NUMBERS, false),
1813        info(p::SCATTER_MIN, &ORDERED_NUMBERS, false),
1814        info(p::SCATTER_MAX, &ORDERED_NUMBERS, false),
1815    ]
1816}
1817
1818/// Builds functions of the IR for the samples of higher-order primitives.
1819pub(crate) struct Builder {
1820    eqns: Vec<Eqn>,
1821}
1822
1823impl Builder {
1824    /// Builds a function from the types of its inputs and a body.
1825    pub(crate) fn function(
1826        in_avals: &[AVal],
1827        body: impl FnOnce(&mut Builder, &[Atom]) -> Vec<Atom>,
1828    ) -> Arc<Function> {
1829        let invars: Vec<Var> = in_avals.iter().cloned().map(Var::new).collect();
1830        let inputs: Vec<Atom> = invars.iter().cloned().map(Atom::Var).collect();
1831        let mut b = Builder { eqns: Vec::new() };
1832        let outvars = body(&mut b, &inputs);
1833        let f = Function {
1834            invars,
1835            eqns: b.eqns,
1836            outvars,
1837            ..Function::default()
1838        };
1839        f.check().expect("a well-typed sample function");
1840        Arc::new(f)
1841    }
1842
1843    /// Applies a primitive.
1844    pub(crate) fn apply(&mut self, prim: Prim, inputs: &[Atom], params: Params) -> Vec<Atom> {
1845        let avals: Vec<AVal> = inputs.iter().map(Atom::aval).collect();
1846        let outputs: Vec<Var> = prim
1847            .abstract_eval(&avals, &params)
1848            .expect("a well-typed sample")
1849            .into_iter()
1850            .map(Var::new)
1851            .collect();
1852        self.eqns.push(Eqn {
1853            prim,
1854            inputs: inputs.to_vec(),
1855            params,
1856            outputs: outputs.clone(),
1857            loc: None,
1858        });
1859        outputs.into_iter().map(Atom::Var).collect()
1860    }
1861
1862    fn rev(&mut self, x: &Atom) -> Atom {
1863        self.apply(
1864            p::REV,
1865            std::slice::from_ref(x),
1866            Params::Rev {
1867                dimensions: vec![0],
1868            },
1869        )
1870        .remove(0)
1871    }
1872}
1873
1874fn lit_i32(v: i32) -> Atom {
1875    Atom::Lit(Literal::new(HostArray::scalar(v)))
1876}
1877
1878fn control() -> Vec<OpInfo> {
1879    vec![
1880        OpInfo::new(p::JIT, &LAYOUT, |rng, d| {
1881            let x = AVal::new([3], d);
1882            let body = Builder::function(&[x.clone(), x], |b, ins| {
1883                let r = b.rev(&ins[0]);
1884                vec![r, ins[1].clone(), ins[0].clone()]
1885            });
1886            vec![Sample::new(
1887                "rev",
1888                Params::Jit {
1889                    name: String::from("f"),
1890                    body,
1891                },
1892                vec![
1893                    rng.array([3], d, Domain::Any),
1894                    rng.array([3], d, Domain::Any),
1895                ],
1896            )]
1897        }),
1898        OpInfo::new(p::COND, &LAYOUT, |rng, d| {
1899            let x = AVal::new([3], d);
1900            let branches = vec![
1901                Builder::function(&[x.clone(), x.clone()], |_, ins| vec![ins[0].clone()]),
1902                Builder::function(&[x.clone(), x.clone()], |b, ins| vec![b.rev(&ins[0])]),
1903                Builder::function(&[x.clone(), x], |_, ins| vec![ins[1].clone()]),
1904            ];
1905            [0, 1, 2, -1, 7]
1906                .into_iter()
1907                .map(|i| {
1908                    Sample::new(
1909                        format!("index {i}"),
1910                        Params::Cond {
1911                            branches: branches.clone(),
1912                        },
1913                        vec![
1914                            HostArray::scalar(i),
1915                            rng.array([3], d, Domain::Any),
1916                            rng.array([3], d, Domain::Any),
1917                        ],
1918                    )
1919                })
1920                .collect()
1921        }),
1922        OpInfo::new(p::WHILE, &LAYOUT, |rng, d| {
1923            let i = AVal::scalar(DType::I32);
1924            let x = AVal::new([3], d);
1925            // while i < limit: i, x = i + 1, (c if i == 1 else rev(x))
1926            let cond = Builder::function(&[i.clone(), i.clone(), x.clone()], |b, ins| {
1927                b.apply(p::LT, &[ins[1].clone(), ins[0].clone()], Params::None)
1928            });
1929            let body = Builder::function(&[x.clone(), i.clone(), x.clone()], |b, ins| {
1930                let (c, i, x) = (&ins[0], &ins[1], &ins[2]);
1931                let next = b
1932                    .apply(p::ADD, &[i.clone(), lit_i32(1)], Params::None)
1933                    .remove(0);
1934                let is_one = b
1935                    .apply(p::EQ, &[i.clone(), lit_i32(1)], Params::None)
1936                    .remove(0);
1937                let r = b.rev(x);
1938                let x = b
1939                    .apply(p::SELECT_N, &[is_one, r, c.clone()], Params::None)
1940                    .remove(0);
1941                vec![next, x]
1942            });
1943            [0, 3]
1944                .into_iter()
1945                .map(|limit| {
1946                    Sample::new(
1947                        format!("limit {limit}"),
1948                        Params::While {
1949                            cond: cond.clone(),
1950                            body: body.clone(),
1951                            cond_nconsts: 1,
1952                            body_nconsts: 1,
1953                        },
1954                        vec![
1955                            HostArray::scalar(limit),
1956                            rng.array([3], d, Domain::Any),
1957                            HostArray::scalar(0i32),
1958                            rng.array([3], d, Domain::Any),
1959                        ],
1960                    )
1961                })
1962                .collect()
1963        }),
1964        OpInfo::new(p::SCAN, &LAYOUT, |rng, d| {
1965            let x = AVal::new([3], d);
1966            // carry' = y; outputs rev(carry) and c.
1967            let body = Builder::function(&[x.clone(), x.clone(), x], |b, ins| {
1968                let (c, carry, y) = (&ins[0], &ins[1], &ins[2]);
1969                vec![y.clone(), b.rev(carry), c.clone()]
1970            });
1971            let mut samples = Vec::new();
1972            for (length, reverse) in [(4, false), (4, true), (0, false)] {
1973                samples.push(Sample::new(
1974                    format!("length {length}{}", if reverse { ", reverse" } else { "" }),
1975                    Params::Scan {
1976                        body: body.clone(),
1977                        length,
1978                        reverse,
1979                        num_consts: 1,
1980                        num_carry: 1,
1981                    },
1982                    vec![
1983                        rng.array([3], d, Domain::Any),
1984                        rng.array([3], d, Domain::Any),
1985                        rng.array([length, 3], d, Domain::Any),
1986                    ],
1987                ));
1988            }
1989            samples
1990        }),
1991    ]
1992}
1993
1994fn un(b: &mut Builder, prim: Prim, x: &Atom) -> Atom {
1995    b.apply(prim, std::slice::from_ref(x), Params::None)
1996        .remove(0)
1997}
1998
1999fn bin(b: &mut Builder, prim: Prim, x: &Atom, y: &Atom) -> Atom {
2000    b.apply(prim, &[x.clone(), y.clone()], Params::None)
2001        .remove(0)
2002}
2003
2004/// Functions with differentiation rules written by the user, and
2005/// `checkpoint`. The rules are the true derivatives, so that the AD check
2006/// (finite differences and the inner-product test) also checks that they
2007/// are used correctly.
2008fn custom() -> Vec<OpInfo> {
2009    vec![
2010        OpInfo::new(p::CUSTOM_JVP_CALL, &FLOATS, |rng, d| {
2011            let x = AVal::new([3], d);
2012            // `sin(x) * y`.
2013            let call = Builder::function(&[x.clone(), x.clone()], |b, ins| {
2014                let s = un(b, p::SIN, &ins[0]);
2015                vec![bin(b, p::MUL, &s, &ins[1])]
2016            });
2017            let jvp = Builder::function(&[x.clone(), x.clone(), x.clone(), x], |b, ins| {
2018                let (x, y, tx, ty) = (&ins[0], &ins[1], &ins[2], &ins[3]);
2019                let s = un(b, p::SIN, x);
2020                let out = bin(b, p::MUL, &s, y);
2021                let cs = un(b, p::COS, x);
2022                let a = bin(b, p::MUL, &cs, y);
2023                let a = bin(b, p::MUL, &a, tx);
2024                let c2 = bin(b, p::MUL, &s, ty);
2025                vec![out, bin(b, p::ADD, &a, &c2)]
2026            });
2027            vec![Sample::new(
2028                "sin(x) * y",
2029                Params::CustomJvp {
2030                    call,
2031                    jvp,
2032                    num_consts: 0,
2033                },
2034                vec![
2035                    rng.array([3], d, Domain::Any),
2036                    rng.array([3], d, Domain::Any),
2037                ],
2038            )]
2039        }),
2040        OpInfo::new(p::CUSTOM_VJP_CALL, &FLOATS, |rng, d| {
2041            let x = AVal::new([3], d);
2042            // `x * y`, with the residuals `x` and `y`.
2043            let call = Builder::function(&[x.clone(), x.clone()], |b, ins| {
2044                vec![bin(b, p::MUL, &ins[0], &ins[1])]
2045            });
2046            let fwd = Builder::function(&[x.clone(), x.clone()], |b, ins| {
2047                vec![
2048                    bin(b, p::MUL, &ins[0], &ins[1]),
2049                    ins[0].clone(),
2050                    ins[1].clone(),
2051                ]
2052            });
2053            let bwd = Builder::function(&[x.clone(), x.clone(), x], |b, ins| {
2054                let (x, y, g) = (&ins[0], &ins[1], &ins[2]);
2055                vec![bin(b, p::MUL, g, y), bin(b, p::MUL, g, x)]
2056            });
2057            vec![Sample::new(
2058                "x * y",
2059                Params::CustomVjp {
2060                    call,
2061                    fwd,
2062                    bwd,
2063                    num_consts: 0,
2064                },
2065                vec![
2066                    rng.array([3], d, Domain::Any),
2067                    rng.array([3], d, Domain::Any),
2068                ],
2069            )]
2070        }),
2071        // `custom_lin` only appears inside linearized functions, which are
2072        // transposed and never evaluated; the reverse mode of
2073        // `custom_vjp_call` checks it.
2074        OpInfo::new(p::CUSTOM_LIN, &[], |_, _| Vec::new()),
2075        OpInfo::new(p::CHECKPOINT, &FLOATS, |rng, d| {
2076            let x = AVal::new([2, 3], d);
2077            let body = Builder::function(&[x.clone(), x], |b, ins| {
2078                let e = un(b, p::TANH, &ins[0]);
2079                let m = bin(b, p::MUL, &e, &ins[1]);
2080                vec![un(b, p::SIN, &m), e]
2081            });
2082            vec![Sample::new(
2083                "sin(tanh(x) * y)",
2084                Params::Checkpoint { body },
2085                vec![
2086                    rng.array([2, 3], d, Domain::Any),
2087                    rng.array([2, 3], d, Domain::Any),
2088                ],
2089            )]
2090        }),
2091    ]
2092}
2093
2094/// `threefry2x32`: keys of rank 0 with arrays of counters (as `jax.random`
2095/// uses it), all operands of the same shape (as after `vmap`), and empty.
2096fn threefry2x32() -> OpInfo {
2097    OpInfo::new(p::THREEFRY2X32, &[DType::U32], |rng, d| {
2098        let a = |rng: &mut Rng, shape: &[usize]| rng.array(shape.to_vec(), d, Domain::Any);
2099        vec![
2100            Sample::new(
2101                "scalar keys",
2102                Params::None,
2103                vec![a(rng, &[]), a(rng, &[]), a(rng, &[5]), a(rng, &[5])],
2104            ),
2105            Sample::new(
2106                "arrays",
2107                Params::None,
2108                vec![
2109                    a(rng, &[2, 3]),
2110                    a(rng, &[2, 3]),
2111                    a(rng, &[2, 3]),
2112                    a(rng, &[2, 3]),
2113                ],
2114            ),
2115            Sample::new(
2116                "all scalars",
2117                Params::None,
2118                vec![a(rng, &[]), a(rng, &[]), a(rng, &[]), a(rng, &[])],
2119            ),
2120            Sample::new(
2121                "empty",
2122                Params::None,
2123                vec![a(rng, &[]), a(rng, &[]), a(rng, &[0]), a(rng, &[0])],
2124            ),
2125        ]
2126    })
2127}