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
//! The distributions of `jax.random` built on `uniform`, `normal`, and the
//! key operations, written with the same operations in the same order as
//! JAX (`jax._src.random.core`), so that they give the same numbers.

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

use super::{Key, bernoulli, gumbel, normal, randint, shuffle, split, split2, tiny, uniform};
use crate::backend::Backend;
use crate::jnp;
use crate::lax;
use crate::value::{Array, ArrayLike, Float, Int, Num, Scalar};

/// A constant of type `T`.
fn c<B: Backend, T: Float>(v: f64) -> Scalar<B, T> {
    Scalar::new(cast::<f64, T>(v))
}

/// `finfo(T).eps`.
fn eps<T: Float>() -> f64 {
    match T::DTYPE {
        DType::F16 => 2f64.powi(-10),
        DType::BF16 => 2f64.powi(-7),
        DType::F32 => 2f64.powi(-23),
        _ => 2f64.powi(-52),
    }
}

/// `finfo(T).epsneg`.
fn epsneg<T: Float>() -> f64 {
    eps::<T>() / 2.0
}

fn zero<B: Backend, T: Float>() -> Scalar<B, T> {
    c(0.0)
}

fn one<B: Backend, T: Float>() -> Scalar<B, T> {
    c(1.0)
}

fn is_nan<B: Backend, T: Float>(x: &Array<B, T>) -> Array<B, bool> {
    x.ne(x)
}

fn is_inf<B: Backend, T: Float>(x: &Array<B, T>) -> Array<B, bool> {
    x.abs().eq(c::<B, T>(f64::INFINITY))
}

/// Exponential random floats with rate 1 (`jax.random.exponential`).
#[track_caller]
pub fn exponential<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
    let u = uniform(key, shape, zero::<B, T>(), one::<B, T>());
    // 1 - u moves the domain of log to (0, 1].
    -jnp::log1p(-u)
}

/// Laplace random floats (`jax.random.laplace`).
#[track_caller]
pub fn laplace<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
    let u = uniform(key, shape, c::<B, T>(-1.0 + epsneg::<T>()), one::<B, T>());
    u.sign() * jnp::log1p(-u.abs())
}

/// Logistic random floats (`jax.random.logistic`).
#[track_caller]
pub fn logistic<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
    let x = uniform(key, shape, Scalar::<B, T>::new(tiny::<T>()), one::<B, T>());
    jnp::log(&x) - jnp::log1p(-&x)
}

/// Cauchy random floats (`jax.random.cauchy`).
#[track_caller]
pub fn cauchy<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
    let u = uniform(key, shape, c::<B, T>(eps::<T>()), one::<B, T>());
    jnp::tan(c::<B, T>(std::f64::consts::PI) * (u - c::<B, T>(0.5)))
}

/// Pareto random floats with shape `b` (`jax.random.pareto`).
#[track_caller]
pub fn pareto<B: Backend, T: Float>(
    key: &Key<B>,
    b: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    let e = exponential::<B, T>(key, shape);
    jnp::exp(e / b.into_array())
}

/// Weibull random floats (`jax.random.weibull_min`).
#[track_caller]
pub fn weibull_min<B: Backend, T: Float>(
    key: &Key<B>,
    scale: impl ArrayLike<B, T>,
    concentration: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    let u = uniform(key, shape, zero::<B, T>(), one::<B, T>());
    let e = -jnp::log1p(-u);
    let k = one::<B, T>() / concentration.into_array();
    jnp::power(e, k) * scale.into_array()
}

/// Random signs: -1 or 1 with equal probability (`jax.random.rademacher`).
#[track_caller]
pub fn rademacher<B: Backend, T: Num>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
    let half = Scalar::<B, f32>::new(0.5);
    let b = bernoulli(key, half, shape).cast::<T>();
    let two = Scalar::<B, T>::new(cast::<u8, T>(2));
    let one = Scalar::<B, T>::new(cast::<u8, T>(1));
    two * b - one
}

/// Maxwell random floats (`jax.random.maxwell`): the norms of standard
/// normal vectors of three elements.
#[track_caller]
pub fn maxwell<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
    let shape = shape.into();
    let mut dims = shape.dims().to_vec();
    dims.push(3);
    let x = normal::<B, T>(key, dims);
    jnp::sqrt(lax::reduce_sum(&(&x * &x), &[shape.rank()]))
}

/// Double-sided Maxwell random floats with location `loc` and scale
/// `scale` (`jax.random.double_sided_maxwell`).
#[track_caller]
pub fn double_sided_maxwell<B: Backend, T: Float>(
    key: &Key<B>,
    loc: impl Into<Scalar<B, T>>,
    scale: impl Into<Scalar<B, T>>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    let shape = shape.into();
    let (maxwell_key, rademacher_key) = split2(key);
    let maxwell_rvs = maxwell::<B, T>(&maxwell_key, shape.clone());
    let random_sign = rademacher::<B, T>(&rademacher_key, shape);
    random_sign * maxwell_rvs * scale.into() + loc.into()
}

/// `nextafter(x, +inf)` (or toward `-inf`), as XLA expands
/// `chlo.next_after`. NaN stays NaN.
fn next_after<B: Backend, T: Float>(x: &Array<B, T>, up: bool) -> Array<B, T> {
    match T::DTYPE.size_in_bytes() {
        2 => next_after_with::<B, T, u16>(x, up),
        4 => next_after_with::<B, T, u32>(x, up),
        _ => next_after_with::<B, T, u64>(x, up),
    }
}

fn next_after_with<B: Backend, T: Float, U: Int>(x: &Array<B, T>, up: bool) -> Array<B, T> {
    let bits = lax::bitcast_convert_type::<B, T, U>(x);
    let nbits = U::DTYPE.size_in_bytes() * 8;
    let u = |v: u64| Scalar::<B, U>::new(cast::<u64, U>(v));
    let sign = u(1 << (nbits - 1));
    let is_zero = (&bits & !sign).eq(u(0));
    let negative = (&bits & sign).ne(u(0));
    // Away from zero when moving in the direction of the sign.
    let away = if up { !&negative } else { negative };
    let next = jnp::where_(away, &bits + u(1), &bits - u(1));
    let smallest = if up { u(1) } else { u((1 << (nbits - 1)) | 1) };
    let next = jnp::where_(is_zero, smallest, next);
    let target = c::<B, T>(if up { f64::INFINITY } else { f64::NEG_INFINITY });
    let out = lax::bitcast_convert_type::<B, U, T>(&next);
    jnp::where_(x.eq(target) | is_nan(x), x, out)
}

/// Standard normal random floats truncated to `(lower, upper)`
/// (`jax.random.truncated_normal`).
#[track_caller]
pub fn truncated_normal<B: Backend, T: Float>(
    key: &Key<B>,
    lower: impl ArrayLike<B, T>,
    upper: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    let (lower, upper) = (lower.into_array(), upper.into_array());
    let sqrt2 = c::<B, T>(std::f64::consts::SQRT_2);
    let a = lax::erf(&(&lower / sqrt2));
    let b = lax::erf(&(&upper / sqrt2));
    let u = uniform(key, shape, a, b);
    let out = sqrt2 * lax::erf_inv(&u);
    let lo = next_after(&lower, true);
    let hi = next_after(&upper, false);
    jnp::minimum(hi, jnp::maximum(lo, out))
}

/// The carry of the outer loop of [`gamma_one`]: the key, `X`, `V`, `U`.
type GammaState<B, T> = (Key<B>, Array<B, T>, Array<B, T>, Array<B, T>);

/// One sample of `Gamma(alpha, 1)` (or its logarithm) by Marsaglia and
/// Tsang's method, as JAX's `_gamma_one`.
fn gamma_one<B: Backend, T: Float>(
    key: Key<B>,
    alpha: Array<B, T>,
    log_space: bool,
) -> Array<B, T> {
    let zero = zero::<B, T>();
    let one = one::<B, T>();
    let minus_one = c::<B, T>(-1.0);
    let two = c::<B, T>(2.0);
    let one_over_two = c::<B, T>(0.5);
    let one_over_three = c::<B, T>(1.0 / 3.0);
    let squeeze_const = c::<B, T>(0.0331);

    // For alpha < 1, Gamma(alpha) ~ Gamma(alpha + 1) * Uniform()^(1 / alpha).
    let boost_mask = alpha.ge(one);
    let alpha_orig = alpha.clone();
    let alpha = jnp::where_(&boost_mask, &alpha, &alpha + one);
    let d = &alpha - one_over_three;
    let cc = one_over_three / jnp::sqrt(&d);

    let (key, subkey) = split2(&key);
    let init = (key, zero.to_array(), one.to_array(), two.to_array());
    let (_, _, v, _) = lax::while_loop(
        |(_, x, v, u): &GammaState<B, T>| {
            let a = u.ge(one - squeeze_const * (x * x));
            let b = jnp::log(u).ge(x * one_over_two + &d * ((one - v) + jnp::log(v)));
            (a & b).to_scalar()
        },
        |(key, _, _, _)| {
            let keys = split(&key, 3);
            let (key, x_key, u_key) = (keys.get(0), keys.get(1), keys.get(2));
            let (_, x, v) = lax::while_loop(
                |(_, _, v): &(Key<B>, Array<B, T>, Array<B, T>)| v.le(zero).to_scalar(),
                |(key, _, _)| {
                    let (key, subkey) = split2(&key);
                    let x = normal::<B, T>(&subkey, Shape::scalar());
                    let v = one + &x * &cc;
                    (key, x, v)
                },
                (x_key, zero.to_array(), minus_one.to_array()),
            );
            let big_x = &x * &x;
            let big_v = &(&v * &v) * &v;
            let u = uniform(&u_key, Shape::scalar(), zero, one);
            (key, big_x, big_v, u)
        },
        init,
    );
    if log_space {
        let log_samples = -exponential::<B, T>(&subkey, Shape::scalar());
        let skip = &boost_mask | log_samples.eq(zero);
        let log_boost = jnp::where_(skip, zero, &log_samples * (one / &alpha_orig));
        jnp::log(&d) + jnp::log(&v) + log_boost
    } else {
        let samples = one - uniform(&subkey, Shape::scalar(), zero, one);
        let boost = jnp::where_(&boost_mask, one, jnp::power(samples, one / &alpha_orig));
        &d * &v * boost
    }
}

/// `random_gamma_p` of JAX: a sample per element of `a`, each from its own
/// key of `split(key, a.size())`.
fn gamma_impl<B: Backend, T: Float>(key: &Key<B>, a: &Array<B, T>, log_space: bool) -> Array<B, T> {
    let shape = a.shape();
    let n = shape.size();
    let keys = split(key, n);
    let alphas = a.reshape([n]);
    let (_, samples) = lax::scan(
        |(), (k, alpha): (Key<B>, Array<B, T>)| ((), gamma_one(k, alpha, log_space)),
        (),
        (keys, alphas),
        n,
    );
    samples.reshape(shape)
}

/// The derivative of samples with respect to `a`, as JAX's `_gamma_grad`.
fn gamma_grad<B: Backend, T: Float>(
    sample: &Array<B, T>,
    a: &Array<B, T>,
    log_space: bool,
) -> Array<B, T> {
    if log_space {
        // d[log(sample)] = d[sample] / sample, with exp(log_sample) = 0
        // replaced by the smallest normal number.
        let samples = jnp::exp(sample);
        let samples = jnp::where_(
            samples.eq(zero::<B, T>()),
            Scalar::<B, T>::new(tiny::<T>()),
            &samples,
        );
        lax::random_gamma_grad(a, &samples) / samples
    } else {
        lax::random_gamma_grad(a, sample)
    }
}

/// `gamma` and `loggamma`: the samples with JAX's derivative with respect
/// to `a`.
fn gamma_sample<B: Backend, T: Float>(
    key: &Key<B>,
    a: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
    log_space: bool,
) -> Array<B, T> {
    key.check_single();
    let a = a.into_array().broadcast_to(shape);
    lax::custom_jvp(
        |a: Array<B, T>| gamma_impl(key, &a, log_space),
        |a: Array<B, T>, a_dot: Array<B, T>| {
            let ans = gamma_impl(key, &a, log_space);
            let t = a_dot * gamma_grad(&ans, &a, log_space);
            (ans, t)
        },
        a,
    )
}

/// Gamma random floats with shape `a` and rate 1 (`jax.random.gamma`),
/// differentiable with respect to `a`.
#[track_caller]
pub fn gamma<B: Backend, T: Float>(
    key: &Key<B>,
    a: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    gamma_sample(key, a, shape, false)
}

/// The logarithms of gamma random floats (`jax.random.loggamma`), accurate
/// for small `a`.
#[track_caller]
pub fn loggamma<B: Backend, T: Float>(
    key: &Key<B>,
    a: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    gamma_sample(key, a, shape, true)
}

/// Beta random floats (`jax.random.beta`).
#[track_caller]
pub fn beta<B: Backend, T: Float>(
    key: &Key<B>,
    a: impl ArrayLike<B, T>,
    b: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    let shape = shape.into();
    let (key_a, key_b) = split2(key);
    let log_gamma_a = loggamma(&key_a, a, shape.clone());
    let log_gamma_b = loggamma(&key_b, b, shape);
    // gamma_a / (gamma_a + gamma_b) without losing precision.
    let log_max = jnp::maximum(&log_gamma_a, &log_gamma_b);
    let gamma_a_scaled = jnp::exp(log_gamma_a - &log_max);
    let gamma_b_scaled = jnp::exp(log_gamma_b - &log_max);
    &gamma_a_scaled / (&gamma_a_scaled + gamma_b_scaled)
}

/// Dirichlet random floats (`jax.random.dirichlet`): `alpha` has shape
/// `[..., k]`, and the result has shape `batch_shape + [k]`.
#[track_caller]
pub fn dirichlet<B: Backend, T: Float>(
    key: &Key<B>,
    alpha: &Array<B, T>,
    batch_shape: impl Into<Shape>,
) -> Array<B, T> {
    let k = *alpha
        .shape()
        .last()
        .expect("dirichlet needs alpha.ndim >= 1");
    let mut dims = batch_shape.into().dims().to_vec();
    dims.push(k);
    let x = loggamma(key, alpha, dims);
    // `jax.nn.softmax` along the last axis.
    let axis = x.ndim() - 1;
    let keep = |a: Array<B, T>| {
        let mut s = a.shape().dims().to_vec();
        s.push(1);
        a.reshape(s)
    };
    let x_max = keep(lax::reduce_max(&x, &[axis]));
    let unnormalized = jnp::exp(x - x_max);
    let sum = keep(lax::reduce_sum(&unnormalized, &[axis]));
    unnormalized / sum
}

/// Student's t random floats with `df` degrees of freedom (`jax.random.t`).
#[track_caller]
pub fn t<B: Backend, T: Float>(
    key: &Key<B>,
    df: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    let shape = shape.into();
    let (key_n, key_g) = split2(key);
    let n = normal::<B, T>(&key_n, shape.clone());
    let half_df = df.into_array() / c::<B, T>(2.0);
    let g = gamma(&key_g, &half_df, shape);
    n * jnp::sqrt(half_df / g)
}

/// Chi-square random floats with `df` degrees of freedom
/// (`jax.random.chisquare`).
#[track_caller]
pub fn chisquare<B: Backend, T: Float>(
    key: &Key<B>,
    df: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    let two = c::<B, T>(2.0);
    let half_df = df.into_array() / two;
    let log_g = loggamma(key, half_df, shape);
    jnp::exp(log_g) * two
}

/// F random floats (`jax.random.f`).
#[track_caller]
pub fn f<B: Backend, T: Float>(
    key: &Key<B>,
    dfnum: impl ArrayLike<B, T>,
    dfden: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    let shape = shape.into();
    let (dfnum, dfden) = (dfnum.into_array(), dfden.into_array());
    let (key_dfd, key_dfn) = split2(key);
    let chi2_dfn = chisquare(&key_dfn, &dfnum, shape.clone());
    let chi2_dfd = chisquare(&key_dfd, &dfden, shape);
    (chi2_dfn / dfnum) / (chi2_dfd / dfden)
}

/// The carry of [`poisson_knuth`]: the iteration, the counts, the key, and
/// the log of the product of uniforms.
type KnuthState<B, T> = (Scalar<B, i32>, Array<B, T>, Key<B>, Array<B, f32>);

/// The carry of [`poisson_rejection`]: the iteration, the samples, whether
/// they are accepted, and the key.
type RejectionState<B> = (Scalar<B, i32>, Array<B, f32>, Array<B, bool>, Key<B>);

/// Poisson by Knuth's algorithm, for small rates.
fn poisson_knuth<B: Backend, T: Int>(
    key: &Key<B>,
    lam: &Array<B, f32>,
    shape: &Shape,
    max_iters: i32,
) -> Array<B, T> {
    let one = Scalar::<B, T>::new(cast::<u8, T>(1));
    let k_init = jnp::zeros::<B, T>(shape.clone());
    let log_rate_init = jnp::zeros::<B, f32>(shape.clone());
    let neg_lam = -lam;
    let (_, k, _, _) = lax::while_loop(
        |(i, _, _, log_prod): &KnuthState<B, T>| {
            let any = jnp::any(log_prod.gt(&neg_lam), crate::jnp::ALL).to_scalar();
            any & i.lt(max_iters)
        },
        |(i, k, rng, log_prod)| {
            let (rng, subkey) = split2(&rng);
            let k = jnp::where_(log_prod.gt(&neg_lam), &k + one, &k);
            let u = uniform(
                &subkey,
                shape.clone(),
                Scalar::<B, f32>::new(0.0),
                Scalar::new(1.0),
            );
            (i + 1, k, rng, log_prod + jnp::log(u))
        },
        (Scalar::new(0), k_init, key.clone(), log_rate_init),
    );
    k - one
}

/// Poisson by Hormann's transformed rejection, for large rates.
fn poisson_rejection<B: Backend, T: Int>(
    key: &Key<B>,
    lam: &Array<B, f32>,
    shape: &Shape,
    max_iters: i32,
) -> Array<B, T> {
    let f = Scalar::<B, f32>::new;
    let log_lam = jnp::log(lam);
    let b = f(0.931) + f(2.53) * jnp::sqrt(lam);
    let a = f(-0.059) + f(0.02483) * &b;
    let inv_alpha = f(1.1239) + f(1.1328) / (&b - f(3.4));
    let v_r = f(0.9277) - f(3.6224) / (&b - f(2.0));
    let k_init = jnp::full::<B, f32>(shape.clone(), -1.0);
    let accepted = jnp::full::<B, bool>(shape.clone(), false);
    let (_, k, _, _) = lax::while_loop(
        |(i, _, accepted, _): &RejectionState<B>| {
            jnp::any(!accepted, crate::jnp::ALL).to_scalar() & i.lt(max_iters)
        },
        |(i, k_out, accepted, key)| {
            let keys = split(&key, 3);
            let (key, subkey_0, subkey_1) = (keys.get(0), keys.get(1), keys.get(2));
            let u = uniform(&subkey_0, shape.clone(), f(0.0), f(1.0)) - f(0.5);
            let v = uniform(&subkey_1, shape.clone(), f(0.0), f(1.0));
            let u_shifted = f(0.5) - u.abs();
            let k = jnp::floor((f(2.0) * &a / &u_shifted + &b) * &u + lam + f(0.43));
            let s = jnp::log(&v * &inv_alpha / (&a / (&u_shifted * &u_shifted) + &b));
            let t = -lam + &k * &log_lam - lax::lgamma(&(&k + f(1.0)));
            let accept1 = u_shifted.ge(f(0.07)) & v.le(&v_r);
            let reject = k.lt(f(0.0)) | (u_shifted.lt(f(0.013)) & v.gt(&u_shifted));
            let accept2 = s.le(&t);
            let accept = accept1 | (!reject & accept2);
            let k_out = jnp::where_(&accept, &k, &k_out);
            let accepted = accepted | accept;
            (i + 1, k_out, accepted, key)
        },
        (Scalar::new(0), k_init, accepted, key.clone()),
    );
    k.cast::<T>()
}

/// Poisson random integers with rate `lam` (`jax.random.poisson`).
#[track_caller]
pub fn poisson<B: Backend, T: Int>(
    key: &Key<B>,
    lam: impl ArrayLike<B, f32>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    key.check_single();
    let shape = shape.into();
    let lam = lam.into_array().broadcast_to(shape.clone());
    let use_knuth = is_nan(&lam) | lam.lt(Scalar::new(10.0));
    let lam_knuth = jnp::where_(&use_knuth, &lam, Scalar::<B, f32>::new(0.0));
    let lam_rejection = jnp::where_(&use_knuth, Scalar::<B, f32>::new(1e5), &lam);
    // JAX's `iinfo(dtype).max`, an insanely conservative bound.
    let max_iters = match T::DTYPE.size_in_bytes() {
        1 => i32::from(i8::MAX),
        2 => i32::from(i16::MAX),
        _ => i32::MAX,
    };
    let result = jnp::where_(
        use_knuth,
        poisson_knuth::<B, T>(key, &lam_knuth, &shape, max_iters),
        poisson_rejection::<B, T>(key, &lam_rejection, &shape, max_iters),
    );
    jnp::where_(lam.eq(Scalar::new(0.0)), jnp::zeros::<B, T>(shape), result)
}

/// JAX's `_stirling_approx_tail`: the tail of Stirling's series for
/// `log(k!)`, from a table for `k <= 9`.
fn stirling_approx_tail<B: Backend, T: Float>(k: &Array<B, T>) -> Array<B, T> {
    const TAIL: [f64; 10] = [
        0.081_061_466_795_327_2,
        0.041_340_695_955_409_2,
        0.027_677_925_684_998_3,
        0.020_790_672_103_765_09,
        0.016_644_691_189_821_1,
        0.013_876_128_823_070_7,
        0.011_896_709_945_891_7,
        0.010_411_265_261_972,
        0.009_255_462_182_712_73,
        0.008_330_563_433_362_87,
    ];
    let use_tail_values = k.le(c::<B, T>(9.0));
    let k = lax::clamp(&c::<B, T>(0.0).to_array(), k, &c::<B, T>(9.0).to_array());
    let k1 = &k + c::<B, T>(1.0);
    let kp1sq = &k1 * &k1;
    let inner = c::<B, T>(1.0 / 360.0) - c::<B, T>(1.0 / 1260.0) / &kp1sq;
    let approx = (c::<B, T>(1.0 / 12.0) - inner / &kp1sq) / k1;
    let k = jnp::floor(&k);
    let mut table = c::<B, T>(TAIL[0]).to_array().broadcast_to(k.shape());
    for (j, &v) in TAIL.iter().enumerate().skip(1) {
        table = jnp::where_(k.eq(c::<B, T>(j as f64)), c::<B, T>(v), table);
    }
    jnp::where_(use_tail_values, table, approx)
}

/// Binomial by inversion (sums of geometric variables), for small means.
fn binomial_inversion<B: Backend, T: Float>(
    key: &Key<B>,
    count: &Array<B, T>,
    prob: &Array<B, T>,
    shape: &Shape,
) -> Array<B, T> {
    let log1minusprob = jnp::log1p(-prob);
    let init = (
        jnp::zeros::<B, T>(shape.clone()),
        jnp::zeros::<B, T>(shape.clone()),
        key.clone(),
    );
    let (num_geom, _, _) = lax::while_loop(
        |(_, geom_sum, _): &(Array<B, T>, Array<B, T>, Key<B>)| {
            jnp::any(geom_sum.le(count), crate::jnp::ALL).to_scalar()
        },
        |(num_geom, geom_sum, key)| {
            let (subkey, key) = split2(&key);
            let num_geom_out =
                jnp::where_(geom_sum.le(count), &num_geom + one::<B, T>(), &num_geom);
            let u = uniform(&subkey, shape.clone(), zero::<B, T>(), one::<B, T>());
            let geom = jnp::ceil(jnp::log(u) / &log1minusprob);
            (num_geom_out, geom_sum + geom, key)
        },
        init,
    );
    num_geom - one::<B, T>()
}

/// Binomial by the BTRS transformed rejection, for large means.
fn btrs<B: Backend, T: Float>(
    key: &Key<B>,
    count: &Array<B, T>,
    prob: &Array<B, T>,
    shape: &Shape,
) -> Array<B, T> {
    let f = c::<B, T>;
    let stddev = jnp::sqrt(count * prob * (f(1.0) - prob));
    let b = f(1.15) + f(2.53) * &stddev;
    let a = f(-0.0873) + f(0.0248) * &b + f(0.01) * prob;
    let cc = count * prob + f(0.5);
    let v_r = f(0.92) - f(4.2) / &b;
    let r = prob / (f(1.0) - prob);
    let alpha = (f(2.83) + f(5.1) / &b) * &stddev;
    let m = jnp::floor((count + f(1.0)) * prob);
    let st_m = stirling_approx_tail(&m);
    let st_count_m = stirling_approx_tail(&(count - &m));
    let k_init = jnp::full::<B, T>(shape.clone(), cast::<f64, T>(-1.0));
    let accepted = jnp::full::<B, bool>(shape.clone(), false);
    let (k, _, _) = lax::while_loop(
        |(_, accepted, _): &(Array<B, T>, Array<B, bool>, Key<B>)| {
            jnp::any(!accepted, crate::jnp::ALL).to_scalar()
        },
        |(k_out, accepted, key)| {
            let keys = split(&key, 3);
            let (key, subkey_0, subkey_1) = (keys.get(0), keys.get(1), keys.get(2));
            let u = uniform(&subkey_0, shape.clone(), f(0.0), f(1.0));
            let v = uniform(&subkey_1, shape.clone(), f(0.0), f(1.0));
            let u = u - f(0.5);
            let us = f(0.5) - u.abs();
            let accept1 = us.ge(f(0.07)) & v.le(&v_r);
            let k = jnp::floor((f(2.0) * &a / &us + &b) * &u + &cc);
            let reject = k.lt(f(0.0)) | k.gt(count);
            let v = jnp::log(v * &alpha / (&a / (&us * &us) + &b));
            let count_m1 = count - &m + f(1.0);
            let count_k1 = count - &k + f(1.0);
            let ub = (&m + f(0.5)) * jnp::log((&m + f(1.0)) / (&r * &count_m1))
                + (count + f(1.0)) * jnp::log(&count_m1 / &count_k1)
                + (&k + f(0.5)) * jnp::log(&r * &count_k1 / (&k + f(1.0)))
                + &st_m
                + &st_count_m
                - stirling_approx_tail(&k)
                - stirling_approx_tail(&(count - &k));
            let accept2 = v.le(&ub);
            let accept = accept1 | (!reject & accept2);
            let k_out = jnp::where_(&accept, &k, &k_out);
            (k_out, accepted | accept, key)
        },
        (k_init, accepted, key.clone()),
    );
    k
}

/// Binomial random floats: the number of successes in `n` trials of
/// probability `p` (`jax.random.binomial`).
#[track_caller]
pub fn binomial<B: Backend, T: Float>(
    key: &Key<B>,
    n: impl ArrayLike<B, T>,
    p: impl ArrayLike<B, T>,
    shape: impl Into<Shape>,
) -> Array<B, T> {
    key.check_single();
    let f = c::<B, T>;
    let shape = shape.into();
    let count = n.into_array().broadcast_to(shape.clone());
    let prob = p.into_array().broadcast_to(shape.clone());
    let p_lt_half = prob.lt(f(0.5));
    let q = jnp::where_(&p_lt_half, &prob, f(1.0) - &prob);
    let count_nan_or_neg = is_nan(&count) | count.lt(f(0.0));
    let count_inf = is_inf(&count);
    let q_is_nan = is_nan(&q);
    let q_l_0 = q.lt(f(0.0));
    let q = jnp::where_(&q_is_nan | &q_l_0, f(0.01), &q);
    let use_inversion = &count_nan_or_neg | (&count * &q).le(f(10.0));
    let count = jnp::floor(&count);
    let count_inv = jnp::where_(&use_inversion, &count, f(0.0));
    let count_btrs = jnp::where_(&use_inversion, f(1e4), &count);
    let q_btrs = jnp::where_(&use_inversion, f(0.5), &q);
    let samples = jnp::where_(
        &use_inversion,
        binomial_inversion(key, &count_inv, &q, &shape),
        btrs(key, &count_btrs, &q_btrs, &shape),
    );
    let invalid = &q_l_0 | &q_is_nan | &count_nan_or_neg;
    let samples = jnp::where_(&invalid, f(f64::NAN), samples);
    let samples = jnp::where_(&count_inf & !&invalid, f(f64::INFINITY), samples);
    let keep = p_lt_half | count_nan_or_neg | q_is_nan | count_inf;
    jnp::where_(keep, &samples, &count - &samples)
}

/// `jnp.take(x, ind, axis=0)` for indices in bounds: the rows of `x` at
/// `ind` (one-dimensional), stacked.
fn take_rows<B: Backend, T: Element>(x: &Array<B, T>, ind: &Array<B, i32>) -> Array<B, T> {
    let shape = x.shape();
    let m = ind.size();
    let ind = ind.reshape([m, 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,
    )
}

/// The result shape of `choice`: `shape` followed by the shape of an
/// element of `a`.
fn choice_shape<B: Backend, T: Element>(a: &Array<B, T>, shape: &Shape) -> Vec<usize> {
    let mut dims = shape.dims().to_vec();
    dims.extend_from_slice(&a.shape().dims()[1..]);
    dims
}

/// Random elements of `a` along axis 0 (`jax.random.choice` with `p=None`
/// and `axis=0`), with or without replacement. Use `jnp::arange` for the
/// integer form `choice(key, n, ...)`.
///
/// # Panics
///
/// Panics if `a` is a scalar or empty, or if `replace` is false and more
/// elements are drawn than `a` has.
#[track_caller]
pub fn choice<B: Backend, T: Element>(
    key: &Key<B>,
    a: &Array<B, T>,
    shape: impl Into<Shape>,
    replace: bool,
) -> Array<B, T> {
    let shape = shape.into();
    let n_inputs = check_choice(a, &shape, replace);
    let n_draws = shape.size();
    let result = if n_draws == 0 {
        jnp::zeros::<B, T>(choice_shape(a, &shape))
    } else if replace {
        if B::FAST_PATHS && n_draws == 1 {
            // One draw, natively: element 0 of the indices (a scalar
            // `randint` gives the same value), whose row is read directly.
            let i = randint(key, [], 0, n_inputs as i32).to_scalar();
            return a.i(i).reshape(choice_shape(a, &shape));
        }
        let ind = randint(key, [n_draws], 0, n_inputs as i32);
        take_rows(a, &ind)
    } else {
        lax::slice_in_dim(&shuffle(key, a), 0, n_draws, 1, 0)
    };
    result.reshape(choice_shape(a, &shape))
}

#[track_caller]
fn check_choice<B: Backend, T: Element>(a: &Array<B, T>, shape: &Shape, replace: bool) -> usize {
    assert!(
        a.ndim() > 0,
        "choice needs an array of at least one dimension"
    );
    let n_inputs = a.shape()[0];
    let n_draws = shape.size();
    assert!(
        n_draws == 0 || n_inputs > 0,
        "a must be greater than 0 unless no samples are taken"
    );
    assert!(
        replace || n_draws <= n_inputs,
        "cannot take a larger sample (size {n_draws}) than population (size {n_inputs}) \
         when replace is false"
    );
    n_inputs
}

/// Random elements of `a` along axis 0 with probabilities `p`
/// (`jax.random.choice` with `p` and `axis=0`), with or without
/// replacement.
///
/// # Panics
///
/// Panics as [`choice`] does, or if `p` does not have one element per row
/// of `a`.
#[track_caller]
pub fn choice_with_p<B: Backend, T: Element, F: Float>(
    key: &Key<B>,
    a: &Array<B, T>,
    shape: impl Into<Shape>,
    replace: bool,
    p: &Array<B, F>,
) -> Array<B, T> {
    let shape = shape.into();
    let n_inputs = check_choice(a, &shape, replace);
    assert_eq!(
        p.shape().dims(),
        [n_inputs],
        "p must be a vector with one element per row of a"
    );
    let n_draws = shape.size();
    if n_draws == 0 {
        return jnp::zeros::<B, T>(choice_shape(a, &shape));
    }
    if B::FAST_PATHS && replace && n_draws == 1 && a.ndim() == 1 {
        // One draw from a vector, natively: the same sums, uniform number,
        // and count as below, with scalars (element 0 of a uniform vector
        // is the scalar uniform), and the element read directly.
        let mut last = zero::<B, F>();
        for i in 0..n_inputs {
            last = last + p.get(i as i64);
        }
        let u = uniform(key, [], zero::<B, F>(), one::<B, F>()).to_scalar();
        let r = last * (one::<B, F>() - u);
        let (mut cum, mut below) = (zero::<B, F>(), Scalar::<B, i32>::new(0));
        for i in 0..n_inputs {
            cum = cum + p.get(i as i64);
            below = below + r.gt(cum).cast::<i32>();
        }
        return a.i(below).reshape(choice_shape(a, &shape));
    }
    let ind = if replace {
        // `jnp.cumsum`, which XLA computes as a sum from the left.
        let (_, p_cuml) = lax::scan(
            |acc: Array<B, F>, x: Array<B, F>| {
                let s = acc + x;
                (s.clone(), s)
            },
            zero::<B, F>().to_array(),
            p.clone(),
            n_inputs,
        );
        let last = lax::index_in_dim(&p_cuml, n_inputs - 1, 0, false);
        let u = uniform(key, [n_draws], zero::<B, F>(), one::<B, F>());
        let r = last * (one::<B, F>() - u);
        // `jnp.searchsorted(p_cuml, r)`: the number of cumulative sums
        // below each value.
        let below = r.reshape([n_draws, 1]).gt(&p_cuml);
        lax::reduce_sum(&below.cast::<i32>(), &[1])
    } else {
        // The Gumbel top-k trick.
        let g = gumbel::<B, F>(key, [n_inputs]) + jnp::log(p);
        // `lax.top_k`: a stable sort of -g puts the largest first, ties in
        // order of index.
        let (_, order) = lax::sort_key_val(&-g, &lax::iota::<B, i32>([n_inputs], 0), 0);
        lax::slice_in_dim(&order, 0, n_draws, 1, 0)
    };
    take_rows(a, &ind).reshape(choice_shape(a, &shape))
}

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

    #[test]
    fn next_after_steps_one_ulp() {
        let x = Array::<Native, f32>::from_vec(vec![1.0, -1.0, 0.0, -0.0, f32::INFINITY], [5]);
        let up = next_after(&x, true).to_vec();
        assert_eq!(up[0], 1.0f32.next_up());
        assert_eq!(up[1], (-1.0f32).next_up());
        assert_eq!(up[2], f32::from_bits(1));
        assert_eq!(up[3], f32::from_bits(1));
        assert_eq!(up[4], f32::INFINITY);
        let down = next_after(&x, false).to_vec();
        assert_eq!(down[0], 1.0f32.next_down());
        assert_eq!(down[1], (-1.0f32).next_down());
        assert_eq!(down[2], -f32::from_bits(1));
        assert_eq!(down[4], f32::MAX);
    }
}