Module Nx.Rng
Random numbers from one Threefry-2x32 generator.
A key is the generator's whole state: every draw is a function of its key, dtype and shape, the same at every placement. Fresh draws come from fresh keys, by Rng.split or Rng.fold_in. A key is spent once it is used: its own draws, its Rng.split keys, its Rng.fold_in keys and the keys of a scope rooted at it all come from one stream of blocks under it, so using a key two of these ways can repeat bits. A scope lets one key stand for a region: a sampler called without ~key takes the scope's next key. A scope may instead refuse such draws (Rng.refusing), so that a region draws only from keys it is given.
A key's two words lie whole on one device: a placement that cuts the words' axis holds no key. Rng.key makes a host key, which Rng.place moves to a placement that keeps the words whole. Rng.split and Rng.fold_in compute where their key lies, and Rng.fold_in_tensor where its key and index lie together. A scope at a host key that no interpretation traces computes its keys on the host when a draw takes one, and no interpretation receives that computation, so its draws lie at any placement. A scope at any other key computes them where that key lies, as Rng.fold_in does, and draws only on that key's set.
On a set without kernels (devices) only a compiler's program computes from a key: Rng.split, Rng.fold_in and a draw from ~key raise Invalid_argument there eagerly, as every computation does. The message of a derivation from an untraced key, or of a keyless draw in a scope at one, names Nx.Rng.place Nx.Host.on key. Keep the keys of such a program on the host, derive them there, and place each where the program reads it, at its call:
let root = Nx.Rng.key 0 let step = Rune.jit Nx.Ptree.(Nx.Rng.ptree @-> returns tensor) (fun key -> Nx.Rng.normal_at Gpu.on ~key Nx.float32 [| 4 |]) let x i = step (Nx.Rng.place Gpu.on (Nx.Rng.fold_in root i))
A key a program returns lies on the program's set: derive the next one inside the program, or place it on the host first.
The type for keys, of shape [|2|], and batches of keys, of shape [|…; 2|]: two 32-bit words per key. Arithmetic on a key gives an array, which no sampler takes.
Keys
of_tensor t is the key, or batch of keys, whose words are t, for words that were saved: the inverse of to_tensor.
Raises Invalid_argument unless t's last axis has extent 2, and if t's placement cuts the last axis.
to_tensor k is k's words: the inverse of of_tensor, and what the coercion of k to an array is.
val place : 'e Placement.t -> 'd key -> 'e keyval placement : 'd key -> 'd Placement.tplacement k is where k's words lie, Nx.placement of to_tensor k. A draw from k at placement k has each device draw from the keys it holds. A single key's placement cuts no axis, so a value of any shape made there combines with its draws. A batch's may cut its batch axes, and a value of another shape that combines with its draws is made at Placement.uncut (placement k). For b a batch of 4 keys split along axis 0:
let at = Nx.Rng.placement b in let x = Nx.Rng.normal_at at ~key:b Nx.float32 [| 3 |] in let bias = Nx.full_at (Nx.Placement.uncut at) Nx.float32 [| 3 |] 0.1 in Nx.add x bias
x has shape [4; 3] at at, each device drawing its rows from its own keys, and bias lies whole on each device. Made at at, bias would be split along its only axis, and add would raise.
val walk : ('a, 'b, 'd, 'e) Ptree.Walk.cursor -> 'd key -> 'e keywalk c k walks k, a key or a batch of keys, at c's path as one fixed array (Ptree.Walk.tensor), and rebuilds it as of_tensor does. A structure holding a key walks it with field c "key" Nx.Rng.walk k; ptree describes a key alone.
ptree is a key, or a batch of keys, as a description: one fixed array at the root, walked by walk, which rebuilds it as of_tensor does. It is at every set, as Ptree.tensor is, so one binding describes keys on the host and on any other set.
split ~n k is n keys derived from k (n defaults to 2), independent of each other. They are k's blocks 0 to n - 1, so a key split is spent (Rng).
Raises Invalid_argument if n < 1 or k is a batch.
split_batch ~n k is split ~n k as one batch of shape [|n; 2|]: row i holds (split ~n k).(i)'s words.
Raises Invalid_argument if n < 1 or k is a batch.
fold_in k i is the key of k indexed by i: distinct i give independent keys. A batch of keys gives a batch.
fold_in_tensor k i is fold_in k of the indices held in i, for an index known only as data. Its shape is k's batch broadcast with i's, then 2; where i holds n it is fold_in k n. It lies at the union of k's and i's placements, each key whole on its device (Routing).
Raises Invalid_argument if the shapes do not broadcast, and as an operation does where k and i cannot be read together.
Samplers
A sampler draws from ~key, or without it from the scope's next key (with_key). The next key of a scope at a host key that no interpretation traces is written into the sampler's program, its two words as full writes its value, so that no bytes move, at any placement; that of a scope at another key is read as ~key is, and raises as it does. A sampler without an array parameter draws on the host, and its _at form at the placement it is given, each device computing its window: placement (uniform_at p dt s) is p. On a set without kernels, a draw without ~key is a creation, the host draw placed there (Nx.devices), and a draw from a ~key there reads the key, a computation, and raises as one. An _at form raises as its host form does, and raises Invalid_argument naming itself where p cuts an axis the draw's shape lacks, and where a device of p does not hold key, naming the place to write. A sampler with array parameters draws where they lie, reading key beside them as an operation reads its operands (Routing). A key with batch axes b draws b followed by the draw's shape, one draw per key, each the draw that key alone gives. Float draws compute at float64 for float64 and at float32 for the other floats, and round once to their dtype.
A donated key reaching a sampler is lent (Donation and copies), and lives on.
A sampler's parameters are arrays, and the draw has their broadcast shape. Each parameter is checked against its domain: an element outside raises Invalid_argument naming the sampler, the parameter, the element's index and its value, as in Nx.Rng.bernoulli: p at [3] is 1.5, not in [0, 1]. The check is a check: it raises at the call for a parameter on the host, and for one on another set at the next wait on that set, so that a draw never waits for its parameters. Under an interpretation it is a Check operation, which raises where the interpretation computes it.
bits shape is uniformly random 32-bit words: word j in C order is word j mod 2 of the generator's block j / 2.
Raises Invalid_argument if an extent is negative.
val bits_at : 'd Placement.t -> ?key:'d key -> int array -> 'd int32_tbits_at p shape is bits shape at p.
uniform dt shape is draws from [0, 1): multiples of 2{^-p}, each equally likely, p the largest such that every multiple of 2{^-p} in [0, 1) is a value of dt: dt's significand width, from float64's 53 down to float8_e5m2's 3; float4_e2m1fn's values below 1 are 0 and 0.5, so its p is 1.
Raises Invalid_argument if an extent is negative.
val uniform_at :
'd Placement.t ->
?key:'d key ->
(float, 's) dtype ->
int array ->
(float, 's, 'd) tuniform_at p dt shape is uniform dt shape at p.
normal dt shape is standard normal draws, by the Box-Muller transform: draws 2q and 2q + 1 in C order are the cosine's and the sine's of one transform, of the uniform draws 2q and 2q + 1 at the compute dtype.
Raises Invalid_argument if an extent is negative.
val normal_at :
'd Placement.t ->
?key:'d key ->
(float, 's) dtype ->
int array ->
(float, 's, 'd) tnormal_at p dt shape is normal dt shape at p.
exponential dt shape is exponential draws of rate 1, by inverting the distribution at 1 - u for a uniform u: finite, and never negative.
Raises Invalid_argument if an extent is negative.
val exponential_at :
'd Placement.t ->
?key:'d key ->
(float, 's) dtype ->
int array ->
(float, 's, 'd) texponential_at p dt shape is exponential dt shape at p.
gumbel dt shape is standard Gumbel draws, of distribution exp (-exp (-x)): -log e for an exponential draw e of 53 random bits at float64 and 32 otherwise, computed so that e keeps its relative precision near 0., so the draws are finite. Added to unnormalised log-probabilities, its argmax draws from the distribution they describe, as categorical does; a softmax in place of the argmax gives that draw's relaxed, differentiable form.
Raises Invalid_argument if an extent is negative.
val gumbel_at :
'd Placement.t ->
?key:'d key ->
(float, 's) dtype ->
int array ->
(float, 's, 'd) tgumbel_at p dt shape is gumbel dt shape at p.
randint ~low ~high shape is integers drawn uniformly from [low, high) (low defaults to 0): a 64-bit draw times high - low, shifted down by 64 bits, whose biased low part, at most one draw in 2{^32}, takes a second draw (Lemire's multiply-shift).
Raises Invalid_argument if low >= high, a bound is outside int32, or an extent is negative.
val randint_at :
'd Placement.t ->
?key:'d key ->
?low:int ->
high:int ->
int array ->
'd int32_trandint_at p ~low ~high shape is randint ~low ~high shape at p.
bernoulli p is true with probability p rounded up to a multiple of 2{^-53}, elementwise: 53 random bits, read as an integer, below p 2{^53}.
Raises Invalid_argument if an element of p is outside [0, 1].
gamma a is gamma draws of concentration a and unit rate, elementwise: Marsaglia and Tsang's rejection, below a concentration of 1 through Gamma(a) = Gamma(a + 1) U{^1/a}. Divide by a rate for the two-parameter family.
It is not exact: a draw takes the first of ten rounds that accepts, each accepting more than 95% of proposals, and the one element in about 10{^13} that no round accepts is the distribution's mean from a concentration of 1 up, and (a + 1) U{^1/a} below.
Raises Invalid_argument if an element of a is outside (0, inf).
beta a b is beta draws on (0, 1) of concentrations a and b, elementwise over their broadcast shape: G(a) / (G(a) + G(b)) for two independent gamma draws, formed from their logarithms so that two draws that underflow keep their ratio. Draw j in C order is formed from the draws 2j and 2j + 1 that gamma gives from its key over a and b interleaved. A draw that would round to 0. or 1. is the nearest value inside: the dtype's least positive value, or the largest below 1., so neither a draw nor 1 - x is ever 0.. It inherits gamma's rounds.
Raises Invalid_argument if the shapes do not broadcast or an element of a or b is outside (0, inf).
von_mises k is von Mises draws of mean direction 0 and concentration k, elementwise, as angles in [-π, π]: uniform on the circle at k = 0, near a normal of variance 1 / k for a large k.
It is not exact: Best and Fisher's rejection from a wrapped Cauchy envelope runs twenty rounds, and the one element in about 2·10{^9} that no round accepts is a draw from the envelope. Add a mean direction, wrapped into [-π, π], for the general family.
Raises Invalid_argument if an element of k is outside [0, inf).
poisson rate is Poisson counts of rate, elementwise; a rate of 0 gives 0. Below 10 a count inverts the distribution with one uniform draw, with no fallback. From 10 up it is Hörmann's transformed rejection over sixteen rounds, and the one element in about 5·10{^9} that no round accepts takes its last proposal, a count near the rate clamped to at least 0. A count past int32's largest saturates there. A float32 rate places its proposals exactly up to about 10{^5}; beyond, float32's spacing near the rate exceeds a hundredth of a count, so proposals drift off their counts and the distribution is biased: give a float64 rate.
Raises Invalid_argument if an element of rate is outside [0, 2{^31}).
binomial n p is the number of successes in n trials that each succeed with probability p, elementwise over their broadcast shape: 0 at p = 0, n at p = 1. Where the mean of the rarer outcome is below 10 a count inverts the distribution with one uniform draw, with no fallback; from 10 up it is Hörmann's transformed rejection over eighteen rounds, and the one element in about 4·10{^9} that no round accepts takes its last proposal, clamped into [0, n]. A float32 p places its proposals exactly up to a mean of about 10{^5}; beyond, float32's spacing near the mean exceeds a hundredth of a count, so proposals drift off their counts and the distribution is biased: give a float64 p.
Raises Invalid_argument if the shapes do not broadcast, an element of n is negative, or one of p is outside [0, 1].
truncated_normal lower upper is standard normal draws conditioned on [lower, upper], elementwise over their broadcast shape. The bounds may come in either order, an infinite one leaves its side open, and equal ones give the bound. Draw j in C order is the x with Φ(x) = (1 - u) Φ(lower) + u Φ(upper), Φ the normal distribution function (ndtr), and u uniform's draw j from the same key at float64 for float64 and at float32 otherwise, floored at its least positive value. It inverts the smaller of the masses below and above x, held as logarithms in the tails, so that bounds far out on one side keep their digits, and its cost does not depend on the interval's mass. A draw lies in the interval, and within 6ε plus 3 units in the last place of the exact solution, ε being 2{^-23} at float32 and 2{^-52} at float64, however far out the bounds lie. The masses at each bound are computed once per element of the bound as given, so a scalar bound costs one.
Raises Invalid_argument if the shapes do not broadcast or an element of lower or upper is NaN.
dirichlet a is Dirichlet draws of concentrations a along its last axis, one draw per row: the gamma draws of a from the same key, each row divided by its sum. The quotient is formed from the draws' logarithms, so that a row of concentrations so small that its gamma draws underflow keeps their ratios: each row sums to 1 and has an element of at least 1 / n, n its length, up to rounding. It inherits gamma's rounds.
Raises Invalid_argument if a has no axis, or an element of a is outside (0, inf).
categorical logits is a position along axis of each row of logits, drawn with probability proportional to the exponential of its logit: axis is the last by default, a negative one counted from the end. A logit of -inf is never drawn. The result has logits' shape without axis; broadcast logits for several draws of one row.
It is the argmax of the logits plus Gumbel noise -log e, computed at float64 for float64 and float32 for the other floats, e an exponential draw formed from b random bits, 53 at float64 and 32 otherwise, that keeps its relative precision near 0. The noise is bounded, so a category whose logit lies more than (b + 1) ln 2 + ln ((b + 1) ln 2) below its row's largest, about 26 at float32 and 41 at float64, is never drawn: its probability is below e{^-26} or e{^-41}.
Raises Invalid_argument if axis is not an axis of logits or has no element, or if a row's largest logit is not finite: +inf, NaN, or a row of -inf.
permutation n is a uniformly random ordering of 0, …, n - 1: the positions that sort n random 64-bit words. Two words collide, and their positions keep their order, with probability below n{^2} / 2{^65}.
Raises Invalid_argument if n is negative.
val permutation_at : 'd Placement.t -> ?key:'d key -> int -> 'd int64_tpermutation_at p n is permutation n at p. A sort reads its axis whole, so where p cuts it each device of p draws and sorts all n words and keeps its window.
Scope
with_key k f runs f in a scope rooted at k: the sampler called nth in f without ~key, counting from 0, draws as it does with ~key:(fold_in k n). Scopes nest, the inner replacing the outer. A scope is per fiber and per domain. What f raises passes on with the backtrace of its raise.
k may be traced, as an interpretation's argument is: the scope's keys are then computed from it by the interpretations around each draw, so a function that receives a key draws what the same function draws eagerly in a scope at that key's value. A scope at a host key that no interpretation traces draws at any placement. A scope at any other key, traced or on another set, draws only where a draw from ~key at k would: a draw elsewhere raises as that draw does, naming the place to write. A traced host key whose draws lie on a device set is placed there first, as with_key (place p k) f.
Raises Invalid_argument if k is dead or a batch.
val refusing : string -> (unit -> 'a) -> 'arefusing name f runs f in a scope that gives no keys. Scopes nest as with_key says: a scope inside f gives its own keys.
A sampler called in f without ~key, and next_key, raise Invalid_argument naming themselves and name, as Nx.Rng.normal: no key inside Rune.scan, which refuses keyless draws. What f raises passes on with the backtrace of its raise.
next_key () is the scope's next key, a host key computed at the call. Outside every scope, it is the next key of the domain's own, seeded from the system's entropy.
Raises Invalid_argument inside refusing, and inside a scope at a key that is traced or lies off the host, whose keys are not host keys.