ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
//! Random numbers following `jax.random`, bit for bit.
//!
//! Keys hold two `u32` words, as JAX's default `threefry2x32` keys. The
//! hash is written generically with the same structure as JAX's lowering
//! (a loop of five iterations of four rounds, and counters built from a
//! `u64` iota), so traced programs compile to the same HLO as JAX and
//! native programs compute the same numbers.
//!
//! # Examples
//!
//! ```
//! use ruxla_core::{Native, random};
//!
//! let key = random::key::<Native>(0);
//! let (k1, k2) = random::split2(&key);
//! let x = random::uniform::<Native, f32>(&k1, [3], 0.0, 1.0);
//! assert!(x.to_vec().iter().all(|&v| (0.0..1.0).contains(&v)));
//! let n = random::randint::<Native, i32>(&k2, [], 0, 10).to_scalar();
//! assert!((0..10).contains(&n.value()));
//! ```

use ruxla_ir::{DType, GatherDims, GatherScatterMode, Shape};
use ruxla_kernels::{BinaryOp, Element, cast};

use crate::backend::Backend;
use crate::jnp;
use crate::lax;
use crate::value::{Array, ArrayLike, Float, Int, Scalar, broadcast_binary};

mod distributions;

pub use distributions::{
    beta, binomial, cauchy, chisquare, choice, choice_with_p, dirichlet, double_sided_maxwell,
    exponential, f, gamma, laplace, loggamma, logistic, maxwell, pareto, poisson, rademacher, t,
    truncated_normal, weibull_min,
};

/// A random key: two `u32` words (or an array of keys, shape `[..., 2]`).
#[derive(Clone, Debug)]
pub struct Key<B: Backend> {
    data: B::KeyData,
}

/// A key is a pytree with one leaf, its data (`u32[..., 2]`).
impl<B: Backend> crate::tree::Tree<B> for Key<B> {
    type On<C: Backend> = Key<C>;
    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
        leaves.push(B::array_leaf::<u32>(&B::key_to_array(&self.data)));
    }
    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
        let l = leaves.next().expect("too few leaves for the structure");
        Key {
            data: B::key_from_array(B::leaf_array::<u32>(l)),
        }
    }
    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Key<C> {
        let l = leaves.next().expect("too few leaves for the structure");
        Key {
            data: C::key_from_array(C::leaf_array::<u32>(l)),
        }
    }
    fn def(&self) -> crate::tree::TreeDef {
        crate::tree::TreeDef::Struct {
            name: String::from("Key"),
            fields: vec![String::from("data")],
            children: vec![crate::tree::TreeDef::Leaf],
        }
    }
    fn select(pred: crate::value::Bool<B>, on_true: &Self, on_false: &Self) -> Self {
        let data = crate::tree::select_tree(pred, &on_true.data(), &on_false.data());
        Key::from_data(data)
    }
}

impl<B: Backend> Key<B> {
    /// Wraps key data (`u32` of shape `[..., 2]`).
    ///
    /// # Panics
    ///
    /// Panics if the last dimension is not 2.
    #[track_caller]
    pub fn from_data(data: Array<B, u32>) -> Self {
        assert_eq!(
            data.shape().last(),
            Some(&2),
            "key data must have shape [..., 2]"
        );
        Self {
            data: B::key_from_array(data.0),
        }
    }

    /// The key data.
    pub fn data(&self) -> Array<B, u32> {
        Array(B::key_to_array(&self.data))
    }

    /// Key `i` of a one-dimensional array of keys.
    #[track_caller]
    pub fn get(&self, i: usize) -> Key<B> {
        let data = self.data();
        assert_eq!(data.ndim(), 2, "get needs a one-dimensional array of keys");
        Key::from_data(lax::index_in_dim(&data, i, 0, false))
    }

    #[track_caller]
    #[inline]
    fn check_single(&self) {
        assert_eq!(
            B::key_rank(&self.data),
            1,
            "this function needs a single key, not an array of keys"
        );
    }
}

/// A key from a seed, like `jax.random.key`.
pub fn key<B: Backend>(seed: i64) -> Key<B> {
    let (hi, lo) = if i32::try_from(seed).is_ok() {
        (0, seed as u32)
    } else {
        ((seed >> 32) as u32, seed as u32)
    };
    Key::from_data(Array::from_vec(vec![hi, lo], [2]))
}

fn u32s<B: Backend>(v: u32) -> Scalar<B, u32> {
    Scalar::new(v)
}

fn shl<B: Backend, T: Int>(x: &Array<B, T>, d: &Array<B, T>) -> Array<B, T> {
    broadcast_binary(BinaryOp::ShiftLeft, x, d)
}

fn shr<B: Backend, T: Int>(x: &Array<B, T>, d: &Array<B, T>) -> Array<B, T> {
    broadcast_binary(BinaryOp::ShiftRightLogical, x, d)
}

fn rotate_left<B: Backend>(x: &Array<B, u32>, d: &Array<B, u32>) -> Array<B, u32> {
    let back = u32s::<B>(32).to_array() - d;
    shl(x, d) | shr(x, &back)
}

fn apply_round<B: Backend>(v: [Array<B, u32>; 2], rotation: &Array<B, u32>) -> [Array<B, u32>; 2] {
    let v0 = &v[0] + &v[1];
    let v1 = rotate_left(&v[1], rotation);
    let v1 = &v0 ^ &v1;
    [v0, v1]
}

/// The carry of the threefry loop: the counters, the key schedule, and the
/// rotations.
type ThreefryState<B> = ([Array<B, u32>; 2], [Array<B, u32>; 3], [Array<B, u32>; 2]);

/// The threefry2x32 hash with the backend's implementation: `Native` uses
/// a scalar loop that gives the same bits as [`threefry2x32_generic`].
fn threefry2x32<B: Backend>(
    k1: &Array<B, u32>,
    k2: &Array<B, u32>,
    x1: &Array<B, u32>,
    x2: &Array<B, u32>,
) -> (Array<B, u32>, Array<B, u32>) {
    let (a, b) = B::threefry2x32(&k1.0, &k2.0, &x1.0, &x2.0);
    (Array(a), Array(b))
}

/// The generic hash of the row-major indices of `shape` (`iota_2x32`) with
/// a key, as JAX computes random bits.
pub(crate) fn key_bits_generic<B: Backend>(
    key: &Array<B, u32>,
    shape: &[usize],
) -> (Array<B, u32>, Array<B, u32>) {
    let (k1, k2) = halves(key);
    let (c1, c2) = iota_2x32::<B>(shape);
    threefry2x32(&k1, &k2, &c1, &c2)
}

/// The two words of a key's data.
fn halves<B: Backend>(data: &Array<B, u32>) -> (Array<B, u32>, Array<B, u32>) {
    (
        lax::index_in_dim(data, 0, 0, false),
        lax::index_in_dim(data, 1, 0, false),
    )
}

/// The threefry2x32 hash, as JAX lowers it with rolled loops.
pub(crate) fn threefry2x32_generic<B: Backend>(
    k1: &Array<B, u32>,
    k2: &Array<B, u32>,
    x1: &Array<B, u32>,
    x2: &Array<B, u32>,
) -> (Array<B, u32>, Array<B, u32>) {
    let rotations: [Array<B, u32>; 2] = [
        Array::from_vec(vec![13, 15, 26, 6], [4]),
        Array::from_vec(vec![17, 29, 16, 24], [4]),
    ];
    let ks2 = (k1 ^ k2) ^ u32s::<B>(0x1BD1_1BDA);
    let x = [x1 + k1, x2 + k2];
    // `rotate_list` in JAX: the first element moves to the end.
    let init = (x, [k2.clone(), ks2, k1.clone()], rotations);
    let (x, _, _) = lax::fori_loop(
        0,
        5,
        |i, (x, ks, rotations): ThreefryState<B>| {
            let mut x = x;
            for j in 0..4 {
                x = apply_round(x, &lax::index_in_dim(&rotations[0], j, 0, false));
            }
            let step = (i + 1).cast::<u32>();
            let x = [&x[0] + &ks[0], (&x[1] + &ks[1]) + step];
            let [ks0, ks1, ks2] = ks;
            let [r0, r1] = rotations;
            (x, [ks1, ks2, ks0], [r1, r0])
        },
        init,
    );
    let [a, b] = x;
    (a, b)
}

/// The row-major index of each element of `shape` as `(high, low)` `u32`
/// words, as JAX's `iota_2x32_shape` lowering computes it.
fn iota_2x32<B: Backend>(shape: &[usize]) -> (Array<B, u32>, Array<B, u32>) {
    if shape.is_empty() {
        let z = jnp::zeros::<B, u32>(Shape::scalar());
        return (z.clone(), z);
    }
    let splat = |v: u64| jnp::full::<B, u64>(shape, v);
    let counts = (0..shape.len())
        .map(|d| {
            let stride = shape[d + 1..].iter().product::<usize>() as u64;
            lax::mul(&splat(stride), &lax::iota::<B, u64>(shape, d))
        })
        .reduce(|a, b| lax::add(&a, &b))
        .expect("the shape is not empty");
    let high = lax::shift_right_logical(&counts, &splat(32));
    (high.cast::<u32>(), counts.cast::<u32>())
}

/// Splits a key into `num` keys (`jax.random.split`).
#[track_caller]
pub fn split<B: Backend>(key: &Key<B>, num: usize) -> Key<B> {
    key.check_single();
    Key {
        data: B::key_split(&key.data, num),
    }
}

/// The generic `split`, as JAX computes it.
pub(crate) fn split_generic<B: Backend>(key: &Array<B, u32>, num: usize) -> Array<B, u32> {
    let (k1, k2) = halves(key);
    let (c1, c2) = iota_2x32::<B>(&[num]);
    let (b1, b2) = threefry2x32(&k1, &k2, &c1, &c2);
    jnp::stack(&[b1, b2], 1)
}

/// Splits a key in two.
#[track_caller]
#[inline]
pub fn split2<B: Backend>(key: &Key<B>) -> (Key<B>, Key<B>) {
    key.check_single();
    if let Some((a, b)) = B::key_split2(&key.data) {
        return (Key { data: a }, Key { data: b });
    }
    split2_generic(key)
}

/// [`split2`] through [`split`].
fn split2_generic<B: Backend>(key: &Key<B>) -> (Key<B>, Key<B>) {
    let keys = split(key, 2);
    (keys.get(0), keys.get(1))
}

/// Folds data into a key (`jax.random.fold_in`).
#[track_caller]
pub fn fold_in<B: Backend>(key: &Key<B>, data: impl Into<Scalar<B, u32>>) -> Key<B> {
    key.check_single();
    Key {
        data: B::key_fold_in(&key.data, data.into().0),
    }
}

/// The generic `fold_in`, as JAX computes it.
pub(crate) fn fold_in_generic<B: Backend>(
    key: &Array<B, u32>,
    data: Scalar<B, u32>,
) -> Array<B, u32> {
    let (k1, k2) = halves(key);
    let zero = jnp::zeros::<B, u32>([1]);
    let data = data.to_array().reshape([1]);
    let (y1, y2) = threefry2x32(&k1, &k2, &zero, &data);
    lax::concatenate(&[y1, y2], 0)
}

/// Random bits of `nbits` (8, 16, 32, or 64) in an unsigned type `U` of
/// that width or wider.
fn random_bits<B: Backend, U: Int>(key: &Key<B>, nbits: usize, shape: &[usize]) -> Array<B, U> {
    key.check_single();
    let (b1, b2) = B::key_bits(&key.data, shape);
    combine_bits(Array::<B, u32>(b1), Array::<B, u32>(b2), nbits)
}

/// Uniform random `u32` bits (`jax.random.bits`).
#[track_caller]
pub fn bits<B: Backend>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, u32> {
    random_bits(key, 32, &shape.into())
}

/// Random bits of `nbits` (8, 16, 32, or 64) in an unsigned type `U` of
/// that width or wider, for each key of an array of keys (`u32[*batch,
/// 2]`): shape `[*batch, *shape]`. This is `random_bits` batched as JAX's
/// `vmap` batches `threefry2x32`: the keys and the counters of one key's
/// draw are broadcast to the full shape, and hashed together.
fn random_bits_batched<B: Backend, U: Int>(
    keys: &Key<B>,
    nbits: usize,
    shape: &[usize],
) -> Array<B, U> {
    let data = keys.data();
    let batch = &data.shape()[..data.ndim() - 1];
    let nb = batch.len();
    let mut full = batch.to_vec();
    full.extend_from_slice(shape);
    let key_dims: Vec<usize> = (0..nb).collect();
    let count_dims: Vec<usize> = (nb..full.len()).collect();
    let word = |i: usize| {
        let w = lax::index_in_dim(&data, i, nb, false);
        lax::broadcast_in_dim(&w, full.as_slice(), &key_dims)
    };
    let (c1, c2) = iota_2x32::<B>(shape);
    let count = |c: &Array<B, u32>| lax::broadcast_in_dim(c, full.as_slice(), &count_dims);
    let (b1, b2) = threefry2x32(&word(0), &word(1), &count(&c1), &count(&c2));
    combine_bits(b1, b2, nbits)
}

/// Random bits of `nbits` from the two words of the hash, as JAX's
/// `threefry_random_bits` combines them.
fn combine_bits<B: Backend, U: Int>(
    b1: Array<B, u32>,
    b2: Array<B, u32>,
    nbits: usize,
) -> Array<B, U> {
    match nbits {
        32 => (&b1 ^ &b2).cast::<U>(),
        64 => {
            let hi = b1.cast::<u64>();
            let lo = b2.cast::<u64>();
            (shl(&hi, &Scalar::<B, u64>::new(32).to_array()) | lo).cast::<U>()
        }
        8 => (&b1 ^ &b2).cast::<u8>().cast::<U>(),
        16 => (&b1 ^ &b2).cast::<u16>().cast::<U>(),
        _ => panic!("random bits must be 8, 16, 32, or 64 bits wide"),
    }
}

fn uniform_with<B: Backend, T: Float, U: Int>(
    key: &Key<B>,
    shape: &[usize],
    minval: Array<B, T>,
    maxval: Array<B, T>,
) -> Array<B, T> {
    uniform_from_bits::<B, T, U>(|n| random_bits(key, n, shape), minval, maxval)
}

/// JAX's `uniform` from the random bits that `bits(nbits)` draws.
fn uniform_from_bits<B: Backend, T: Float, U: Int>(
    bits: impl FnOnce(usize) -> Array<B, U>,
    minval: Array<B, T>,
    maxval: Array<B, T>,
) -> Array<B, T> {
    let (nbits, nmant) = match T::DTYPE {
        DType::F16 => (16, 10),
        DType::BF16 => (16, 7),
        DType::F32 => (32, 23),
        _ => (64, 52),
    };
    // Fill the mantissa of a number in [1, 2) with random bits, then shift
    // to [0, 1) and scale.
    let rng_bits = if nmant < 8 { 8 } else { nbits };
    let bits: Array<B, U> = bits(rng_bits);
    let shift = Scalar::<B, U>::new(cast::<u64, U>((rng_bits - nmant) as u64)).to_array();
    let one: Scalar<B, T> = Scalar::new(cast::<u8, T>(1));
    let one_bits = one.bitcast::<U>().to_array();
    let float_bits = shr(&bits, &shift) | one_bits;
    let floats = lax::bitcast_convert_type::<B, U, T>(&float_bits) - one;
    let scaled = floats * (&maxval - &minval) + &minval;
    jnp::maximum(minval, scaled)
}

/// Uniform random floats in `[minval, maxval)` (`jax.random.uniform`).
#[track_caller]
pub fn uniform<B: Backend, T: Float>(
    key: &Key<B>,
    shape: impl Into<Shape>,
    minval: impl ArrayLike<B, T>,
    maxval: impl ArrayLike<B, T>,
) -> Array<B, T> {
    let shape = shape.into();
    if B::FAST_PATHS
        && shape.rank() == 0
        && let (Some(lo), Some(hi)) = (minval.as_scalar(), maxval.as_scalar())
    {
        key.check_single();
        if let Some(v) = B::random_uniform_scalar::<T>(&key.data, lo.0, hi.0) {
            return Scalar(v).to_array();
        }
    }
    let (lo, hi) = (minval.into_array(), maxval.into_array());
    key.check_single();
    if let Some(r) = B::random_uniform::<T>(&key.data, &shape, &lo.0, &hi.0) {
        return Array(r);
    }
    uniform_generic(key, &shape, lo, hi)
}

/// The generic `uniform`, as JAX computes it.
pub(crate) fn uniform_generic<B: Backend, T: Float>(
    key: &Key<B>,
    shape: &Shape,
    lo: Array<B, T>,
    hi: Array<B, T>,
) -> Array<B, T> {
    let shape = shape.clone();
    match T::DTYPE {
        DType::F16 | DType::BF16 => uniform_with::<B, T, u16>(key, &shape, lo, hi),
        DType::F32 => uniform_with::<B, T, u32>(key, &shape, lo, hi),
        _ => uniform_with::<B, T, u64>(key, &shape, lo, hi),
    }
}

/// Uniform random floats in `[minval, maxval)` for each key of an array of
/// keys (`u32[*batch, 2]`), of shape `[*batch, *shape]`: JAX's
/// `jax.vmap(lambda k: jax.random.uniform(k, shape, minval, maxval))(keys)`
/// (one vmap per batch dimension), with the keys hashed together as JAX's
/// batched `threefry2x32` hashes them. `minval` and `maxval` broadcast
/// against the result, as unbatched operands of the vmapped function.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Native, random};
///
/// let keys = random::split(&random::key::<Native>(0), 3);
/// let u = random::batched_uniform::<Native, f32>(&keys, [2], 0.0, 1.0);
/// assert_eq!(u.shape().dims(), &[3, 2]);
/// for i in 0..3 {
///     let one = random::uniform::<Native, f32>(&keys.get(i), [2], 0.0, 1.0);
///     assert_eq!(u.to_vec()[2 * i..2 * i + 2], one.to_vec());
/// }
/// ```
///
/// # Panics
///
/// Panics if `keys` is a single key (use [`uniform`]).
#[track_caller]
pub fn batched_uniform<B: Backend, T: Float>(
    keys: &Key<B>,
    shape: impl Into<Shape>,
    minval: impl ArrayLike<B, T>,
    maxval: impl ArrayLike<B, T>,
) -> Array<B, T> {
    assert!(
        B::key_rank(&keys.data) > 1,
        "batched_uniform needs an array of keys, not a single key"
    );
    let shape = shape.into();
    let (lo, hi) = (minval.into_array(), maxval.into_array());
    match T::DTYPE {
        DType::F16 | DType::BF16 => {
            uniform_from_bits::<B, T, u16>(|n| random_bits_batched(keys, n, &shape), lo, hi)
        }
        DType::F32 => {
            uniform_from_bits::<B, T, u32>(|n| random_bits_batched(keys, n, &shape), lo, hi)
        }
        _ => uniform_from_bits::<B, T, u64>(|n| random_bits_batched(keys, n, &shape), lo, hi),
    }
}

fn next_after_minus_one<T: Float>() -> T {
    // Decrementing the bits of -1 moves it one step toward zero.
    let mut bytes = Vec::new();
    cast::<f64, T>(-1.0).write_bytes(&mut bytes);
    let n = bytes.len();
    let mut v = u64::from_le_bytes({
        let mut b = [0u8; 8];
        b[..n].copy_from_slice(&if cfg!(target_endian = "little") {
            bytes.clone()
        } else {
            bytes.iter().rev().copied().collect()
        });
        b
    });
    v -= 1;
    let le = v.to_le_bytes();
    let out: Vec<u8> = if cfg!(target_endian = "little") {
        le[..n].to_vec()
    } else {
        le[..n].iter().rev().copied().collect()
    };
    T::read_bytes(&out)
}

/// Standard normal random floats (`jax.random.normal`).
#[track_caller]
pub fn normal<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
    let lo = Scalar::<B, T>::new(next_after_minus_one::<T>());
    let u = uniform(key, shape, lo, Scalar::new(cast::<u8, T>(1)));
    lax::erf_inv(&u) * Scalar::new(cast::<f64, T>(std::f64::consts::SQRT_2))
}

fn int_range<T: Int>() -> (i128, i128) {
    match T::DTYPE {
        DType::I8 => (i8::MIN.into(), i8::MAX.into()),
        DType::I16 => (i16::MIN.into(), i16::MAX.into()),
        DType::I32 => (i32::MIN.into(), i32::MAX.into()),
        DType::I64 => (i64::MIN.into(), i64::MAX.into()),
        DType::U8 => (0, u8::MAX.into()),
        DType::U16 => (0, u16::MAX.into()),
        DType::U32 => (0, u32::MAX.into()),
        _ => (0, u64::MAX.into()),
    }
}

fn int_const<B: Backend, T: Int>(v: i128) -> Scalar<B, T> {
    Scalar::new(if T::DTYPE.kind() == ruxla_ir::DTypeKind::UnsignedInt {
        cast::<u64, T>(v as u64)
    } else {
        cast::<i64, T>(v as i64)
    })
}

/// `_convert_and_clip_integer` of JAX, for bounds already of type `T`: a
/// clamp to the range of `T`.
fn convert_and_clip<B: Backend, T: Int>(x: &Array<B, T>) -> Array<B, T> {
    let (lo, hi) = int_range::<T>();
    lax::clamp(
        &int_const::<B, T>(lo).to_array(),
        x,
        &int_const::<B, T>(hi).to_array(),
    )
}

fn randint_with<B: Backend, T: Int, U: Int>(
    key: &Key<B>,
    shape: &[usize],
    minval: Array<B, T>,
    maxval: Array<B, T>,
) -> Array<B, T> {
    let (_, max) = int_range::<T>();
    let maxval_out_of_range = maxval.gt(convert_and_clip(&int_const::<B, T>(max).to_array()));
    let minval = convert_and_clip(&minval);
    let maxval = convert_and_clip(&maxval);
    let nbits = T::DTYPE.size_in_bytes() * 8;
    let (k1, k2) = split2(key);
    let higher: Array<B, U> = random_bits(&k1, nbits, shape);
    let lower: Array<B, U> = random_bits(&k2, nbits, shape);
    let one = Scalar::<B, U>::new(cast::<u8, U>(1));
    let span = (&maxval - &minval).cast::<U>();
    let span = jnp::where_(maxval.le(&minval), one, &span);
    let span = jnp::where_(maxval_out_of_range & maxval.gt(&minval), &span + one, &span);
    let half = Scalar::<B, U>::new(cast::<u64, U>(1u64 << (nbits / 2))).to_array();
    let multiplier = jnp::fmod(half, &span);
    let multiplier = jnp::fmod(&multiplier * &multiplier, &span);
    let offset = jnp::fmod(&higher, &span) * &multiplier + jnp::fmod(&lower, &span);
    let offset = jnp::fmod(offset, &span);
    jnp::broadcast_to(minval + offset.cast::<T>(), shape)
}

/// Uniform random integers in `[minval, maxval)` (`jax.random.randint`).
#[track_caller]
pub fn randint<B: Backend, T: Int>(
    key: &Key<B>,
    shape: impl Into<Shape>,
    minval: impl ArrayLike<B, T>,
    maxval: impl ArrayLike<B, T>,
) -> Array<B, T> {
    let shape = shape.into();
    if B::FAST_PATHS
        && shape.rank() == 0
        && let (Some(lo), Some(hi)) = (minval.as_scalar(), maxval.as_scalar())
    {
        key.check_single();
        if let Some(v) = B::random_randint_scalar::<T>(&key.data, lo.0, hi.0) {
            return Scalar(v).to_array();
        }
    }
    let (lo, hi) = (minval.into_array(), maxval.into_array());
    key.check_single();
    if let Some(r) = B::random_randint::<T>(&key.data, &shape, &lo.0, &hi.0) {
        return Array(r);
    }
    randint_generic(key, &shape, lo, hi)
}

/// The generic `randint`, as JAX computes it.
pub(crate) fn randint_generic<B: Backend, T: Int>(
    key: &Key<B>,
    shape: &Shape,
    lo: Array<B, T>,
    hi: Array<B, T>,
) -> Array<B, T> {
    let shape = shape.clone();
    match T::DTYPE.size_in_bytes() {
        1 => randint_with::<B, T, u8>(key, &shape, lo, hi),
        2 => randint_with::<B, T, u16>(key, &shape, lo, hi),
        4 => randint_with::<B, T, u32>(key, &shape, lo, hi),
        _ => randint_with::<B, T, u64>(key, &shape, lo, hi),
    }
}

/// Random booleans that are true with probability `p`
/// (`jax.random.bernoulli`).
#[track_caller]
pub fn bernoulli<B: Backend, T: Float>(
    key: &Key<B>,
    p: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, bool> {
    let zero = Scalar::<B, T>::new(cast::<u8, T>(0));
    let one = Scalar::<B, T>::new(cast::<u8, T>(1));
    uniform(key, shape, zero, one).lt(p.into_array())
}

fn tiny<T: Float>() -> T {
    match T::DTYPE {
        DType::F16 => cast(6.103_515_625e-5f64),
        DType::BF16 | DType::F32 => cast(f64::from(f32::MIN_POSITIVE)),
        _ => cast(f64::MIN_POSITIVE),
    }
}

/// Standard Gumbel random floats (`jax.random.gumbel`).
#[track_caller]
pub fn gumbel<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
    let u = uniform(
        key,
        shape,
        Scalar::<B, T>::new(tiny::<T>()),
        Scalar::new(cast::<u8, T>(1)),
    );
    -jnp::log(-jnp::log(u))
}

/// Samples indices (`i32`) from the categorical distribution of `logits`
/// along `axis` (`jax.random.categorical`).
#[track_caller]
pub fn categorical<B: Backend, T: Float>(
    key: &Key<B>,
    logits: &Array<B, T>,
    axis: i64,
) -> Array<B, i32> {
    let noise = gumbel::<B, T>(key, logits.shape());
    jnp::argmax(noise + logits, axis)
}

/// The number of sorts by random keys that `_shuffle` in JAX does for `size`
/// elements: `ceil(3 ln(size) / ln(2^32 - 1))`, with at least one element.
fn shuffle_rounds(size: usize) -> usize {
    let exponent = 3.0;
    let uint32_max = f64::from(u32::MAX);
    (exponent * (size.max(1) as f64).ln() / uint32_max.ln()).ceil() as usize
}

/// JAX's `_shuffle` along axis 0: sorts by fresh random `u32` keys of the
/// shape of `x`, as many times as [`shuffle_rounds`] says.
fn shuffle_leading<B: Backend, T: Element>(key: &Key<B>, x: Array<B, T>) -> Array<B, T> {
    let mut key = key.clone();
    let mut x = x;
    for _ in 0..shuffle_rounds(x.size()) {
        let (next, subkey) = split2(&key);
        key = next;
        let sort_keys = bits(&subkey, x.shape());
        x = lax::sort_key_val(&sort_keys, &x, 0).1;
    }
    x
}

/// A random permutation of `0..n` (`jax.random.permutation(key, n)`).
///
/// # Examples
///
/// ```
/// use ruxla_core::{Native, random};
///
/// let p = random::permutation::<Native>(&random::key(0), 5).to_vec();
/// let mut sorted = p.clone();
/// sorted.sort();
/// assert_eq!(sorted, [0, 1, 2, 3, 4]);
/// ```
#[track_caller]
pub fn permutation<B: Backend>(key: &Key<B>, n: usize) -> Array<B, i32> {
    key.check_single();
    shuffle_leading(key, jnp::arange::<B, i32>(n))
}

/// `x` with its elements along axis 0 randomly permuted
/// (`jax.random.permutation(key, x)`, with `axis=0` and
/// `independent=False`): the rows are taken in the order of
/// [`permutation`] of their number.
///
/// # Panics
///
/// Panics if `x` is a scalar.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, random};
///
/// let x = Array::<Native, f32>::from_vec(vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0], [3, 2]);
/// let y = random::shuffle(&random::key(0), &x);
/// assert_eq!(y.shape().dims(), [3, 2]);
/// ```
#[track_caller]
pub fn shuffle<B: Backend, T: Element>(key: &Key<B>, x: &Array<B, T>) -> Array<B, T> {
    key.check_single();
    let shape = x.shape();
    assert!(shape.rank() > 0, "shuffle needs at least one dimension");
    if shape.rank() == 1 {
        return shuffle_leading(key, x.clone());
    }
    // `jnp.take(x, permutation(key, n), axis=0)`. JAX's `take` gathers in
    // the fill mode, which gives the same values for these indices, which
    // are always in bounds.
    let n = shape[0];
    let ind = permutation(key, n).reshape([n, 1]);
    let mut slice_sizes = shape.dims().to_vec();
    slice_sizes[0] = 1;
    let dims = GatherDims {
        offset_dims: (1..shape.rank()).collect(),
        collapsed_slice_dims: vec![0],
        start_index_map: vec![0],
        ..GatherDims::default()
    };
    lax::gather(
        x,
        &ind,
        &dims,
        &slice_sizes,
        GatherScatterMode::PromiseInBounds,
    )
}

#[cfg(test)]
mod threefry_tests {
    use super::*;
    use crate::backend::Native;

    /// The native scalar loop gives the same bits as the generic
    /// implementation (which gives JAX's IR).
    #[test]
    fn native_threefry_matches_the_generic_one() {
        let counts: Vec<u32> = (0..64u32).map(|i| i.wrapping_mul(0x9E37_79B9)).collect();
        for (k1, k2) in [
            (0u32, 0u32),
            (1, 2),
            (0xDEAD_BEEF, 0x1234_5678),
            (u32::MAX, 7),
        ] {
            let k1 = Array::<Native, u32>::from_vec(vec![k1], Shape::scalar());
            let k2 = Array::<Native, u32>::from_vec(vec![k2], Shape::scalar());
            let x1 = Array::<Native, u32>::from_vec(counts.clone(), [64]);
            let x2 = Array::<Native, u32>::from_vec(counts.iter().rev().copied().collect(), [64]);
            let fast = threefry2x32(&k1, &k2, &x1, &x2);
            let generic = threefry2x32_generic(&k1, &k2, &x1, &x2);
            assert_eq!(fast.0.to_vec(), generic.0.to_vec());
            assert_eq!(fast.1.to_vec(), generic.1.to_vec());
        }
    }
}

#[cfg(test)]
mod batched_tests {
    use super::*;
    use crate::backend::{Native, Trace};
    use crate::{bf16, vmap};

    fn check<T: Float>(lo: f64, hi: f64) {
        let keys = split(&key::<Native>(11), 6);
        let (lo, hi) = (
            Scalar::<Native, T>::new(cast(lo)),
            Scalar::<Native, T>::new(cast(hi)),
        );
        let bits =
            |a: &Array<Native, T>| a.to_vec().iter().map(|v| v.to_bits()).collect::<Vec<_>>();
        for shape in [vec![], vec![4], vec![2, 3]] {
            let shape = Shape::from(shape);
            let batched = batched_uniform(&keys, shape.clone(), lo, hi);
            let mut dims = vec![6];
            dims.extend_from_slice(&shape);
            assert_eq!(batched.shape().dims(), &dims[..]);
            // The same numbers as JAX's `vmap` of `uniform` (ruxla's `vmap`
            // of the traced program), and as `uniform` key by key.
            let examples: Vec<Key<Native>> = (0..6).map(|i| keys.get(i)).collect();
            let (l, h) = (lo.value(), hi.value());
            let s = shape.clone();
            let vmapped =
                vmap(move |k: Key<Trace>| uniform::<Trace, T>(&k, s.clone(), l, h)).call(&examples);
            let n = shape.size();
            let got = bits(&batched);
            for (i, k) in examples.iter().enumerate() {
                let one = uniform(k, shape.clone(), lo, hi);
                assert_eq!(
                    got[i * n..(i + 1) * n],
                    bits(&one),
                    "{} [{shape}]",
                    T::DTYPE
                );
                assert_eq!(bits(&vmapped[i]), bits(&one), "{} [{shape}]", T::DTYPE);
            }
            // Traced and interpreted, the same numbers.
            let s = shape.clone();
            let traced = crate::transform::trace(
                move |k: Key<Trace>| batched_uniform::<Trace, T>(&k, s, l, h),
                &keys,
            );
            let outs = ruxla_interp::eval(&traced.function, &crate::tree::leaves(&keys))
                .unwrap_or_else(|e| panic!("{e}"));
            let interpreted = Array::<Native, T>(Native::leaf_array::<T>(outs[0].clone()));
            assert_eq!(bits(&interpreted), got, "{} [{shape}]", T::DTYPE);
        }
        // Two batch dimensions.
        let grid = Key::<Native>::from_data(keys.data().reshape([2, 3, 2]));
        let batched = batched_uniform(&grid, [5], lo, hi);
        assert_eq!(batched.shape().dims(), &[2, 3, 5]);
        let flat = batched_uniform(&keys, [5], lo, hi);
        assert_eq!(bits(&batched), bits(&flat));
    }

    #[test]
    fn batched_uniform_is_the_vmap_of_uniform() {
        check::<f32>(0.0, 1.0);
        check::<f32>(-2.0, 3.0);
        check::<f64>(0.0, 1.0);
        check::<bf16>(-1.0, 1.0);
    }

    #[test]
    #[should_panic(expected = "array of keys")]
    fn batched_uniform_needs_an_array_of_keys() {
        let _ = batched_uniform::<Native, f32>(&key(0), [2], 0.0, 1.0);
    }
}

#[cfg(test)]
mod native_override_tests {
    use super::*;
    use crate::backend::Native;
    use crate::{bf16, f16};

    fn check_uniform<T: Float>(lo: f64, hi: f64) {
        let key = key::<Native>(3);
        let (lo, hi) = (
            Scalar::<Native, T>::new(cast(lo)),
            Scalar::<Native, T>::new(cast(hi)),
        );
        for shape in [vec![], vec![7], vec![3, 5]] {
            let shape = Shape::from(shape);
            let fast = uniform(&key, shape.clone(), lo, hi);
            let generic = uniform_generic(&key, &shape, lo.to_array(), hi.to_array());
            let bits =
                |a: &Array<Native, T>| a.to_vec().iter().map(|v| v.to_bits()).collect::<Vec<_>>();
            assert_eq!(bits(&fast), bits(&generic), "{} [{shape}]", T::DTYPE);
        }
    }

    fn check_randint<T: Int>(lo: i64, hi: i64) {
        let key = key::<Native>(5);
        let (lo, hi) = (
            Scalar::<Native, T>::new(cast(lo)),
            Scalar::<Native, T>::new(cast(hi)),
        );
        for shape in [vec![], vec![9], vec![2, 4]] {
            let shape = Shape::from(shape);
            let fast = randint(&key, shape.clone(), lo, hi);
            let generic = randint_generic(&key, &shape, lo.to_array(), hi.to_array());
            assert_eq!(fast.to_vec(), generic.to_vec(), "{} [{shape}]", T::DTYPE);
        }
    }

    /// The native implementations of `uniform` and `randint` give the same
    /// bits as the generic ones (which give JAX's IR).
    #[test]
    fn native_random_matches_the_generic_one() {
        check_uniform::<f32>(-0.05, 0.05);
        check_uniform::<f32>(0.0, 1.0);
        check_uniform::<f64>(-3.0, 2.0);
        check_uniform::<f16>(0.0, 1.0);
        check_uniform::<bf16>(-1.0, 1.0);
        check_randint::<i32>(0, 5);
        check_randint::<i32>(-7, 3);
        check_randint::<i32>(4, 4);
        check_randint::<i32>(i32::MIN.into(), i32::MAX.into());
        check_randint::<u8>(1, 200);
        check_randint::<i64>(-1_000_000_007, 1_000_000_007);
        check_randint::<u16>(0, 3);
    }
}