Skip to main content

ruxla_core/random/
distributions.rs

1//! The distributions of `jax.random` built on `uniform`, `normal`, and the
2//! key operations, written with the same operations in the same order as
3//! JAX (`jax._src.random.core`), so that they give the same numbers.
4
5use ruxla_ir::{DType, GatherDims, GatherScatterMode, Shape};
6use ruxla_kernels::{Element, cast};
7
8use super::{Key, bernoulli, gumbel, normal, randint, shuffle, split, split2, tiny, uniform};
9use crate::backend::Backend;
10use crate::jnp;
11use crate::lax;
12use crate::value::{Array, ArrayLike, Float, Int, Num, Scalar};
13
14/// A constant of type `T`.
15fn c<B: Backend, T: Float>(v: f64) -> Scalar<B, T> {
16    Scalar::new(cast::<f64, T>(v))
17}
18
19/// `finfo(T).eps`.
20fn eps<T: Float>() -> f64 {
21    match T::DTYPE {
22        DType::F16 => 2f64.powi(-10),
23        DType::BF16 => 2f64.powi(-7),
24        DType::F32 => 2f64.powi(-23),
25        _ => 2f64.powi(-52),
26    }
27}
28
29/// `finfo(T).epsneg`.
30fn epsneg<T: Float>() -> f64 {
31    eps::<T>() / 2.0
32}
33
34fn zero<B: Backend, T: Float>() -> Scalar<B, T> {
35    c(0.0)
36}
37
38fn one<B: Backend, T: Float>() -> Scalar<B, T> {
39    c(1.0)
40}
41
42fn is_nan<B: Backend, T: Float>(x: &Array<B, T>) -> Array<B, bool> {
43    x.ne(x)
44}
45
46fn is_inf<B: Backend, T: Float>(x: &Array<B, T>) -> Array<B, bool> {
47    x.abs().eq(c::<B, T>(f64::INFINITY))
48}
49
50/// Exponential random floats with rate 1 (`jax.random.exponential`).
51#[track_caller]
52pub fn exponential<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
53    let u = uniform(key, shape, zero::<B, T>(), one::<B, T>());
54    // 1 - u moves the domain of log to (0, 1].
55    -jnp::log1p(-u)
56}
57
58/// Laplace random floats (`jax.random.laplace`).
59#[track_caller]
60pub fn laplace<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
61    let u = uniform(key, shape, c::<B, T>(-1.0 + epsneg::<T>()), one::<B, T>());
62    u.sign() * jnp::log1p(-u.abs())
63}
64
65/// Logistic random floats (`jax.random.logistic`).
66#[track_caller]
67pub fn logistic<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
68    let x = uniform(key, shape, Scalar::<B, T>::new(tiny::<T>()), one::<B, T>());
69    jnp::log(&x) - jnp::log1p(-&x)
70}
71
72/// Cauchy random floats (`jax.random.cauchy`).
73#[track_caller]
74pub fn cauchy<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
75    let u = uniform(key, shape, c::<B, T>(eps::<T>()), one::<B, T>());
76    jnp::tan(c::<B, T>(std::f64::consts::PI) * (u - c::<B, T>(0.5)))
77}
78
79/// Pareto random floats with shape `b` (`jax.random.pareto`).
80#[track_caller]
81pub fn pareto<B: Backend, T: Float>(
82    key: &Key<B>,
83    b: impl ArrayLike<B, T>,
84    shape: impl Into<Shape>,
85) -> Array<B, T> {
86    let e = exponential::<B, T>(key, shape);
87    jnp::exp(e / b.into_array())
88}
89
90/// Weibull random floats (`jax.random.weibull_min`).
91#[track_caller]
92pub fn weibull_min<B: Backend, T: Float>(
93    key: &Key<B>,
94    scale: impl ArrayLike<B, T>,
95    concentration: impl ArrayLike<B, T>,
96    shape: impl Into<Shape>,
97) -> Array<B, T> {
98    let u = uniform(key, shape, zero::<B, T>(), one::<B, T>());
99    let e = -jnp::log1p(-u);
100    let k = one::<B, T>() / concentration.into_array();
101    jnp::power(e, k) * scale.into_array()
102}
103
104/// Random signs: -1 or 1 with equal probability (`jax.random.rademacher`).
105#[track_caller]
106pub fn rademacher<B: Backend, T: Num>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
107    let half = Scalar::<B, f32>::new(0.5);
108    let b = bernoulli(key, half, shape).cast::<T>();
109    let two = Scalar::<B, T>::new(cast::<u8, T>(2));
110    let one = Scalar::<B, T>::new(cast::<u8, T>(1));
111    two * b - one
112}
113
114/// Maxwell random floats (`jax.random.maxwell`): the norms of standard
115/// normal vectors of three elements.
116#[track_caller]
117pub fn maxwell<B: Backend, T: Float>(key: &Key<B>, shape: impl Into<Shape>) -> Array<B, T> {
118    let shape = shape.into();
119    let mut dims = shape.dims().to_vec();
120    dims.push(3);
121    let x = normal::<B, T>(key, dims);
122    jnp::sqrt(lax::reduce_sum(&(&x * &x), &[shape.rank()]))
123}
124
125/// Double-sided Maxwell random floats with location `loc` and scale
126/// `scale` (`jax.random.double_sided_maxwell`).
127#[track_caller]
128pub fn double_sided_maxwell<B: Backend, T: Float>(
129    key: &Key<B>,
130    loc: impl Into<Scalar<B, T>>,
131    scale: impl Into<Scalar<B, T>>,
132    shape: impl Into<Shape>,
133) -> Array<B, T> {
134    let shape = shape.into();
135    let (maxwell_key, rademacher_key) = split2(key);
136    let maxwell_rvs = maxwell::<B, T>(&maxwell_key, shape.clone());
137    let random_sign = rademacher::<B, T>(&rademacher_key, shape);
138    random_sign * maxwell_rvs * scale.into() + loc.into()
139}
140
141/// `nextafter(x, +inf)` (or toward `-inf`), as XLA expands
142/// `chlo.next_after`. NaN stays NaN.
143fn next_after<B: Backend, T: Float>(x: &Array<B, T>, up: bool) -> Array<B, T> {
144    match T::DTYPE.size_in_bytes() {
145        2 => next_after_with::<B, T, u16>(x, up),
146        4 => next_after_with::<B, T, u32>(x, up),
147        _ => next_after_with::<B, T, u64>(x, up),
148    }
149}
150
151fn next_after_with<B: Backend, T: Float, U: Int>(x: &Array<B, T>, up: bool) -> Array<B, T> {
152    let bits = lax::bitcast_convert_type::<B, T, U>(x);
153    let nbits = U::DTYPE.size_in_bytes() * 8;
154    let u = |v: u64| Scalar::<B, U>::new(cast::<u64, U>(v));
155    let sign = u(1 << (nbits - 1));
156    let is_zero = (&bits & !sign).eq(u(0));
157    let negative = (&bits & sign).ne(u(0));
158    // Away from zero when moving in the direction of the sign.
159    let away = if up { !&negative } else { negative };
160    let next = jnp::where_(away, &bits + u(1), &bits - u(1));
161    let smallest = if up { u(1) } else { u((1 << (nbits - 1)) | 1) };
162    let next = jnp::where_(is_zero, smallest, next);
163    let target = c::<B, T>(if up { f64::INFINITY } else { f64::NEG_INFINITY });
164    let out = lax::bitcast_convert_type::<B, U, T>(&next);
165    jnp::where_(x.eq(target) | is_nan(x), x, out)
166}
167
168/// Standard normal random floats truncated to `(lower, upper)`
169/// (`jax.random.truncated_normal`).
170#[track_caller]
171pub fn truncated_normal<B: Backend, T: Float>(
172    key: &Key<B>,
173    lower: impl ArrayLike<B, T>,
174    upper: impl ArrayLike<B, T>,
175    shape: impl Into<Shape>,
176) -> Array<B, T> {
177    let (lower, upper) = (lower.into_array(), upper.into_array());
178    let sqrt2 = c::<B, T>(std::f64::consts::SQRT_2);
179    let a = lax::erf(&(&lower / sqrt2));
180    let b = lax::erf(&(&upper / sqrt2));
181    let u = uniform(key, shape, a, b);
182    let out = sqrt2 * lax::erf_inv(&u);
183    let lo = next_after(&lower, true);
184    let hi = next_after(&upper, false);
185    jnp::minimum(hi, jnp::maximum(lo, out))
186}
187
188/// The carry of the outer loop of [`gamma_one`]: the key, `X`, `V`, `U`.
189type GammaState<B, T> = (Key<B>, Array<B, T>, Array<B, T>, Array<B, T>);
190
191/// One sample of `Gamma(alpha, 1)` (or its logarithm) by Marsaglia and
192/// Tsang's method, as JAX's `_gamma_one`.
193fn gamma_one<B: Backend, T: Float>(
194    key: Key<B>,
195    alpha: Array<B, T>,
196    log_space: bool,
197) -> Array<B, T> {
198    let zero = zero::<B, T>();
199    let one = one::<B, T>();
200    let minus_one = c::<B, T>(-1.0);
201    let two = c::<B, T>(2.0);
202    let one_over_two = c::<B, T>(0.5);
203    let one_over_three = c::<B, T>(1.0 / 3.0);
204    let squeeze_const = c::<B, T>(0.0331);
205
206    // For alpha < 1, Gamma(alpha) ~ Gamma(alpha + 1) * Uniform()^(1 / alpha).
207    let boost_mask = alpha.ge(one);
208    let alpha_orig = alpha.clone();
209    let alpha = jnp::where_(&boost_mask, &alpha, &alpha + one);
210    let d = &alpha - one_over_three;
211    let cc = one_over_three / jnp::sqrt(&d);
212
213    let (key, subkey) = split2(&key);
214    let init = (key, zero.to_array(), one.to_array(), two.to_array());
215    let (_, _, v, _) = lax::while_loop(
216        |(_, x, v, u): &GammaState<B, T>| {
217            let a = u.ge(one - squeeze_const * (x * x));
218            let b = jnp::log(u).ge(x * one_over_two + &d * ((one - v) + jnp::log(v)));
219            (a & b).to_scalar()
220        },
221        |(key, _, _, _)| {
222            let keys = split(&key, 3);
223            let (key, x_key, u_key) = (keys.get(0), keys.get(1), keys.get(2));
224            let (_, x, v) = lax::while_loop(
225                |(_, _, v): &(Key<B>, Array<B, T>, Array<B, T>)| v.le(zero).to_scalar(),
226                |(key, _, _)| {
227                    let (key, subkey) = split2(&key);
228                    let x = normal::<B, T>(&subkey, Shape::scalar());
229                    let v = one + &x * &cc;
230                    (key, x, v)
231                },
232                (x_key, zero.to_array(), minus_one.to_array()),
233            );
234            let big_x = &x * &x;
235            let big_v = &(&v * &v) * &v;
236            let u = uniform(&u_key, Shape::scalar(), zero, one);
237            (key, big_x, big_v, u)
238        },
239        init,
240    );
241    if log_space {
242        let log_samples = -exponential::<B, T>(&subkey, Shape::scalar());
243        let skip = &boost_mask | log_samples.eq(zero);
244        let log_boost = jnp::where_(skip, zero, &log_samples * (one / &alpha_orig));
245        jnp::log(&d) + jnp::log(&v) + log_boost
246    } else {
247        let samples = one - uniform(&subkey, Shape::scalar(), zero, one);
248        let boost = jnp::where_(&boost_mask, one, jnp::power(samples, one / &alpha_orig));
249        &d * &v * boost
250    }
251}
252
253/// `random_gamma_p` of JAX: a sample per element of `a`, each from its own
254/// key of `split(key, a.size())`.
255fn gamma_impl<B: Backend, T: Float>(key: &Key<B>, a: &Array<B, T>, log_space: bool) -> Array<B, T> {
256    let shape = a.shape();
257    let n = shape.size();
258    let keys = split(key, n);
259    let alphas = a.reshape([n]);
260    let (_, samples) = lax::scan(
261        |(), (k, alpha): (Key<B>, Array<B, T>)| ((), gamma_one(k, alpha, log_space)),
262        (),
263        (keys, alphas),
264        n,
265    );
266    samples.reshape(shape)
267}
268
269/// The derivative of samples with respect to `a`, as JAX's `_gamma_grad`.
270fn gamma_grad<B: Backend, T: Float>(
271    sample: &Array<B, T>,
272    a: &Array<B, T>,
273    log_space: bool,
274) -> Array<B, T> {
275    if log_space {
276        // d[log(sample)] = d[sample] / sample, with exp(log_sample) = 0
277        // replaced by the smallest normal number.
278        let samples = jnp::exp(sample);
279        let samples = jnp::where_(
280            samples.eq(zero::<B, T>()),
281            Scalar::<B, T>::new(tiny::<T>()),
282            &samples,
283        );
284        lax::random_gamma_grad(a, &samples) / samples
285    } else {
286        lax::random_gamma_grad(a, sample)
287    }
288}
289
290/// `gamma` and `loggamma`: the samples with JAX's derivative with respect
291/// to `a`.
292fn gamma_sample<B: Backend, T: Float>(
293    key: &Key<B>,
294    a: impl ArrayLike<B, T>,
295    shape: impl Into<Shape>,
296    log_space: bool,
297) -> Array<B, T> {
298    key.check_single();
299    let a = a.into_array().broadcast_to(shape);
300    lax::custom_jvp(
301        |a: Array<B, T>| gamma_impl(key, &a, log_space),
302        |a: Array<B, T>, a_dot: Array<B, T>| {
303            let ans = gamma_impl(key, &a, log_space);
304            let t = a_dot * gamma_grad(&ans, &a, log_space);
305            (ans, t)
306        },
307        a,
308    )
309}
310
311/// Gamma random floats with shape `a` and rate 1 (`jax.random.gamma`),
312/// differentiable with respect to `a`.
313#[track_caller]
314pub fn gamma<B: Backend, T: Float>(
315    key: &Key<B>,
316    a: impl ArrayLike<B, T>,
317    shape: impl Into<Shape>,
318) -> Array<B, T> {
319    gamma_sample(key, a, shape, false)
320}
321
322/// The logarithms of gamma random floats (`jax.random.loggamma`), accurate
323/// for small `a`.
324#[track_caller]
325pub fn loggamma<B: Backend, T: Float>(
326    key: &Key<B>,
327    a: impl ArrayLike<B, T>,
328    shape: impl Into<Shape>,
329) -> Array<B, T> {
330    gamma_sample(key, a, shape, true)
331}
332
333/// Beta random floats (`jax.random.beta`).
334#[track_caller]
335pub fn beta<B: Backend, T: Float>(
336    key: &Key<B>,
337    a: impl ArrayLike<B, T>,
338    b: impl ArrayLike<B, T>,
339    shape: impl Into<Shape>,
340) -> Array<B, T> {
341    let shape = shape.into();
342    let (key_a, key_b) = split2(key);
343    let log_gamma_a = loggamma(&key_a, a, shape.clone());
344    let log_gamma_b = loggamma(&key_b, b, shape);
345    // gamma_a / (gamma_a + gamma_b) without losing precision.
346    let log_max = jnp::maximum(&log_gamma_a, &log_gamma_b);
347    let gamma_a_scaled = jnp::exp(log_gamma_a - &log_max);
348    let gamma_b_scaled = jnp::exp(log_gamma_b - &log_max);
349    &gamma_a_scaled / (&gamma_a_scaled + gamma_b_scaled)
350}
351
352/// Dirichlet random floats (`jax.random.dirichlet`): `alpha` has shape
353/// `[..., k]`, and the result has shape `batch_shape + [k]`.
354#[track_caller]
355pub fn dirichlet<B: Backend, T: Float>(
356    key: &Key<B>,
357    alpha: &Array<B, T>,
358    batch_shape: impl Into<Shape>,
359) -> Array<B, T> {
360    let k = *alpha
361        .shape()
362        .last()
363        .expect("dirichlet needs alpha.ndim >= 1");
364    let mut dims = batch_shape.into().dims().to_vec();
365    dims.push(k);
366    let x = loggamma(key, alpha, dims);
367    // `jax.nn.softmax` along the last axis.
368    let axis = x.ndim() - 1;
369    let keep = |a: Array<B, T>| {
370        let mut s = a.shape().dims().to_vec();
371        s.push(1);
372        a.reshape(s)
373    };
374    let x_max = keep(lax::reduce_max(&x, &[axis]));
375    let unnormalized = jnp::exp(x - x_max);
376    let sum = keep(lax::reduce_sum(&unnormalized, &[axis]));
377    unnormalized / sum
378}
379
380/// Student's t random floats with `df` degrees of freedom (`jax.random.t`).
381#[track_caller]
382pub fn t<B: Backend, T: Float>(
383    key: &Key<B>,
384    df: impl ArrayLike<B, T>,
385    shape: impl Into<Shape>,
386) -> Array<B, T> {
387    let shape = shape.into();
388    let (key_n, key_g) = split2(key);
389    let n = normal::<B, T>(&key_n, shape.clone());
390    let half_df = df.into_array() / c::<B, T>(2.0);
391    let g = gamma(&key_g, &half_df, shape);
392    n * jnp::sqrt(half_df / g)
393}
394
395/// Chi-square random floats with `df` degrees of freedom
396/// (`jax.random.chisquare`).
397#[track_caller]
398pub fn chisquare<B: Backend, T: Float>(
399    key: &Key<B>,
400    df: impl ArrayLike<B, T>,
401    shape: impl Into<Shape>,
402) -> Array<B, T> {
403    let two = c::<B, T>(2.0);
404    let half_df = df.into_array() / two;
405    let log_g = loggamma(key, half_df, shape);
406    jnp::exp(log_g) * two
407}
408
409/// F random floats (`jax.random.f`).
410#[track_caller]
411pub fn f<B: Backend, T: Float>(
412    key: &Key<B>,
413    dfnum: impl ArrayLike<B, T>,
414    dfden: impl ArrayLike<B, T>,
415    shape: impl Into<Shape>,
416) -> Array<B, T> {
417    let shape = shape.into();
418    let (dfnum, dfden) = (dfnum.into_array(), dfden.into_array());
419    let (key_dfd, key_dfn) = split2(key);
420    let chi2_dfn = chisquare(&key_dfn, &dfnum, shape.clone());
421    let chi2_dfd = chisquare(&key_dfd, &dfden, shape);
422    (chi2_dfn / dfnum) / (chi2_dfd / dfden)
423}
424
425/// The carry of [`poisson_knuth`]: the iteration, the counts, the key, and
426/// the log of the product of uniforms.
427type KnuthState<B, T> = (Scalar<B, i32>, Array<B, T>, Key<B>, Array<B, f32>);
428
429/// The carry of [`poisson_rejection`]: the iteration, the samples, whether
430/// they are accepted, and the key.
431type RejectionState<B> = (Scalar<B, i32>, Array<B, f32>, Array<B, bool>, Key<B>);
432
433/// Poisson by Knuth's algorithm, for small rates.
434fn poisson_knuth<B: Backend, T: Int>(
435    key: &Key<B>,
436    lam: &Array<B, f32>,
437    shape: &Shape,
438    max_iters: i32,
439) -> Array<B, T> {
440    let one = Scalar::<B, T>::new(cast::<u8, T>(1));
441    let k_init = jnp::zeros::<B, T>(shape.clone());
442    let log_rate_init = jnp::zeros::<B, f32>(shape.clone());
443    let neg_lam = -lam;
444    let (_, k, _, _) = lax::while_loop(
445        |(i, _, _, log_prod): &KnuthState<B, T>| {
446            let any = jnp::any(log_prod.gt(&neg_lam), crate::jnp::ALL).to_scalar();
447            any & i.lt(max_iters)
448        },
449        |(i, k, rng, log_prod)| {
450            let (rng, subkey) = split2(&rng);
451            let k = jnp::where_(log_prod.gt(&neg_lam), &k + one, &k);
452            let u = uniform(
453                &subkey,
454                shape.clone(),
455                Scalar::<B, f32>::new(0.0),
456                Scalar::new(1.0),
457            );
458            (i + 1, k, rng, log_prod + jnp::log(u))
459        },
460        (Scalar::new(0), k_init, key.clone(), log_rate_init),
461    );
462    k - one
463}
464
465/// Poisson by Hormann's transformed rejection, for large rates.
466fn poisson_rejection<B: Backend, T: Int>(
467    key: &Key<B>,
468    lam: &Array<B, f32>,
469    shape: &Shape,
470    max_iters: i32,
471) -> Array<B, T> {
472    let f = Scalar::<B, f32>::new;
473    let log_lam = jnp::log(lam);
474    let b = f(0.931) + f(2.53) * jnp::sqrt(lam);
475    let a = f(-0.059) + f(0.02483) * &b;
476    let inv_alpha = f(1.1239) + f(1.1328) / (&b - f(3.4));
477    let v_r = f(0.9277) - f(3.6224) / (&b - f(2.0));
478    let k_init = jnp::full::<B, f32>(shape.clone(), -1.0);
479    let accepted = jnp::full::<B, bool>(shape.clone(), false);
480    let (_, k, _, _) = lax::while_loop(
481        |(i, _, accepted, _): &RejectionState<B>| {
482            jnp::any(!accepted, crate::jnp::ALL).to_scalar() & i.lt(max_iters)
483        },
484        |(i, k_out, accepted, key)| {
485            let keys = split(&key, 3);
486            let (key, subkey_0, subkey_1) = (keys.get(0), keys.get(1), keys.get(2));
487            let u = uniform(&subkey_0, shape.clone(), f(0.0), f(1.0)) - f(0.5);
488            let v = uniform(&subkey_1, shape.clone(), f(0.0), f(1.0));
489            let u_shifted = f(0.5) - u.abs();
490            let k = jnp::floor((f(2.0) * &a / &u_shifted + &b) * &u + lam + f(0.43));
491            let s = jnp::log(&v * &inv_alpha / (&a / (&u_shifted * &u_shifted) + &b));
492            let t = -lam + &k * &log_lam - lax::lgamma(&(&k + f(1.0)));
493            let accept1 = u_shifted.ge(f(0.07)) & v.le(&v_r);
494            let reject = k.lt(f(0.0)) | (u_shifted.lt(f(0.013)) & v.gt(&u_shifted));
495            let accept2 = s.le(&t);
496            let accept = accept1 | (!reject & accept2);
497            let k_out = jnp::where_(&accept, &k, &k_out);
498            let accepted = accepted | accept;
499            (i + 1, k_out, accepted, key)
500        },
501        (Scalar::new(0), k_init, accepted, key.clone()),
502    );
503    k.cast::<T>()
504}
505
506/// Poisson random integers with rate `lam` (`jax.random.poisson`).
507#[track_caller]
508pub fn poisson<B: Backend, T: Int>(
509    key: &Key<B>,
510    lam: impl ArrayLike<B, f32>,
511    shape: impl Into<Shape>,
512) -> Array<B, T> {
513    key.check_single();
514    let shape = shape.into();
515    let lam = lam.into_array().broadcast_to(shape.clone());
516    let use_knuth = is_nan(&lam) | lam.lt(Scalar::new(10.0));
517    let lam_knuth = jnp::where_(&use_knuth, &lam, Scalar::<B, f32>::new(0.0));
518    let lam_rejection = jnp::where_(&use_knuth, Scalar::<B, f32>::new(1e5), &lam);
519    // JAX's `iinfo(dtype).max`, an insanely conservative bound.
520    let max_iters = match T::DTYPE.size_in_bytes() {
521        1 => i32::from(i8::MAX),
522        2 => i32::from(i16::MAX),
523        _ => i32::MAX,
524    };
525    let result = jnp::where_(
526        use_knuth,
527        poisson_knuth::<B, T>(key, &lam_knuth, &shape, max_iters),
528        poisson_rejection::<B, T>(key, &lam_rejection, &shape, max_iters),
529    );
530    jnp::where_(lam.eq(Scalar::new(0.0)), jnp::zeros::<B, T>(shape), result)
531}
532
533/// JAX's `_stirling_approx_tail`: the tail of Stirling's series for
534/// `log(k!)`, from a table for `k <= 9`.
535fn stirling_approx_tail<B: Backend, T: Float>(k: &Array<B, T>) -> Array<B, T> {
536    const TAIL: [f64; 10] = [
537        0.081_061_466_795_327_2,
538        0.041_340_695_955_409_2,
539        0.027_677_925_684_998_3,
540        0.020_790_672_103_765_09,
541        0.016_644_691_189_821_1,
542        0.013_876_128_823_070_7,
543        0.011_896_709_945_891_7,
544        0.010_411_265_261_972,
545        0.009_255_462_182_712_73,
546        0.008_330_563_433_362_87,
547    ];
548    let use_tail_values = k.le(c::<B, T>(9.0));
549    let k = lax::clamp(&c::<B, T>(0.0).to_array(), k, &c::<B, T>(9.0).to_array());
550    let k1 = &k + c::<B, T>(1.0);
551    let kp1sq = &k1 * &k1;
552    let inner = c::<B, T>(1.0 / 360.0) - c::<B, T>(1.0 / 1260.0) / &kp1sq;
553    let approx = (c::<B, T>(1.0 / 12.0) - inner / &kp1sq) / k1;
554    let k = jnp::floor(&k);
555    let mut table = c::<B, T>(TAIL[0]).to_array().broadcast_to(k.shape());
556    for (j, &v) in TAIL.iter().enumerate().skip(1) {
557        table = jnp::where_(k.eq(c::<B, T>(j as f64)), c::<B, T>(v), table);
558    }
559    jnp::where_(use_tail_values, table, approx)
560}
561
562/// Binomial by inversion (sums of geometric variables), for small means.
563fn binomial_inversion<B: Backend, T: Float>(
564    key: &Key<B>,
565    count: &Array<B, T>,
566    prob: &Array<B, T>,
567    shape: &Shape,
568) -> Array<B, T> {
569    let log1minusprob = jnp::log1p(-prob);
570    let init = (
571        jnp::zeros::<B, T>(shape.clone()),
572        jnp::zeros::<B, T>(shape.clone()),
573        key.clone(),
574    );
575    let (num_geom, _, _) = lax::while_loop(
576        |(_, geom_sum, _): &(Array<B, T>, Array<B, T>, Key<B>)| {
577            jnp::any(geom_sum.le(count), crate::jnp::ALL).to_scalar()
578        },
579        |(num_geom, geom_sum, key)| {
580            let (subkey, key) = split2(&key);
581            let num_geom_out =
582                jnp::where_(geom_sum.le(count), &num_geom + one::<B, T>(), &num_geom);
583            let u = uniform(&subkey, shape.clone(), zero::<B, T>(), one::<B, T>());
584            let geom = jnp::ceil(jnp::log(u) / &log1minusprob);
585            (num_geom_out, geom_sum + geom, key)
586        },
587        init,
588    );
589    num_geom - one::<B, T>()
590}
591
592/// Binomial by the BTRS transformed rejection, for large means.
593fn btrs<B: Backend, T: Float>(
594    key: &Key<B>,
595    count: &Array<B, T>,
596    prob: &Array<B, T>,
597    shape: &Shape,
598) -> Array<B, T> {
599    let f = c::<B, T>;
600    let stddev = jnp::sqrt(count * prob * (f(1.0) - prob));
601    let b = f(1.15) + f(2.53) * &stddev;
602    let a = f(-0.0873) + f(0.0248) * &b + f(0.01) * prob;
603    let cc = count * prob + f(0.5);
604    let v_r = f(0.92) - f(4.2) / &b;
605    let r = prob / (f(1.0) - prob);
606    let alpha = (f(2.83) + f(5.1) / &b) * &stddev;
607    let m = jnp::floor((count + f(1.0)) * prob);
608    let st_m = stirling_approx_tail(&m);
609    let st_count_m = stirling_approx_tail(&(count - &m));
610    let k_init = jnp::full::<B, T>(shape.clone(), cast::<f64, T>(-1.0));
611    let accepted = jnp::full::<B, bool>(shape.clone(), false);
612    let (k, _, _) = lax::while_loop(
613        |(_, accepted, _): &(Array<B, T>, Array<B, bool>, Key<B>)| {
614            jnp::any(!accepted, crate::jnp::ALL).to_scalar()
615        },
616        |(k_out, accepted, key)| {
617            let keys = split(&key, 3);
618            let (key, subkey_0, subkey_1) = (keys.get(0), keys.get(1), keys.get(2));
619            let u = uniform(&subkey_0, shape.clone(), f(0.0), f(1.0));
620            let v = uniform(&subkey_1, shape.clone(), f(0.0), f(1.0));
621            let u = u - f(0.5);
622            let us = f(0.5) - u.abs();
623            let accept1 = us.ge(f(0.07)) & v.le(&v_r);
624            let k = jnp::floor((f(2.0) * &a / &us + &b) * &u + &cc);
625            let reject = k.lt(f(0.0)) | k.gt(count);
626            let v = jnp::log(v * &alpha / (&a / (&us * &us) + &b));
627            let count_m1 = count - &m + f(1.0);
628            let count_k1 = count - &k + f(1.0);
629            let ub = (&m + f(0.5)) * jnp::log((&m + f(1.0)) / (&r * &count_m1))
630                + (count + f(1.0)) * jnp::log(&count_m1 / &count_k1)
631                + (&k + f(0.5)) * jnp::log(&r * &count_k1 / (&k + f(1.0)))
632                + &st_m
633                + &st_count_m
634                - stirling_approx_tail(&k)
635                - stirling_approx_tail(&(count - &k));
636            let accept2 = v.le(&ub);
637            let accept = accept1 | (!reject & accept2);
638            let k_out = jnp::where_(&accept, &k, &k_out);
639            (k_out, accepted | accept, key)
640        },
641        (k_init, accepted, key.clone()),
642    );
643    k
644}
645
646/// Binomial random floats: the number of successes in `n` trials of
647/// probability `p` (`jax.random.binomial`).
648#[track_caller]
649pub fn binomial<B: Backend, T: Float>(
650    key: &Key<B>,
651    n: impl ArrayLike<B, T>,
652    p: impl ArrayLike<B, T>,
653    shape: impl Into<Shape>,
654) -> Array<B, T> {
655    key.check_single();
656    let f = c::<B, T>;
657    let shape = shape.into();
658    let count = n.into_array().broadcast_to(shape.clone());
659    let prob = p.into_array().broadcast_to(shape.clone());
660    let p_lt_half = prob.lt(f(0.5));
661    let q = jnp::where_(&p_lt_half, &prob, f(1.0) - &prob);
662    let count_nan_or_neg = is_nan(&count) | count.lt(f(0.0));
663    let count_inf = is_inf(&count);
664    let q_is_nan = is_nan(&q);
665    let q_l_0 = q.lt(f(0.0));
666    let q = jnp::where_(&q_is_nan | &q_l_0, f(0.01), &q);
667    let use_inversion = &count_nan_or_neg | (&count * &q).le(f(10.0));
668    let count = jnp::floor(&count);
669    let count_inv = jnp::where_(&use_inversion, &count, f(0.0));
670    let count_btrs = jnp::where_(&use_inversion, f(1e4), &count);
671    let q_btrs = jnp::where_(&use_inversion, f(0.5), &q);
672    let samples = jnp::where_(
673        &use_inversion,
674        binomial_inversion(key, &count_inv, &q, &shape),
675        btrs(key, &count_btrs, &q_btrs, &shape),
676    );
677    let invalid = &q_l_0 | &q_is_nan | &count_nan_or_neg;
678    let samples = jnp::where_(&invalid, f(f64::NAN), samples);
679    let samples = jnp::where_(&count_inf & !&invalid, f(f64::INFINITY), samples);
680    let keep = p_lt_half | count_nan_or_neg | q_is_nan | count_inf;
681    jnp::where_(keep, &samples, &count - &samples)
682}
683
684/// `jnp.take(x, ind, axis=0)` for indices in bounds: the rows of `x` at
685/// `ind` (one-dimensional), stacked.
686fn take_rows<B: Backend, T: Element>(x: &Array<B, T>, ind: &Array<B, i32>) -> Array<B, T> {
687    let shape = x.shape();
688    let m = ind.size();
689    let ind = ind.reshape([m, 1]);
690    let mut slice_sizes = shape.dims().to_vec();
691    slice_sizes[0] = 1;
692    let dims = GatherDims {
693        offset_dims: (1..shape.rank()).collect(),
694        collapsed_slice_dims: vec![0],
695        start_index_map: vec![0],
696        ..GatherDims::default()
697    };
698    lax::gather(
699        x,
700        &ind,
701        &dims,
702        &slice_sizes,
703        GatherScatterMode::PromiseInBounds,
704    )
705}
706
707/// The result shape of `choice`: `shape` followed by the shape of an
708/// element of `a`.
709fn choice_shape<B: Backend, T: Element>(a: &Array<B, T>, shape: &Shape) -> Vec<usize> {
710    let mut dims = shape.dims().to_vec();
711    dims.extend_from_slice(&a.shape().dims()[1..]);
712    dims
713}
714
715/// Random elements of `a` along axis 0 (`jax.random.choice` with `p=None`
716/// and `axis=0`), with or without replacement. Use `jnp::arange` for the
717/// integer form `choice(key, n, ...)`.
718///
719/// # Panics
720///
721/// Panics if `a` is a scalar or empty, or if `replace` is false and more
722/// elements are drawn than `a` has.
723#[track_caller]
724pub fn choice<B: Backend, T: Element>(
725    key: &Key<B>,
726    a: &Array<B, T>,
727    shape: impl Into<Shape>,
728    replace: bool,
729) -> Array<B, T> {
730    let shape = shape.into();
731    let n_inputs = check_choice(a, &shape, replace);
732    let n_draws = shape.size();
733    let result = if n_draws == 0 {
734        jnp::zeros::<B, T>(choice_shape(a, &shape))
735    } else if replace {
736        if B::FAST_PATHS && n_draws == 1 {
737            // One draw, natively: element 0 of the indices (a scalar
738            // `randint` gives the same value), whose row is read directly.
739            let i = randint(key, [], 0, n_inputs as i32).to_scalar();
740            return a.i(i).reshape(choice_shape(a, &shape));
741        }
742        let ind = randint(key, [n_draws], 0, n_inputs as i32);
743        take_rows(a, &ind)
744    } else {
745        lax::slice_in_dim(&shuffle(key, a), 0, n_draws, 1, 0)
746    };
747    result.reshape(choice_shape(a, &shape))
748}
749
750#[track_caller]
751fn check_choice<B: Backend, T: Element>(a: &Array<B, T>, shape: &Shape, replace: bool) -> usize {
752    assert!(
753        a.ndim() > 0,
754        "choice needs an array of at least one dimension"
755    );
756    let n_inputs = a.shape()[0];
757    let n_draws = shape.size();
758    assert!(
759        n_draws == 0 || n_inputs > 0,
760        "a must be greater than 0 unless no samples are taken"
761    );
762    assert!(
763        replace || n_draws <= n_inputs,
764        "cannot take a larger sample (size {n_draws}) than population (size {n_inputs}) \
765         when replace is false"
766    );
767    n_inputs
768}
769
770/// Random elements of `a` along axis 0 with probabilities `p`
771/// (`jax.random.choice` with `p` and `axis=0`), with or without
772/// replacement.
773///
774/// # Panics
775///
776/// Panics as [`choice`] does, or if `p` does not have one element per row
777/// of `a`.
778#[track_caller]
779pub fn choice_with_p<B: Backend, T: Element, F: Float>(
780    key: &Key<B>,
781    a: &Array<B, T>,
782    shape: impl Into<Shape>,
783    replace: bool,
784    p: &Array<B, F>,
785) -> Array<B, T> {
786    let shape = shape.into();
787    let n_inputs = check_choice(a, &shape, replace);
788    assert_eq!(
789        p.shape().dims(),
790        [n_inputs],
791        "p must be a vector with one element per row of a"
792    );
793    let n_draws = shape.size();
794    if n_draws == 0 {
795        return jnp::zeros::<B, T>(choice_shape(a, &shape));
796    }
797    if B::FAST_PATHS && replace && n_draws == 1 && a.ndim() == 1 {
798        // One draw from a vector, natively: the same sums, uniform number,
799        // and count as below, with scalars (element 0 of a uniform vector
800        // is the scalar uniform), and the element read directly.
801        let mut last = zero::<B, F>();
802        for i in 0..n_inputs {
803            last = last + p.get(i as i64);
804        }
805        let u = uniform(key, [], zero::<B, F>(), one::<B, F>()).to_scalar();
806        let r = last * (one::<B, F>() - u);
807        let (mut cum, mut below) = (zero::<B, F>(), Scalar::<B, i32>::new(0));
808        for i in 0..n_inputs {
809            cum = cum + p.get(i as i64);
810            below = below + r.gt(cum).cast::<i32>();
811        }
812        return a.i(below).reshape(choice_shape(a, &shape));
813    }
814    let ind = if replace {
815        // `jnp.cumsum`, which XLA computes as a sum from the left.
816        let (_, p_cuml) = lax::scan(
817            |acc: Array<B, F>, x: Array<B, F>| {
818                let s = acc + x;
819                (s.clone(), s)
820            },
821            zero::<B, F>().to_array(),
822            p.clone(),
823            n_inputs,
824        );
825        let last = lax::index_in_dim(&p_cuml, n_inputs - 1, 0, false);
826        let u = uniform(key, [n_draws], zero::<B, F>(), one::<B, F>());
827        let r = last * (one::<B, F>() - u);
828        // `jnp.searchsorted(p_cuml, r)`: the number of cumulative sums
829        // below each value.
830        let below = r.reshape([n_draws, 1]).gt(&p_cuml);
831        lax::reduce_sum(&below.cast::<i32>(), &[1])
832    } else {
833        // The Gumbel top-k trick.
834        let g = gumbel::<B, F>(key, [n_inputs]) + jnp::log(p);
835        // `lax.top_k`: a stable sort of -g puts the largest first, ties in
836        // order of index.
837        let (_, order) = lax::sort_key_val(&-g, &lax::iota::<B, i32>([n_inputs], 0), 0);
838        lax::slice_in_dim(&order, 0, n_draws, 1, 0)
839    };
840    take_rows(a, &ind).reshape(choice_shape(a, &shape))
841}
842
843#[cfg(test)]
844mod tests {
845    use super::*;
846    use crate::backend::Native;
847
848    #[test]
849    fn next_after_steps_one_ulp() {
850        let x = Array::<Native, f32>::from_vec(vec![1.0, -1.0, 0.0, -0.0, f32::INFINITY], [5]);
851        let up = next_after(&x, true).to_vec();
852        assert_eq!(up[0], 1.0f32.next_up());
853        assert_eq!(up[1], (-1.0f32).next_up());
854        assert_eq!(up[2], f32::from_bits(1));
855        assert_eq!(up[3], f32::from_bits(1));
856        assert_eq!(up[4], f32::INFINITY);
857        let down = next_after(&x, false).to_vec();
858        assert_eq!(down[0], 1.0f32.next_down());
859        assert_eq!(down[1], (-1.0f32).next_down());
860        assert_eq!(down[2], -f32::from_bits(1));
861        assert_eq!(down[4], f32::MAX);
862    }
863}