Skip to main content

ruxla_core/
random.rs

1//! Random numbers following `jax.random`, bit for bit.
2//!
3//! Keys hold two `u32` words, as JAX's default `threefry2x32` keys. The
4//! hash is written generically with the same structure as JAX's lowering
5//! (a loop of five iterations of four rounds, and counters built from a
6//! `u64` iota), so traced programs compile to the same HLO as JAX and
7//! native programs compute the same numbers.
8//!
9//! # Examples
10//!
11//! ```
12//! use ruxla_core::{Native, random};
13//!
14//! let key = random::key::<Native>(0);
15//! let (k1, k2) = random::split2(&key);
16//! let x = random::uniform::<Native, f32>(&k1, [3], 0.0, 1.0);
17//! assert!(x.to_vec().iter().all(|&v| (0.0..1.0).contains(&v)));
18//! let n = random::randint::<Native, i32>(&k2, [], 0, 10).to_scalar();
19//! assert!((0..10).contains(&n.value()));
20//! ```
21
22use ruxla_ir::{DType, GatherDims, GatherScatterMode, Shape};
23use ruxla_kernels::{BinaryOp, Element, cast};
24
25use crate::backend::Backend;
26use crate::jnp;
27use crate::lax;
28use crate::value::{Array, ArrayLike, Float, Int, Scalar, broadcast_binary};
29
30mod distributions;
31
32pub use distributions::{
33    beta, binomial, cauchy, chisquare, choice, choice_with_p, dirichlet, double_sided_maxwell,
34    exponential, f, gamma, laplace, loggamma, logistic, maxwell, pareto, poisson, rademacher, t,
35    truncated_normal, weibull_min,
36};
37
38/// A random key: two `u32` words (or an array of keys, shape `[..., 2]`).
39#[derive(Clone, Debug)]
40pub struct Key<B: Backend> {
41    data: B::KeyData,
42}
43
44/// A key is a pytree with one leaf, its data (`u32[..., 2]`).
45impl<B: Backend> crate::tree::Tree<B> for Key<B> {
46    type On<C: Backend> = Key<C>;
47    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
48        leaves.push(B::array_leaf::<u32>(&B::key_to_array(&self.data)));
49    }
50    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
51        let l = leaves.next().expect("too few leaves for the structure");
52        Key {
53            data: B::key_from_array(B::leaf_array::<u32>(l)),
54        }
55    }
56    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Key<C> {
57        let l = leaves.next().expect("too few leaves for the structure");
58        Key {
59            data: C::key_from_array(C::leaf_array::<u32>(l)),
60        }
61    }
62    fn def(&self) -> crate::tree::TreeDef {
63        crate::tree::TreeDef::Struct {
64            name: String::from("Key"),
65            fields: vec![String::from("data")],
66            children: vec![crate::tree::TreeDef::Leaf],
67        }
68    }
69    fn select(pred: crate::value::Bool<B>, on_true: &Self, on_false: &Self) -> Self {
70        let data = crate::tree::select_tree(pred, &on_true.data(), &on_false.data());
71        Key::from_data(data)
72    }
73}
74
75impl<B: Backend> Key<B> {
76    /// Wraps key data (`u32` of shape `[..., 2]`).
77    ///
78    /// # Panics
79    ///
80    /// Panics if the last dimension is not 2.
81    #[track_caller]
82    pub fn from_data(data: Array<B, u32>) -> Self {
83        assert_eq!(
84            data.shape().last(),
85            Some(&2),
86            "key data must have shape [..., 2]"
87        );
88        Self {
89            data: B::key_from_array(data.0),
90        }
91    }
92
93    /// The key data.
94    pub fn data(&self) -> Array<B, u32> {
95        Array(B::key_to_array(&self.data))
96    }
97
98    /// Key `i` of a one-dimensional array of keys.
99    #[track_caller]
100    pub fn get(&self, i: usize) -> Key<B> {
101        let data = self.data();
102        assert_eq!(data.ndim(), 2, "get needs a one-dimensional array of keys");
103        Key::from_data(lax::index_in_dim(&data, i, 0, false))
104    }
105
106    #[track_caller]
107    #[inline]
108    fn check_single(&self) {
109        assert_eq!(
110            B::key_rank(&self.data),
111            1,
112            "this function needs a single key, not an array of keys"
113        );
114    }
115}
116
117/// A key from a seed, like `jax.random.key`.
118pub fn key<B: Backend>(seed: i64) -> Key<B> {
119    let (hi, lo) = if i32::try_from(seed).is_ok() {
120        (0, seed as u32)
121    } else {
122        ((seed >> 32) as u32, seed as u32)
123    };
124    Key::from_data(Array::from_vec(vec![hi, lo], [2]))
125}
126
127fn u32s<B: Backend>(v: u32) -> Scalar<B, u32> {
128    Scalar::new(v)
129}
130
131fn shl<B: Backend, T: Int>(x: &Array<B, T>, d: &Array<B, T>) -> Array<B, T> {
132    broadcast_binary(BinaryOp::ShiftLeft, x, d)
133}
134
135fn shr<B: Backend, T: Int>(x: &Array<B, T>, d: &Array<B, T>) -> Array<B, T> {
136    broadcast_binary(BinaryOp::ShiftRightLogical, x, d)
137}
138
139fn rotate_left<B: Backend>(x: &Array<B, u32>, d: &Array<B, u32>) -> Array<B, u32> {
140    let back = u32s::<B>(32).to_array() - d;
141    shl(x, d) | shr(x, &back)
142}
143
144fn apply_round<B: Backend>(v: [Array<B, u32>; 2], rotation: &Array<B, u32>) -> [Array<B, u32>; 2] {
145    let v0 = &v[0] + &v[1];
146    let v1 = rotate_left(&v[1], rotation);
147    let v1 = &v0 ^ &v1;
148    [v0, v1]
149}
150
151/// The carry of the threefry loop: the counters, the key schedule, and the
152/// rotations.
153type ThreefryState<B> = ([Array<B, u32>; 2], [Array<B, u32>; 3], [Array<B, u32>; 2]);
154
155/// The threefry2x32 hash with the backend's implementation: `Native` uses
156/// a scalar loop that gives the same bits as [`threefry2x32_generic`].
157fn threefry2x32<B: Backend>(
158    k1: &Array<B, u32>,
159    k2: &Array<B, u32>,
160    x1: &Array<B, u32>,
161    x2: &Array<B, u32>,
162) -> (Array<B, u32>, Array<B, u32>) {
163    let (a, b) = B::threefry2x32(&k1.0, &k2.0, &x1.0, &x2.0);
164    (Array(a), Array(b))
165}
166
167/// The generic hash of the row-major indices of `shape` (`iota_2x32`) with
168/// a key, as JAX computes random bits.
169pub(crate) fn key_bits_generic<B: Backend>(
170    key: &Array<B, u32>,
171    shape: &[usize],
172) -> (Array<B, u32>, Array<B, u32>) {
173    let (k1, k2) = halves(key);
174    let (c1, c2) = iota_2x32::<B>(shape);
175    threefry2x32(&k1, &k2, &c1, &c2)
176}
177
178/// The two words of a key's data.
179fn halves<B: Backend>(data: &Array<B, u32>) -> (Array<B, u32>, Array<B, u32>) {
180    (
181        lax::index_in_dim(data, 0, 0, false),
182        lax::index_in_dim(data, 1, 0, false),
183    )
184}
185
186/// The threefry2x32 hash, as JAX lowers it with rolled loops.
187pub(crate) fn threefry2x32_generic<B: Backend>(
188    k1: &Array<B, u32>,
189    k2: &Array<B, u32>,
190    x1: &Array<B, u32>,
191    x2: &Array<B, u32>,
192) -> (Array<B, u32>, Array<B, u32>) {
193    let rotations: [Array<B, u32>; 2] = [
194        Array::from_vec(vec![13, 15, 26, 6], [4]),
195        Array::from_vec(vec![17, 29, 16, 24], [4]),
196    ];
197    let ks2 = (k1 ^ k2) ^ u32s::<B>(0x1BD1_1BDA);
198    let x = [x1 + k1, x2 + k2];
199    // `rotate_list` in JAX: the first element moves to the end.
200    let init = (x, [k2.clone(), ks2, k1.clone()], rotations);
201    let (x, _, _) = lax::fori_loop(
202        0,
203        5,
204        |i, (x, ks, rotations): ThreefryState<B>| {
205            let mut x = x;
206            for j in 0..4 {
207                x = apply_round(x, &lax::index_in_dim(&rotations[0], j, 0, false));
208            }
209            let step = (i + 1).cast::<u32>();
210            let x = [&x[0] + &ks[0], (&x[1] + &ks[1]) + step];
211            let [ks0, ks1, ks2] = ks;
212            let [r0, r1] = rotations;
213            (x, [ks1, ks2, ks0], [r1, r0])
214        },
215        init,
216    );
217    let [a, b] = x;
218    (a, b)
219}
220
221/// The row-major index of each element of `shape` as `(high, low)` `u32`
222/// words, as JAX's `iota_2x32_shape` lowering computes it.
223fn iota_2x32<B: Backend>(shape: &[usize]) -> (Array<B, u32>, Array<B, u32>) {
224    if shape.is_empty() {
225        let z = jnp::zeros::<B, u32>(Shape::scalar());
226        return (z.clone(), z);
227    }
228    let splat = |v: u64| jnp::full::<B, u64>(shape, v);
229    let counts = (0..shape.len())
230        .map(|d| {
231            let stride = shape[d + 1..].iter().product::<usize>() as u64;
232            lax::mul(&splat(stride), &lax::iota::<B, u64>(shape, d))
233        })
234        .reduce(|a, b| lax::add(&a, &b))
235        .expect("the shape is not empty");
236    let high = lax::shift_right_logical(&counts, &splat(32));
237    (high.cast::<u32>(), counts.cast::<u32>())
238}
239
240/// Splits a key into `num` keys (`jax.random.split`).
241#[track_caller]
242pub fn split<B: Backend>(key: &Key<B>, num: usize) -> Key<B> {
243    key.check_single();
244    Key {
245        data: B::key_split(&key.data, num),
246    }
247}
248
249/// The generic `split`, as JAX computes it.
250pub(crate) fn split_generic<B: Backend>(key: &Array<B, u32>, num: usize) -> Array<B, u32> {
251    let (k1, k2) = halves(key);
252    let (c1, c2) = iota_2x32::<B>(&[num]);
253    let (b1, b2) = threefry2x32(&k1, &k2, &c1, &c2);
254    jnp::stack(&[b1, b2], 1)
255}
256
257/// Splits a key in two.
258#[track_caller]
259#[inline]
260pub fn split2<B: Backend>(key: &Key<B>) -> (Key<B>, Key<B>) {
261    key.check_single();
262    if let Some((a, b)) = B::key_split2(&key.data) {
263        return (Key { data: a }, Key { data: b });
264    }
265    split2_generic(key)
266}
267
268/// [`split2`] through [`split`].
269fn split2_generic<B: Backend>(key: &Key<B>) -> (Key<B>, Key<B>) {
270    let keys = split(key, 2);
271    (keys.get(0), keys.get(1))
272}
273
274/// Folds data into a key (`jax.random.fold_in`).
275#[track_caller]
276pub fn fold_in<B: Backend>(key: &Key<B>, data: impl Into<Scalar<B, u32>>) -> Key<B> {
277    key.check_single();
278    Key {
279        data: B::key_fold_in(&key.data, data.into().0),
280    }
281}
282
283/// The generic `fold_in`, as JAX computes it.
284pub(crate) fn fold_in_generic<B: Backend>(
285    key: &Array<B, u32>,
286    data: Scalar<B, u32>,
287) -> Array<B, u32> {
288    let (k1, k2) = halves(key);
289    let zero = jnp::zeros::<B, u32>([1]);
290    let data = data.to_array().reshape([1]);
291    let (y1, y2) = threefry2x32(&k1, &k2, &zero, &data);
292    lax::concatenate(&[y1, y2], 0)
293}
294
295/// Random bits of `nbits` (8, 16, 32, or 64) in an unsigned type `U` of
296/// that width or wider.
297fn random_bits<B: Backend, U: Int>(key: &Key<B>, nbits: usize, shape: &[usize]) -> Array<B, U> {
298    key.check_single();
299    let (b1, b2) = B::key_bits(&key.data, shape);
300    combine_bits(Array::<B, u32>(b1), Array::<B, u32>(b2), nbits)
301}
302
303/// Uniform random `u32` bits (`jax.random.bits`).
304#[track_caller]
305pub fn bits<B: Backend>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, u32> {
306    random_bits(key, 32, &shape.into())
307}
308
309/// Random bits of `nbits` (8, 16, 32, or 64) in an unsigned type `U` of
310/// that width or wider, for each key of an array of keys (`u32[*batch,
311/// 2]`): shape `[*batch, *shape]`. This is `random_bits` batched as JAX's
312/// `vmap` batches `threefry2x32`: the keys and the counters of one key's
313/// draw are broadcast to the full shape, and hashed together.
314fn random_bits_batched<B: Backend, U: Int>(
315    keys: &Key<B>,
316    nbits: usize,
317    shape: &[usize],
318) -> Array<B, U> {
319    let data = keys.data();
320    let batch = &data.shape()[..data.ndim() - 1];
321    let nb = batch.len();
322    let mut full = batch.to_vec();
323    full.extend_from_slice(shape);
324    let key_dims: Vec<usize> = (0..nb).collect();
325    let count_dims: Vec<usize> = (nb..full.len()).collect();
326    let word = |i: usize| {
327        let w = lax::index_in_dim(&data, i, nb, false);
328        lax::broadcast_in_dim(&w, full.as_slice(), &key_dims)
329    };
330    let (c1, c2) = iota_2x32::<B>(shape);
331    let count = |c: &Array<B, u32>| lax::broadcast_in_dim(c, full.as_slice(), &count_dims);
332    let (b1, b2) = threefry2x32(&word(0), &word(1), &count(&c1), &count(&c2));
333    combine_bits(b1, b2, nbits)
334}
335
336/// Random bits of `nbits` from the two words of the hash, as JAX's
337/// `threefry_random_bits` combines them.
338fn combine_bits<B: Backend, U: Int>(
339    b1: Array<B, u32>,
340    b2: Array<B, u32>,
341    nbits: usize,
342) -> Array<B, U> {
343    match nbits {
344        32 => (&b1 ^ &b2).cast::<U>(),
345        64 => {
346            let hi = b1.cast::<u64>();
347            let lo = b2.cast::<u64>();
348            (shl(&hi, &Scalar::<B, u64>::new(32).to_array()) | lo).cast::<U>()
349        }
350        8 => (&b1 ^ &b2).cast::<u8>().cast::<U>(),
351        16 => (&b1 ^ &b2).cast::<u16>().cast::<U>(),
352        _ => panic!("random bits must be 8, 16, 32, or 64 bits wide"),
353    }
354}
355
356fn uniform_with<B: Backend, T: Float, U: Int>(
357    key: &Key<B>,
358    shape: &[usize],
359    minval: Array<B, T>,
360    maxval: Array<B, T>,
361) -> Array<B, T> {
362    uniform_from_bits::<B, T, U>(|n| random_bits(key, n, shape), minval, maxval)
363}
364
365/// JAX's `uniform` from the random bits that `bits(nbits)` draws.
366fn uniform_from_bits<B: Backend, T: Float, U: Int>(
367    bits: impl FnOnce(usize) -> Array<B, U>,
368    minval: Array<B, T>,
369    maxval: Array<B, T>,
370) -> Array<B, T> {
371    let (nbits, nmant) = match T::DTYPE {
372        DType::F16 => (16, 10),
373        DType::BF16 => (16, 7),
374        DType::F32 => (32, 23),
375        _ => (64, 52),
376    };
377    // Fill the mantissa of a number in [1, 2) with random bits, then shift
378    // to [0, 1) and scale.
379    let rng_bits = if nmant < 8 { 8 } else { nbits };
380    let bits: Array<B, U> = bits(rng_bits);
381    let shift = Scalar::<B, U>::new(cast::<u64, U>((rng_bits - nmant) as u64)).to_array();
382    let one: Scalar<B, T> = Scalar::new(cast::<u8, T>(1));
383    let one_bits = one.bitcast::<U>().to_array();
384    let float_bits = shr(&bits, &shift) | one_bits;
385    let floats = lax::bitcast_convert_type::<B, U, T>(&float_bits) - one;
386    let scaled = floats * (&maxval - &minval) + &minval;
387    jnp::maximum(minval, scaled)
388}
389
390/// Uniform random floats in `[minval, maxval)` (`jax.random.uniform`).
391#[track_caller]
392pub fn uniform<B: Backend, T: Float>(
393    key: &Key<B>,
394    shape: impl Into<Shape>,
395    minval: impl ArrayLike<B, T>,
396    maxval: impl ArrayLike<B, T>,
397) -> Array<B, T> {
398    let shape = shape.into();
399    if B::FAST_PATHS
400        && shape.rank() == 0
401        && let (Some(lo), Some(hi)) = (minval.as_scalar(), maxval.as_scalar())
402    {
403        key.check_single();
404        if let Some(v) = B::random_uniform_scalar::<T>(&key.data, lo.0, hi.0) {
405            return Scalar(v).to_array();
406        }
407    }
408    let (lo, hi) = (minval.into_array(), maxval.into_array());
409    key.check_single();
410    if let Some(r) = B::random_uniform::<T>(&key.data, &shape, &lo.0, &hi.0) {
411        return Array(r);
412    }
413    uniform_generic(key, &shape, lo, hi)
414}
415
416/// The generic `uniform`, as JAX computes it.
417pub(crate) fn uniform_generic<B: Backend, T: Float>(
418    key: &Key<B>,
419    shape: &Shape,
420    lo: Array<B, T>,
421    hi: Array<B, T>,
422) -> Array<B, T> {
423    let shape = shape.clone();
424    match T::DTYPE {
425        DType::F16 | DType::BF16 => uniform_with::<B, T, u16>(key, &shape, lo, hi),
426        DType::F32 => uniform_with::<B, T, u32>(key, &shape, lo, hi),
427        _ => uniform_with::<B, T, u64>(key, &shape, lo, hi),
428    }
429}
430
431/// Uniform random floats in `[minval, maxval)` for each key of an array of
432/// keys (`u32[*batch, 2]`), of shape `[*batch, *shape]`: JAX's
433/// `jax.vmap(lambda k: jax.random.uniform(k, shape, minval, maxval))(keys)`
434/// (one vmap per batch dimension), with the keys hashed together as JAX's
435/// batched `threefry2x32` hashes them. `minval` and `maxval` broadcast
436/// against the result, as unbatched operands of the vmapped function.
437///
438/// # Examples
439///
440/// ```
441/// use ruxla_core::{Native, random};
442///
443/// let keys = random::split(&random::key::<Native>(0), 3);
444/// let u = random::batched_uniform::<Native, f32>(&keys, [2], 0.0, 1.0);
445/// assert_eq!(u.shape().dims(), &[3, 2]);
446/// for i in 0..3 {
447///     let one = random::uniform::<Native, f32>(&keys.get(i), [2], 0.0, 1.0);
448///     assert_eq!(u.to_vec()[2 * i..2 * i + 2], one.to_vec());
449/// }
450/// ```
451///
452/// # Panics
453///
454/// Panics if `keys` is a single key (use [`uniform`]).
455#[track_caller]
456pub fn batched_uniform<B: Backend, T: Float>(
457    keys: &Key<B>,
458    shape: impl Into<Shape>,
459    minval: impl ArrayLike<B, T>,
460    maxval: impl ArrayLike<B, T>,
461) -> Array<B, T> {
462    assert!(
463        B::key_rank(&keys.data) > 1,
464        "batched_uniform needs an array of keys, not a single key"
465    );
466    let shape = shape.into();
467    let (lo, hi) = (minval.into_array(), maxval.into_array());
468    match T::DTYPE {
469        DType::F16 | DType::BF16 => {
470            uniform_from_bits::<B, T, u16>(|n| random_bits_batched(keys, n, &shape), lo, hi)
471        }
472        DType::F32 => {
473            uniform_from_bits::<B, T, u32>(|n| random_bits_batched(keys, n, &shape), lo, hi)
474        }
475        _ => uniform_from_bits::<B, T, u64>(|n| random_bits_batched(keys, n, &shape), lo, hi),
476    }
477}
478
479fn next_after_minus_one<T: Float>() -> T {
480    // Decrementing the bits of -1 moves it one step toward zero.
481    let mut bytes = Vec::new();
482    cast::<f64, T>(-1.0).write_bytes(&mut bytes);
483    let n = bytes.len();
484    let mut v = u64::from_le_bytes({
485        let mut b = [0u8; 8];
486        b[..n].copy_from_slice(&if cfg!(target_endian = "little") {
487            bytes.clone()
488        } else {
489            bytes.iter().rev().copied().collect()
490        });
491        b
492    });
493    v -= 1;
494    let le = v.to_le_bytes();
495    let out: Vec<u8> = if cfg!(target_endian = "little") {
496        le[..n].to_vec()
497    } else {
498        le[..n].iter().rev().copied().collect()
499    };
500    T::read_bytes(&out)
501}
502
503/// Standard normal random floats (`jax.random.normal`).
504#[track_caller]
505pub fn normal<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
506    let lo = Scalar::<B, T>::new(next_after_minus_one::<T>());
507    let u = uniform(key, shape, lo, Scalar::new(cast::<u8, T>(1)));
508    lax::erf_inv(&u) * Scalar::new(cast::<f64, T>(std::f64::consts::SQRT_2))
509}
510
511fn int_range<T: Int>() -> (i128, i128) {
512    match T::DTYPE {
513        DType::I8 => (i8::MIN.into(), i8::MAX.into()),
514        DType::I16 => (i16::MIN.into(), i16::MAX.into()),
515        DType::I32 => (i32::MIN.into(), i32::MAX.into()),
516        DType::I64 => (i64::MIN.into(), i64::MAX.into()),
517        DType::U8 => (0, u8::MAX.into()),
518        DType::U16 => (0, u16::MAX.into()),
519        DType::U32 => (0, u32::MAX.into()),
520        _ => (0, u64::MAX.into()),
521    }
522}
523
524fn int_const<B: Backend, T: Int>(v: i128) -> Scalar<B, T> {
525    Scalar::new(if T::DTYPE.kind() == ruxla_ir::DTypeKind::UnsignedInt {
526        cast::<u64, T>(v as u64)
527    } else {
528        cast::<i64, T>(v as i64)
529    })
530}
531
532/// `_convert_and_clip_integer` of JAX, for bounds already of type `T`: a
533/// clamp to the range of `T`.
534fn convert_and_clip<B: Backend, T: Int>(x: &Array<B, T>) -> Array<B, T> {
535    let (lo, hi) = int_range::<T>();
536    lax::clamp(
537        &int_const::<B, T>(lo).to_array(),
538        x,
539        &int_const::<B, T>(hi).to_array(),
540    )
541}
542
543fn randint_with<B: Backend, T: Int, U: Int>(
544    key: &Key<B>,
545    shape: &[usize],
546    minval: Array<B, T>,
547    maxval: Array<B, T>,
548) -> Array<B, T> {
549    let (_, max) = int_range::<T>();
550    let maxval_out_of_range = maxval.gt(convert_and_clip(&int_const::<B, T>(max).to_array()));
551    let minval = convert_and_clip(&minval);
552    let maxval = convert_and_clip(&maxval);
553    let nbits = T::DTYPE.size_in_bytes() * 8;
554    let (k1, k2) = split2(key);
555    let higher: Array<B, U> = random_bits(&k1, nbits, shape);
556    let lower: Array<B, U> = random_bits(&k2, nbits, shape);
557    let one = Scalar::<B, U>::new(cast::<u8, U>(1));
558    let span = (&maxval - &minval).cast::<U>();
559    let span = jnp::where_(maxval.le(&minval), one, &span);
560    let span = jnp::where_(maxval_out_of_range & maxval.gt(&minval), &span + one, &span);
561    let half = Scalar::<B, U>::new(cast::<u64, U>(1u64 << (nbits / 2))).to_array();
562    let multiplier = jnp::fmod(half, &span);
563    let multiplier = jnp::fmod(&multiplier * &multiplier, &span);
564    let offset = jnp::fmod(&higher, &span) * &multiplier + jnp::fmod(&lower, &span);
565    let offset = jnp::fmod(offset, &span);
566    jnp::broadcast_to(minval + offset.cast::<T>(), shape)
567}
568
569/// Uniform random integers in `[minval, maxval)` (`jax.random.randint`).
570#[track_caller]
571pub fn randint<B: Backend, T: Int>(
572    key: &Key<B>,
573    shape: impl Into<Shape>,
574    minval: impl ArrayLike<B, T>,
575    maxval: impl ArrayLike<B, T>,
576) -> Array<B, T> {
577    let shape = shape.into();
578    if B::FAST_PATHS
579        && shape.rank() == 0
580        && let (Some(lo), Some(hi)) = (minval.as_scalar(), maxval.as_scalar())
581    {
582        key.check_single();
583        if let Some(v) = B::random_randint_scalar::<T>(&key.data, lo.0, hi.0) {
584            return Scalar(v).to_array();
585        }
586    }
587    let (lo, hi) = (minval.into_array(), maxval.into_array());
588    key.check_single();
589    if let Some(r) = B::random_randint::<T>(&key.data, &shape, &lo.0, &hi.0) {
590        return Array(r);
591    }
592    randint_generic(key, &shape, lo, hi)
593}
594
595/// The generic `randint`, as JAX computes it.
596pub(crate) fn randint_generic<B: Backend, T: Int>(
597    key: &Key<B>,
598    shape: &Shape,
599    lo: Array<B, T>,
600    hi: Array<B, T>,
601) -> Array<B, T> {
602    let shape = shape.clone();
603    match T::DTYPE.size_in_bytes() {
604        1 => randint_with::<B, T, u8>(key, &shape, lo, hi),
605        2 => randint_with::<B, T, u16>(key, &shape, lo, hi),
606        4 => randint_with::<B, T, u32>(key, &shape, lo, hi),
607        _ => randint_with::<B, T, u64>(key, &shape, lo, hi),
608    }
609}
610
611/// Random booleans that are true with probability `p`
612/// (`jax.random.bernoulli`).
613#[track_caller]
614pub fn bernoulli<B: Backend, T: Float>(
615    key: &Key<B>,
616    p: impl ArrayLike<B, T>,
617    shape: impl Into<Shape>,
618) -> Array<B, bool> {
619    let zero = Scalar::<B, T>::new(cast::<u8, T>(0));
620    let one = Scalar::<B, T>::new(cast::<u8, T>(1));
621    uniform(key, shape, zero, one).lt(p.into_array())
622}
623
624fn tiny<T: Float>() -> T {
625    match T::DTYPE {
626        DType::F16 => cast(6.103_515_625e-5f64),
627        DType::BF16 | DType::F32 => cast(f64::from(f32::MIN_POSITIVE)),
628        _ => cast(f64::MIN_POSITIVE),
629    }
630}
631
632/// Standard Gumbel random floats (`jax.random.gumbel`).
633#[track_caller]
634pub fn gumbel<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
635    let u = uniform(
636        key,
637        shape,
638        Scalar::<B, T>::new(tiny::<T>()),
639        Scalar::new(cast::<u8, T>(1)),
640    );
641    -jnp::log(-jnp::log(u))
642}
643
644/// Samples indices (`i32`) from the categorical distribution of `logits`
645/// along `axis` (`jax.random.categorical`).
646#[track_caller]
647pub fn categorical<B: Backend, T: Float>(
648    key: &Key<B>,
649    logits: &Array<B, T>,
650    axis: i64,
651) -> Array<B, i32> {
652    let noise = gumbel::<B, T>(key, logits.shape());
653    jnp::argmax(noise + logits, axis)
654}
655
656/// The number of sorts by random keys that `_shuffle` in JAX does for `size`
657/// elements: `ceil(3 ln(size) / ln(2^32 - 1))`, with at least one element.
658fn shuffle_rounds(size: usize) -> usize {
659    let exponent = 3.0;
660    let uint32_max = f64::from(u32::MAX);
661    (exponent * (size.max(1) as f64).ln() / uint32_max.ln()).ceil() as usize
662}
663
664/// JAX's `_shuffle` along axis 0: sorts by fresh random `u32` keys of the
665/// shape of `x`, as many times as [`shuffle_rounds`] says.
666fn shuffle_leading<B: Backend, T: Element>(key: &Key<B>, x: Array<B, T>) -> Array<B, T> {
667    let mut key = key.clone();
668    let mut x = x;
669    for _ in 0..shuffle_rounds(x.size()) {
670        let (next, subkey) = split2(&key);
671        key = next;
672        let sort_keys = bits(&subkey, x.shape());
673        x = lax::sort_key_val(&sort_keys, &x, 0).1;
674    }
675    x
676}
677
678/// A random permutation of `0..n` (`jax.random.permutation(key, n)`).
679///
680/// # Examples
681///
682/// ```
683/// use ruxla_core::{Native, random};
684///
685/// let p = random::permutation::<Native>(&random::key(0), 5).to_vec();
686/// let mut sorted = p.clone();
687/// sorted.sort();
688/// assert_eq!(sorted, [0, 1, 2, 3, 4]);
689/// ```
690#[track_caller]
691pub fn permutation<B: Backend>(key: &Key<B>, n: usize) -> Array<B, i32> {
692    key.check_single();
693    shuffle_leading(key, jnp::arange::<B, i32>(n))
694}
695
696/// `x` with its elements along axis 0 randomly permuted
697/// (`jax.random.permutation(key, x)`, with `axis=0` and
698/// `independent=False`): the rows are taken in the order of
699/// [`permutation`] of their number.
700///
701/// # Panics
702///
703/// Panics if `x` is a scalar.
704///
705/// # Examples
706///
707/// ```
708/// use ruxla_core::{Array, Native, random};
709///
710/// let x = Array::<Native, f32>::from_vec(vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0], [3, 2]);
711/// let y = random::shuffle(&random::key(0), &x);
712/// assert_eq!(y.shape().dims(), [3, 2]);
713/// ```
714#[track_caller]
715pub fn shuffle<B: Backend, T: Element>(key: &Key<B>, x: &Array<B, T>) -> Array<B, T> {
716    key.check_single();
717    let shape = x.shape();
718    assert!(shape.rank() > 0, "shuffle needs at least one dimension");
719    if shape.rank() == 1 {
720        return shuffle_leading(key, x.clone());
721    }
722    // `jnp.take(x, permutation(key, n), axis=0)`. JAX's `take` gathers in
723    // the fill mode, which gives the same values for these indices, which
724    // are always in bounds.
725    let n = shape[0];
726    let ind = permutation(key, n).reshape([n, 1]);
727    let mut slice_sizes = shape.dims().to_vec();
728    slice_sizes[0] = 1;
729    let dims = GatherDims {
730        offset_dims: (1..shape.rank()).collect(),
731        collapsed_slice_dims: vec![0],
732        start_index_map: vec![0],
733        ..GatherDims::default()
734    };
735    lax::gather(
736        x,
737        &ind,
738        &dims,
739        &slice_sizes,
740        GatherScatterMode::PromiseInBounds,
741    )
742}
743
744#[cfg(test)]
745mod threefry_tests {
746    use super::*;
747    use crate::backend::Native;
748
749    /// The native scalar loop gives the same bits as the generic
750    /// implementation (which gives JAX's IR).
751    #[test]
752    fn native_threefry_matches_the_generic_one() {
753        let counts: Vec<u32> = (0..64u32).map(|i| i.wrapping_mul(0x9E37_79B9)).collect();
754        for (k1, k2) in [
755            (0u32, 0u32),
756            (1, 2),
757            (0xDEAD_BEEF, 0x1234_5678),
758            (u32::MAX, 7),
759        ] {
760            let k1 = Array::<Native, u32>::from_vec(vec![k1], Shape::scalar());
761            let k2 = Array::<Native, u32>::from_vec(vec![k2], Shape::scalar());
762            let x1 = Array::<Native, u32>::from_vec(counts.clone(), [64]);
763            let x2 = Array::<Native, u32>::from_vec(counts.iter().rev().copied().collect(), [64]);
764            let fast = threefry2x32(&k1, &k2, &x1, &x2);
765            let generic = threefry2x32_generic(&k1, &k2, &x1, &x2);
766            assert_eq!(fast.0.to_vec(), generic.0.to_vec());
767            assert_eq!(fast.1.to_vec(), generic.1.to_vec());
768        }
769    }
770}
771
772#[cfg(test)]
773mod batched_tests {
774    use super::*;
775    use crate::backend::{Native, Trace};
776    use crate::{bf16, vmap};
777
778    fn check<T: Float>(lo: f64, hi: f64) {
779        let keys = split(&key::<Native>(11), 6);
780        let (lo, hi) = (
781            Scalar::<Native, T>::new(cast(lo)),
782            Scalar::<Native, T>::new(cast(hi)),
783        );
784        let bits =
785            |a: &Array<Native, T>| a.to_vec().iter().map(|v| v.to_bits()).collect::<Vec<_>>();
786        for shape in [vec![], vec![4], vec![2, 3]] {
787            let shape = Shape::from(shape);
788            let batched = batched_uniform(&keys, shape.clone(), lo, hi);
789            let mut dims = vec![6];
790            dims.extend_from_slice(&shape);
791            assert_eq!(batched.shape().dims(), &dims[..]);
792            // The same numbers as JAX's `vmap` of `uniform` (ruxla's `vmap`
793            // of the traced program), and as `uniform` key by key.
794            let examples: Vec<Key<Native>> = (0..6).map(|i| keys.get(i)).collect();
795            let (l, h) = (lo.value(), hi.value());
796            let s = shape.clone();
797            let vmapped =
798                vmap(move |k: Key<Trace>| uniform::<Trace, T>(&k, s.clone(), l, h)).call(&examples);
799            let n = shape.size();
800            let got = bits(&batched);
801            for (i, k) in examples.iter().enumerate() {
802                let one = uniform(k, shape.clone(), lo, hi);
803                assert_eq!(
804                    got[i * n..(i + 1) * n],
805                    bits(&one),
806                    "{} [{shape}]",
807                    T::DTYPE
808                );
809                assert_eq!(bits(&vmapped[i]), bits(&one), "{} [{shape}]", T::DTYPE);
810            }
811            // Traced and interpreted, the same numbers.
812            let s = shape.clone();
813            let traced = crate::transform::trace(
814                move |k: Key<Trace>| batched_uniform::<Trace, T>(&k, s, l, h),
815                &keys,
816            );
817            let outs = ruxla_interp::eval(&traced.function, &crate::tree::leaves(&keys))
818                .unwrap_or_else(|e| panic!("{e}"));
819            let interpreted = Array::<Native, T>(Native::leaf_array::<T>(outs[0].clone()));
820            assert_eq!(bits(&interpreted), got, "{} [{shape}]", T::DTYPE);
821        }
822        // Two batch dimensions.
823        let grid = Key::<Native>::from_data(keys.data().reshape([2, 3, 2]));
824        let batched = batched_uniform(&grid, [5], lo, hi);
825        assert_eq!(batched.shape().dims(), &[2, 3, 5]);
826        let flat = batched_uniform(&keys, [5], lo, hi);
827        assert_eq!(bits(&batched), bits(&flat));
828    }
829
830    #[test]
831    fn batched_uniform_is_the_vmap_of_uniform() {
832        check::<f32>(0.0, 1.0);
833        check::<f32>(-2.0, 3.0);
834        check::<f64>(0.0, 1.0);
835        check::<bf16>(-1.0, 1.0);
836    }
837
838    #[test]
839    #[should_panic(expected = "array of keys")]
840    fn batched_uniform_needs_an_array_of_keys() {
841        let _ = batched_uniform::<Native, f32>(&key(0), [2], 0.0, 1.0);
842    }
843}
844
845#[cfg(test)]
846mod native_override_tests {
847    use super::*;
848    use crate::backend::Native;
849    use crate::{bf16, f16};
850
851    fn check_uniform<T: Float>(lo: f64, hi: f64) {
852        let key = key::<Native>(3);
853        let (lo, hi) = (
854            Scalar::<Native, T>::new(cast(lo)),
855            Scalar::<Native, T>::new(cast(hi)),
856        );
857        for shape in [vec![], vec![7], vec![3, 5]] {
858            let shape = Shape::from(shape);
859            let fast = uniform(&key, shape.clone(), lo, hi);
860            let generic = uniform_generic(&key, &shape, lo.to_array(), hi.to_array());
861            let bits =
862                |a: &Array<Native, T>| a.to_vec().iter().map(|v| v.to_bits()).collect::<Vec<_>>();
863            assert_eq!(bits(&fast), bits(&generic), "{} [{shape}]", T::DTYPE);
864        }
865    }
866
867    fn check_randint<T: Int>(lo: i64, hi: i64) {
868        let key = key::<Native>(5);
869        let (lo, hi) = (
870            Scalar::<Native, T>::new(cast(lo)),
871            Scalar::<Native, T>::new(cast(hi)),
872        );
873        for shape in [vec![], vec![9], vec![2, 4]] {
874            let shape = Shape::from(shape);
875            let fast = randint(&key, shape.clone(), lo, hi);
876            let generic = randint_generic(&key, &shape, lo.to_array(), hi.to_array());
877            assert_eq!(fast.to_vec(), generic.to_vec(), "{} [{shape}]", T::DTYPE);
878        }
879    }
880
881    /// The native implementations of `uniform` and `randint` give the same
882    /// bits as the generic ones (which give JAX's IR).
883    #[test]
884    fn native_random_matches_the_generic_one() {
885        check_uniform::<f32>(-0.05, 0.05);
886        check_uniform::<f32>(0.0, 1.0);
887        check_uniform::<f64>(-3.0, 2.0);
888        check_uniform::<f16>(0.0, 1.0);
889        check_uniform::<bf16>(-1.0, 1.0);
890        check_randint::<i32>(0, 5);
891        check_randint::<i32>(-7, 3);
892        check_randint::<i32>(4, 4);
893        check_randint::<i32>(i32::MIN.into(), i32::MAX.into());
894        check_randint::<u8>(1, 200);
895        check_randint::<i64>(-1_000_000_007, 1_000_000_007);
896        check_randint::<u16>(0, 3);
897    }
898}