Skip to main content

ruxla_testing/
rng.rs

1//! A small deterministic random number generator for test samples.
2
3use ruxla_ir::{DType, DTypeKind, HostArray, Shape, Value};
4use ruxla_kernels::{BinaryOp, Element, Ops, with_dtype};
5
6/// A deterministic random number generator (SplitMix64).
7///
8/// Test samples must be reproducible, so the generator is seeded explicitly
9/// and does not depend on external crates.
10#[derive(Clone, Debug)]
11pub struct Rng(u64);
12
13/// The range of values to draw.
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub enum Domain {
16    /// Small values of either sign: `[-3, 3]` for floats, `[-10, 10]` for
17    /// integers (`[0, 20]` for unsigned).
18    Any,
19    /// Positive values: `[0.1, 3]` for floats, `[1, 10]` for integers.
20    Positive,
21    /// Nonzero values, for divisors.
22    NonZero,
23    /// Values in `(-1, 1)`, for `erf_inv`.
24    Unit,
25    /// Values in `(0, 1)`: `[0.01, 0.99]` for floats, 0 or 1 for integers.
26    Probability,
27}
28
29impl Rng {
30    /// Creates a generator from a seed.
31    pub fn new(seed: u64) -> Self {
32        Self(seed)
33    }
34
35    /// Returns the next 64 random bits.
36    pub fn next_u64(&mut self) -> u64 {
37        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
38        let mut z = self.0;
39        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
40        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
41        z ^ (z >> 31)
42    }
43
44    /// Returns a uniform float in `[lo, hi)`.
45    pub fn uniform(&mut self, lo: f64, hi: f64) -> f64 {
46        let unit = (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64;
47        lo + (hi - lo) * unit
48    }
49
50    /// Returns a uniform integer in `[lo, hi]`.
51    pub fn int(&mut self, lo: i64, hi: i64) -> i64 {
52        let span = (hi - lo + 1) as u64;
53        lo + (self.next_u64() % span) as i64
54    }
55
56    fn sign(&mut self, x: f64) -> f64 {
57        if self.next_u64().is_multiple_of(2) {
58            x
59        } else {
60            -x
61        }
62    }
63
64    fn value(&mut self, dtype: DType, domain: Domain) -> Value {
65        match dtype.kind() {
66            DTypeKind::Complex => {
67                let Value::Float(re) = self.value(DType::F64, domain) else {
68                    unreachable!("floats")
69                };
70                let im = match domain {
71                    Domain::Unit | Domain::Probability => self.uniform(-0.99, 0.99),
72                    _ => self.uniform(-3.0, 3.0),
73                };
74                Value::Complex(re, im)
75            }
76            DTypeKind::Bool => Value::Bool(self.next_u64().is_multiple_of(2)),
77            DTypeKind::Float => Value::Float(match domain {
78                Domain::Any => self.uniform(-3.0, 3.0),
79                Domain::Positive => self.uniform(0.1, 3.0),
80                Domain::NonZero => {
81                    let x = self.uniform(0.5, 3.0);
82                    self.sign(x)
83                }
84                Domain::Unit => self.uniform(-0.99, 0.99),
85                Domain::Probability => self.uniform(0.01, 0.99),
86            }),
87            DTypeKind::UnsignedInt => Value::UInt(match domain {
88                Domain::Any => self.int(0, 20) as u64,
89                Domain::Positive | Domain::NonZero => self.int(1, 10) as u64,
90                Domain::Unit | Domain::Probability => self.int(0, 1) as u64,
91            }),
92            DTypeKind::SignedInt => Value::Int(match domain {
93                Domain::Any => self.int(-10, 10),
94                Domain::Positive => self.int(1, 10),
95                Domain::NonZero => {
96                    let x = self.int(1, 10) as f64;
97                    self.sign(x) as i64
98                }
99                Domain::Unit => self.int(-1, 1),
100                Domain::Probability => self.int(0, 1),
101            }),
102        }
103    }
104
105    /// Returns a random host array.
106    pub fn array(&mut self, shape: impl Into<Shape>, dtype: DType, domain: Domain) -> HostArray {
107        let shape = shape.into();
108        let values: Vec<Value> = (0..shape.size())
109            .map(|_| self.value(dtype, domain))
110            .collect();
111        from_values(&values, shape, dtype)
112    }
113}
114
115/// Builds an array from values, converted to `dtype` as `Element::from_value`
116/// does.
117pub fn from_values(values: &[Value], shape: impl Into<Shape>, dtype: DType) -> HostArray {
118    with_dtype!(dtype, |T| HostArray::from_vec(
119        values.iter().map(|&v| T::from_value(v)).collect::<Vec<T>>(),
120        shape
121    ))
122}
123
124/// Returns values at the edges of a type: NaN, infinities, signed zeros, and
125/// halfway cases for floats; the extremes, -1, 0, and 1 for integers.
126///
127/// For complex types, pairs of such values for the real and imaginary
128/// parts.
129pub fn edge_values(dtype: DType) -> HostArray {
130    if dtype.is_complex() {
131        let (inf, nan) = (f64::INFINITY, f64::NAN);
132        let pairs = [
133            (0.0, 0.0),
134            (-0.0, 0.0),
135            (0.0, -0.0),
136            (1.0, 0.0),
137            (0.0, 1.0),
138            (-1.0, -1.0),
139            (2.5, -1.5),
140            (-0.5, 0.5),
141            (1e-30, 1e-30),
142            (3.0e38, 3.0e38),
143            (inf, 0.0),
144            (-inf, 1.0),
145            (0.0, inf),
146            (1.0, -inf),
147            (inf, inf),
148            (nan, 0.0),
149            (0.0, nan),
150            (nan, nan),
151        ];
152        let values: Vec<Value> = pairs
153            .iter()
154            .map(|&(re, im)| Value::Complex(re, im))
155            .collect();
156        let n = values.len();
157        return from_values(&values, [n], dtype);
158    }
159    with_dtype!(dtype, |T| {
160        let mut v: Vec<T> = vec![<T as Ops>::lowest(), <T as Ops>::highest()];
161        let small: &[f64] = match dtype.kind() {
162            DTypeKind::Bool => &[0.0, 1.0],
163            DTypeKind::Float => &[
164                f64::NAN,
165                0.0,
166                -0.0,
167                1.0,
168                -1.0,
169                0.5,
170                -0.5,
171                1.5,
172                2.5,
173                -2.5,
174                1e-30,
175                3.0e38,
176                65504.0,
177            ],
178            DTypeKind::SignedInt => &[-1.0, 0.0, 1.0, 2.0, 7.0, 100.0],
179            DTypeKind::UnsignedInt => &[0.0, 1.0, 2.0, 7.0, 100.0],
180            DTypeKind::Complex => unreachable!("handled above"),
181        };
182        v.extend(small.iter().map(|&x| T::from_value(Value::Float(x))));
183        if dtype.kind() == DTypeKind::SignedInt {
184            let one = T::from_value(Value::Int(1));
185            v.push(Ops::binary(BinaryOp::Add, <T as Ops>::lowest(), one));
186        }
187        let n = v.len();
188        HostArray::from_vec(v, [n])
189    })
190}