Random numbers on a computer: generators and sampling
Monte Carlo, weight initialization and dropout rely on a deterministic generator that imitates randomness. Study classical and modern generators (LCG, Mersenne Twister, PCG and Philox), uniform floats from bits, counter-based generators on GPUs, and algorithms transforming uniforms into distributions: numerical inversion, rejection, Ziggurat, alias and Gumbel-max. Practical seed and stream management for reproducibility is covered in m00.
After this lesson you can
- Implement an LCG, an xorshift and PCG32 and subject them to simple statistical tests.
- Explain why counter-based generators are the choice for GPUs and parallel computing.
- Convert random bits into uniform floats without exact zeros and range integers without modulo bias.
- Implement numerical inversion, rejection, the polar method and Ziggurat, the alias method and Gumbel-max.
- Calculate a rejection sampler's acceptance rate and anticipate its collapse in high dimensions.
Before you start
Motivation: three failures that raise no error
Every Monte Carlo run, every weight initialization, every dropout mask and every token generated by a language model comes from the same source: a deterministic function that, from a few bytes of state, produces numbers that appear independent and uniform. When that source fails, it almost never fails with an exception. It fails like this:
- A backtest that does not repeat. You set
np.random.seed(0)at the start of the script, but a library you update callsnp.random.shuffleone more time during data loading. From that point all simulated paths differ, backtest metrics change and nothing warns you: there is one global state and anyone can consume it. - Eight processes doing the same thing. Your
Datasetcreatesself.rng = np.random.default_rng(0)in__init__. TheDataLoadercopies the object, with its state, to each of eight workers, and all eight apply exactly the same augmentations in the same order. The model sees eight times less variety than you think. - Biased token sampling. You convert random bits to a vocabulary index with
x % V, or generate Gumbel noise with-log(-log(u))and anuthat can be exactly 0 or 1. The first systematically favors part of the vocabulary, increasingly so with fewer bits; the second occasionally returns and forces an arbitrary token.
This lesson opens the box. First, generators: how congruential generators, Mersenne Twister, the xorshift family, PCG and GPU counter-based generators work inside, and how a bad generator is detected. Next, bits to numbers: uniform floats without treacherous zeros and unbiased integers in a range. Finally, sampling algorithms that transform uniforms into any distribution: inversion, rejection, the polar method, Ziggurat, the alias method and the Gumbel-max trick. Practical management of seeds and streams for reproducibility is the subject of generators and streams; here we study their underlying mechanisms.
Inside pseudorandom generators
All designs are variations on the same question: how much complexity to put in and how much in . Congruential generators and Mersenne Twister put almost everything in and use a simple output; PCG uses a simple transition and a mixing output; counter-based generators take the idea to the extreme, with and all complexity in .
Congruential generators and their lattice: RANDU
The linear congruential generator (LCG) is with . Its period depends on , and in a completely known way. If , the Hull–Dobell theorem (Knuth, vol. 2, §3.2.1.2) says the period is maximal, , if and only if , is divisible by every prime dividing , and is a multiple of 4 if is. If and with , the maximum is , attained if and only if or and the seed is odd.
RANDU, the generator in IBM’s scientific library for System/360 in the 1960s, is the textbook example of what can go wrong:
The multiplier was chosen because multiplication by it is a shift and two additions, and , so with an odd seed the period is . So far, nothing serious. The problem is its square:
Since and , it follows that . Dividing by ,
Each triple of consecutive outputs lies on one of the planes . How many? With , the left side lies strictly between and , so : fifteen parallel planes, with normal and separation . A three-dimensional simulation with RANDU does not explore the cube: it explores fifteen sheets, with no point between them.
np.random.default_rng(0)) and repeat the search: there is no special angle.The unsettling thing about the figure is the initial view: structure appears only from a few directions. That is why RANDU remained in use for years. A one-dimensional uniformity test or correlation between consecutive pairs does not detect it; you will check this in the lab.
RANDU is extreme, but not an exception. Marsaglia (1968) proved that -tuples of any congruential generator fall on at most parallel hyperplanes: for and , about 2344. RANDU uses 15 of that maximum. The spectral test of Coveyou and MacPherson, which Knuth makes the central criterion for choosing , measures the largest separation between hyperplanes in each dimension; a good multiplier makes it small in all low dimensions at once. But no multiplier eliminates the lattice: with the state is too small, and congruential generators modulo also have low bits with short periods (RANDU’s lowest bit is always 1, because all are odd).
Linear over the two-element field: xorshift and Mersenne Twister
Another family avoids multiplication. Marsaglia (2003) proposed xorshift generators, which apply shift and XOR operations to the state. The 32-bit one with shifts is
x ^= (x << 13) & 0xFFFFFFFF
x ^= x >> 17
x ^= (x << 5) & 0xFFFFFFFF
and has period : it visits every state except zero. If you view as a vector over (the two-element field, where addition is XOR), each shift is a matrix and each x ^= x << a multiplies by . The entire transition is linear: with . Mersenne Twister (Matsumoto and Nishimura, 1998), the default generator in Python, NumPy’s legacy interface and PyTorch on CPU, is the same idea at scale: 624 32-bit words (19937 useful bits, almost 2.5 KB), period , a Mersenne prime, and an output that applies a linear bijective transformation to the state, tempering. That linearity has a demonstrable price.
Proof
By the Cayley–Hamilton theorem, , also over . Then for every . Expanding , term is , leaving , which in is the same as the stated equality.
∎A truly random bit sequence obeys no short linear recurrence: its linear complexity, the length of the shortest recurrence reproducing the first bits, is around . Bits of a linear generator with bits of state have linear complexity at most , and the Berlekamp–Massey algorithm (1969) finds that recurrence from bits. This is TestU01’s LinearComp test, and exactly where Mersenne Twister fails: it passes almost the whole battery but has two clear failures, both in linear complexity, in Crush and BigCrush (L’Ecuyer and Simard, 2007). You will see it in the lab with xorshift32, where and 64 bits suffice.
Linearity has another consequence, this time for security. Since tempering is invertible, each 32-bit output of Mersenne Twister reveals a state word, and 624 consecutive outputs determine it entirely: from then on, all future outputs are predictable. No special ingenuity is needed, only linear algebra. We return to this when discussing cryptographic generators.
Modern successors retain the speed of the linear part and break its structure with a nonlinear output. xoshiro256** (Blackman and Vigna, 2021) has 256 bits of linear state, period , and returns a function involving multiplications and rotations of one word, the scrambler **, which destroys the recurrence in output bits.
PCG: a congruential generator with output permutation
PCG (O’Neill, 2014) starts from the opposite observation: the high bits of a congruential generator modulo are excellent; the low ones are bad. So it uses a 64- or 128-bit congruential transition and an output that uses the state’s high bits to decide how to permute the others. In PCG32 (64-bit state, 32-bit output):
- Advance the state: , with odd .
- On the previous state, apply a xorshift (
(s >> 18) ^ s) and keep 32 bits, positions 27 through 58. - Rotate those 32 bits by a number of positions given by the state’s highest 5 bits (
s >> 59).
The bits deciding rotation have the longest period, so the permutation changes from step to step without a short pattern, and low output bits inherit the quality of high state bits. The result passes BigCrush with 16 bytes of state and one multiplication per number. np.random.default_rng uses PCG64: 128-bit state, XSL RR output (XOR of the two halves and 64-bit rotation), period . In the lab you implement it from scratch and check that it matches NumPy bit for bit.
Period, equidistribution and test batteries
A “good” generator has properties that can be proved and properties that can only be tested.
- Period. Necessary but cheap: a period of suffices for any reasonable use in a single stream. Astronomical periods () do not buy statistical quality by themselves.
- Equidistribution. A generator with -bit outputs is -distributed to bits of accuracy if, over its complete period, each of the cells formed by the high bits of consecutive outputs appears the same number of times (except sometimes the all-zero cell). Mersenne Twister is 623-distributed to 32 bits. This is a structural guarantee about the entire period, not the numbers you will use.
- Empirical batteries. TestU01 (L’Ecuyer and Simard, 2007) groups dozens of tests into SmallCrush, Crush and BigCrush; PractRand applies increasingly long tests until the generator fails or time runs out. Each test computes a statistic whose distribution is known if the numbers are independent and uniform, and checks whether the observed value is plausible. A generator that reproducibly fails a test (with value , not ) has a defect; passing all proves nothing, only that the defect, if any, is not one these tests seek.
Lab: generators from scratch and statistical tests
Start by checking RANDU’s arithmetic: the multiplier’s square, the fifteen integers and Marsaglia’s bound.
import numpy as np
a, m = 65539, 2**31
print("a² mod 2^31 =", a * a % m, " 6a − 9 =", 6 * a - 9, " a mod 8 =", a % 8)
def randu(seed, n):
x, out = seed, np.empty(n, dtype=np.int64)
for i in range(n):
x = (a * x) % m
out[i] = x
return out
x = randu(1, 30_000)
comb = x[2:] - 6 * x[1:-1] + 9 * x[:-2] # x_{n+2} − 6x_{n+1} + 9x_n, en enteros exactos
print("restos módulo 2^31:", set((comb % m).tolist()))
print("valores de k:", sorted(set((comb // m).tolist())))
print(f"separación entre planos 1/√118 = {1 / np.sqrt(118):.4f}")
print(f"cota de Marsaglia (3!·2^31)^(1/3) = {(6 * m) ** (1 / 3):.0f} planos")
print("¿todas las salidas impares?", bool(np.all(x % 2 == 1)))Now the four generators according to their specifications: MINSTD (Park and Miller’s congruential generator, , ), RANDU, xorshift32 and PCG32. For PCG32 the output is checked against O’Neill’s demonstration program (pcg32-demo, seed 42 and sequence 54), which starts with 0xa15c02b7.
import numpy as np
M32, M64 = 0xFFFFFFFF, 0xFFFFFFFFFFFFFFFF
def lcg(a, c, m, seed, n):
x, out = seed, np.empty(n)
for i in range(n):
x = (a * x + c) % m
out[i] = x / m
return out
def xorshift32(seed, n):
x, out = seed, np.empty(n)
for i in range(n):
x ^= (x << 13) & M32
x ^= x >> 17
x ^= (x << 5) & M32
out[i] = x / 2**32
return out
class PCG32:
MULT = 6364136223846793005
def __init__(self, seed, seq):
self.inc = ((seq << 1) | 1) & M64 # el incremento c tiene que ser impar
self.state = 0
self.next()
self.state = (self.state + seed) & M64
self.next()
def next(self):
old = self.state
self.state = (old * self.MULT + self.inc) & M64
xs = (((old >> 18) ^ old) >> 27) & M32 # xorshift y 32 bits del medio
rot = old >> 59 # los 5 bits más altos deciden la rotación
return ((xs >> rot) | (xs << ((-rot) & 31))) & M32
def floats(self, n):
return np.array([self.next() for _ in range(n)]) / 2**32
def float53(self):
"""Flotante de 53 bits con dos salidas de 32: 27 bits altos de una y 26 de otra (como Python)."""
a, b = self.next() >> 5, self.next() >> 6
return (a * 2**26 + b) * 2.0**-53
p = PCG32(42, 54)
print("PCG32(42, 54):", [hex(p.next()) for _ in range(3)], " referencia: 0xa15c02b7 0x7b47f409 0xba1d3330")
q = PCG32(42, 54)
print("flotantes de 53 bits:", [q.float53() for _ in range(2)])
N = 3 * 2**16
muestras = {
"RANDU": lcg(65539, 0, 2**31, 1, N),
"MINSTD": lcg(16807, 0, 2**31 - 1, 1, N),
"xorshift32": xorshift32(2463534242, N),
"PCG32": PCG32(42, 54).floats(N),
"PCG64 (NumPy)": np.random.default_rng(0).random(N),
}
print({k: v[:3].round(4).tolist() for k, v in muestras.items()})float53 is the 53-bit float conversion studied below; for the tests 32-bit resolution, , suffices because none looks beyond the high 8 bits. The four tests that follow are small versions of TestU01’s. Each returns an value: the probability, if numbers really were independent and uniform, of seeing a statistic at least as extreme.
- One-dimensional chi-square: 64 equal bins in .
- Serial correlation: the coefficient between and ; under independence, is approximately standard normal.
- Three-dimensional chi-square: disjoint triples in cells.
- Birthday spacings (Marsaglia): distribute “birthdays” among “days” (here, cells formed from triples), sort them and count repeated spacings between consecutive birthdays. Under the null hypothesis that number is approximately Poisson with mean ; 128 repetitions are summed and compared with a Poisson of mean 256.
import numpy as np
from scipy import stats
def bateria(u):
n = len(u)
p_chi1 = stats.chisquare(np.bincount((u * 64).astype(int), minlength=64)).pvalue
r = np.corrcoef(u[:-1], u[1:])[0, 1]
p_corr = 2 * stats.norm.sf(abs(r) * np.sqrt(n))
tri = u[: n // 3 * 3].reshape(-1, 3)
c = (tri * 10).astype(int)
p_chi3 = stats.chisquare(np.bincount(c[:, 0] * 100 + c[:, 1] * 10 + c[:, 2], minlength=1000)).pvalue
d = (tri * 256).astype(np.int64)
dias = d[:, 0] * 65536 + d[:, 1] * 256 + d[:, 2] # 2^24 días
rep = 0
for j in range(len(dias) // 512):
esp = np.sort(np.diff(np.sort(dias[512 * j: 512 * (j + 1)])))
rep += int(np.sum(esp[1:] == esp[:-1]))
lam = 2 * (len(dias) // 512)
p_bday = min(1.0, 2 * min(stats.poisson.cdf(rep, lam), stats.poisson.sf(rep - 1, lam)))
return p_chi1, p_corr, p_chi3, rep, lam, p_bday
print(f"{'generador':14s} {'χ² 1D':>8s} {'corr.':>8s} {'χ² 3D':>9s} {'cumpleaños':>18s}")
for nombre, u in muestras.items():
p1, pc, p3, rep, lam, pb = bateria(u)
print(f"{nombre:14s} {p1:8.3f} {pc:8.3f} {p3:9.1e} {rep:5d}/{lam} p={pb:.1e}")The table tells RANDU’s story in numbers. It passes one-dimensional chi-square and serial correlation effortlessly: its marginal values are uniform and consecutive pairs are not linearly correlated. But three-dimensional chi-square gives an value on the order of , and birthday spacings show about 2900 repetitions where 256 are expected: RANDU’s birthdays fall on a regular lattice and their distances repeat much more than by chance. MINSTD, xorshift32 and both PCGs show nothing similar. Notice, however, PCG64’s in one-dimensional chi-square and xorshift32’s in three dimensions: with twenty values in the table, one or two falling below is expected by chance alone. What reveals a defect is not an isolated small but an astronomically small one reproducible with another seed.
Passing does not absolve xorshift32. The linear-complexity test sinks it with 64 bits:
import numpy as np
def berlekamp_massey(bits):
"""Longitud de la recurrencia lineal más corta (sobre F2) que genera la sucesión de bits."""
s = np.array(bits, dtype=np.uint8)
n = len(s)
c = np.zeros(n + 1, dtype=np.uint8); b = np.zeros(n + 1, dtype=np.uint8)
c[0] = b[0] = 1
L, mm = 0, -1
for i in range(n):
d = s[i] ^ (np.dot(c[1:L + 1], s[i - L:i][::-1]) & 1) if L else s[i]
if d:
t = c.copy()
c[i - mm:] ^= b[: n + 1 - (i - mm)]
if 2 * L <= i:
L, mm, b = i + 1 - L, i, t
return L
def bits_bajos(gen_next, n):
return [gen_next() & 1 for _ in range(n)]
estado = [2463534242]
def xs_next():
x = estado[0]
x ^= (x << 13) & 0xFFFFFFFF; x ^= x >> 17; x ^= (x << 5) & 0xFFFFFFFF
estado[0] = x
return x
pcg = PCG32(42, 54)
for N in (64, 400):
print(f"N = {N}: xorshift32 → {berlekamp_massey(bits_bajos(xs_next, N)):3d}"
f" PCG32 → {berlekamp_massey(bits_bajos(pcg.next, N)):3d} (azar: ≈ N/2 = {N // 2})")The low bit of xorshift32 obeys a recurrence of order 32, its state dimension, and Berlekamp–Massey finds it with 64 bits; with 400 bits it is still 32. PCG32’s has linear complexity , like a random bit, because state-dependent rotation is nonlinear. For Mersenne Twister the number would be 19937, and about 40000 bits suffice to see it: this is the test it fails in BigCrush.
From bits to numbers
A generator produces bit words. Almost always you need something else: a float in , an integer in . Both conversions have pitfalls.
Uniform floats: 53 bits and endpoints
An float64 has a 53-bit significand (floating-point representation). Standard conversion takes the high 53 bits of a 64-bit word and scales them:
These are equally spaced values, all exactly representable and equiprobable, with largest . This is what NumPy and PCG64 do; Python and Mersenne Twister combine 27 and 26 bits from two 32-bit outputs for the same result. The naive alternative, x / 2**64 in floating point, is worse than it seems: the quotient is rounded to the nearest float, and since near 1 floats are separated by , all round to exactly 1.0. Its probability is , small, but it breaks the promise that and produces an unexpected value.
The lower endpoint is more dangerous. With standard conversion, has probability , and in float32 (24-bit significand) the analogous conversion gives . One dropout mask over a large batch’s activations, or Gumbel noise for a batch of 2048 sequences over a 50000-token vocabulary, consumes on the order of uniforms: the expected number of exact zeros is around 6. And . The solutions are simple:
- use when taking :
-np.log1p(-u)instead of-np.log(u); - or generate in the open interval, ;
- or check which interval your library returns: cuRAND’s
curand_uniform, for example, returns values in , excluding 0 and including 1 (as its documentation states).
import numpy as np
# 1. la conversión de NumPy es (x >> 11) * 2^-53 sobre la salida de PCG64
raw = np.random.PCG64(0).random_raw(4)
print("random() == (x >> 11)·2^-53:", np.array_equal(np.random.default_rng(0).random(4), (raw >> np.uint64(11)) * 2.0**-53))
# 2. x / 2^64 en coma flotante: los x más altos se redondean a 1.0
for x in (2**64 - 1025, 2**64 - 1024, 2**64 - 1):
print(f"x = 2^64 − {2**64 - x:4d}: x / 2^64 = {float(x) / 2**64!r}")
# 3. convertir un float64 casi 1 a float32 también da 1.0
print("float32(1 − 2^-30) == 1.0:", np.float32(1 - 2.0**-30) == 1.0)
# 4. ceros exactos en float32: P(u = 0) = 2^-24
g = np.random.default_rng(1)
ceros, n = 0, 0
for _ in range(8):
u = g.random(2**22, dtype=np.float32)
ceros += int(np.count_nonzero(u == 0)); n += u.size
print(f"{n:,} uniformes float32: {ceros} ceros exactos (esperados {n / 2**24:.1f})")
with np.errstate(divide="ignore"):
print("−log(0) =", -np.log(np.float32(0.0)), " −log1p(−0) =", -np.log1p(-np.float32(0.0)))The cell confirms all three pitfalls: the highest 1024 values of give exactly 1.0, rounding to float32 also produces ones, and among float32 uniforms exact zeros appear (one in this run, when 2 are expected), each an waiting for a logarithm.
Range integers without modulo bias
To choose an index in with a uniform word of bits, the temptation is x % n. If does not divide , remainders are not equiprobable: there are values of with remainder , equal to for and for the rest. With small relative to relative bias is at most and usually negligible, but grows with . The extreme case is instructive: with and , remainders below are twice as probable as the rest, and the first third of the range occurs half the time instead of one third.
The classic solution is rejection: discard and keep x % n. It is correct but performs a division for every number, the most expensive integer operation. Lemire (2019) avoids nearly all divisions with an -bit multiplication. This is the method used by NumPy’s Generator.integers (its documentation cites the paper).
Proof
Fix . The with are those satisfying , and for them . The map is injective, and its image is exactly the set of with : given one, is an integer less than . Thus the of class form a residue class modulo inside . Interval has length , a multiple of , and therefore contains exactly elements of any residue class. Each thus has the same number of accepted , . Summing over the values of , of the values of are accepted, so are rejected, with probability , and .
∎The practical trick is that , so (with its division) only needs computing when , which happens with probability . Almost always, a range integer costs one multiplication.
import numpy as np
from scipy import stats
g = np.random.default_rng(3)
n = 3 * 2**30
x = (g.bit_generator.random_raw(1_000_000) >> np.uint64(32)).astype(np.uint64) # palabras de 32 bits
mod = x % np.uint64(n)
print(f"x % n: fracción en el primer tercio = {np.mean(mod < n // 3):.4f} (debería ser 0.3333)")
def lemire(xs, n, w=32):
"""Vectorizado: devuelve los h aceptados y cuántos se rechazaron."""
prod = xs * np.uint64(n) # cabe en 64 bits porque x, n < 2^32
h, l = prod >> np.uint64(w), prod & np.uint64(2**w - 1)
t = (2**w) % n
ok = l >= np.uint64(t)
return h[ok], int(np.count_nonzero(~ok))
h, rech = lemire(x, n)
print(f"Lemire: fracción en el primer tercio = {np.mean(h < n // 3):.4f}, rechazados {rech / len(x):.4f} (t/2^32 = {2**32 % n / 2**32:.4f})")
tercios = np.bincount((h // (n // 3)).astype(int), minlength=3)
print("chi-cuadrado de los tercios, p =", round(stats.chisquare(tercios).pvalue, 3))
_, r6 = lemire(x, 6)
print("con n = 6, rechazados:", r6, " (t = 2^32 mod 6 =", 2**32 % 6, ")")Counter-based generators
A GPU has tens of thousands of threads, each needing its own numbers. With a stateful generator there are two poor options: a shared generator (and a queue to use it) or a state per thread (2.5 KB per thread with Mersenne Twister, plus the problem of ensuring streams do not overlap). Salmon, Moraes, Dror and Shaw (2011) proposed changing the design fundamentally.
The consequences are exactly what parallel computing needs:
- Random access. Number is computed directly, without generating previous ones: skipping is free.
- Streams by key. Two distinct keys give two distinct permutations of counter space, unrelated to each other. There is no need to prove two streams do not overlap: they are two different functions evaluated at the same points.
- Minimal state and reproducibility. Thread of a kernel uses in its registers; the result does not depend on the number of threads or their execution order.
Philox replaces a cipher’s boxes with integer products. One Philox4x32 round takes four 32-bit words, multiplies two by constants, and combines the high and low halves of the 64-bit products with the other two words and the key using XOR, changing positions; the key is incremented with Weyl constants between rounds. Multiplication is the operation that mixes most per cycle on a GPU. With the standard version’s ten rounds, Philox passes SmallCrush, Crush and BigCrush, as do all Random123 generators according to its documentation. Threefry adapts Threefish, the block cipher of SHA-3 candidate Skein, using addition, rotations and XOR (ARX), and is JAX’s default generator (Threefry-2x32). Random123, which implements both, explicitly warns that they are unsuitable for cryptography: rounds are reduced to the minimum passing statistical tests, not the number resisting an adversary.
Where they are: cuRAND offers Philox4_32_10 alongside XORWOW (its default generator, a xorshift with a Weyl counter), MRG32k3a and MTGP32; PyTorch CUDA kernels use Philox with seed and offset state, so each random operation reserves a counter segment; NumPy offers np.random.Philox (the 4x64 variant).
import numpy as np
M64, M128 = 2**64 - 1, 2**128 - 1
# --- PCG64 (XSL RR): estado de 128 bits, salida de 64
bg = np.random.PCG64(0)
s, inc = bg.state["state"]["state"], bg.state["state"]["inc"]
print(f"estado inicial de default_rng(0): {s:#x}\nincremento: {inc:#x}")
MULT = 0x2360ED051FC65DA44385DF649FCCF645
def pcg64_next():
global s
s = (s * MULT + inc) & M128 # paso del congruencial de 128 bits
v = (s >> 64) ^ (s & M64) # XSL: XOR de las dos mitades
rot = s >> 122 # RR: rotación según los 6 bits altos
return ((v >> rot) | (v << ((-rot) & 63))) & M64
mio = [pcg64_next() for _ in range(5)]
print("PCG64 desde cero == NumPy:", mio == [int(v) for v in np.random.PCG64(0).random_raw(5)])
# --- Philox4x64-10: 10 rondas de multiplicaciones de 128 bits
MUL = (0xD2E7470EE14C6C93, 0xCA5A826395121157)
WEYL = (0x9E3779B97F4A7C15, 0xBB67AE8584CAA73B)
def philox4x64(ctr, key, rondas=10):
c, k = list(ctr), list(key)
for _ in range(rondas):
p0, p1 = MUL[0] * c[0], MUL[1] * c[2]
c = [(p1 >> 64) ^ c[1] ^ k[0], p1 & M64, (p0 >> 64) ^ c[3] ^ k[1], p0 & M64]
k = [(k[0] + WEYL[0]) & M64, (k[1] + WEYL[1]) & M64]
return c
ref = [int(v) for v in np.random.Philox(key=7).random_raw(8)]
print("Philox desde cero == NumPy:", philox4x64([1, 0, 0, 0], [7, 0]) + philox4x64([2, 0, 0, 0], [7, 0]) == ref,
" (NumPy incrementa el contador antes de usarlo)")
# acceso aleatorio: el bloque 10^12, directamente
directo = philox4x64([10**12 + 1, 0, 0, 0], [7, 0])
saltado = np.random.Philox(key=7, counter=[10**12, 0, 0, 0]).random_raw(4)
print("bloque 10^12 sin generar los anteriores:", directo == [int(v) for v in saltado])Inside parallel streams
With a stateful generator there are two clean ways to distribute streams. The first is skipping: PCG64 advances steps in , because composing congruential generators gives another congruential generator (, computable by repeated squaring), and jumped() skips about steps; Mersenne Twister has a skip but it is expensive (computed with polynomials over of degree 19937), and NumPy offers it as MT19937.jumped(), advancing steps. The second is seeding each stream with a high-quality mix of the root seed and its position in the tree, which is what SeedSequence does.
Seeding with semilla + i mixes two risks. One is bookkeeping: process 1 of an experiment with seed 0 and process 0 of an experiment with seed 1 receive the same seed, and therefore the same stream. The other depends on how the generator converts seed to state. If the conversion is nearly linear, consecutive seeds give consecutive states and related streams (in a congruential generator with , difference does not depend on , as shown in an exercise in the reproducibility lesson). Mersenne Twister also has its own weakness: from states with many zeros its mixing is slow, and 2002 initialization was redesigned to make those states unlikely. With a counter-based generator the problem does not arise: each process uses its own key, and stream independence is that of permutations for different keys.
Pseudorandom versus cryptographic generators
Everything above seeks statistical quality: no reasonable test distinguishes outputs from randomness. A cryptographically secure generator (CSPRNG) promises something much stronger: no efficient algorithm seeing previous outputs can predict the next bit with probability appreciably greater than . Mersenne Twister and congruential generators fail trivially: state is reconstructed from a few outputs (624 for Mersenne Twister, by the linearity just seen) and predicts everything else. PCG is much harder to invert, but is not designed to resist an adversary either, and attacks recovering its state from output have been published. Therefore:
- Never use
randomornumpy.randomfor secrets: session tokens, passwords, keys, reset links or identifiers that must not be guessable. - Use Python’s
secretsmodule (PEP 506), which takes bytes from the operating system’s cryptographic generator (os.urandom), or your platform’s CSPRNG. - How to detect it: security static analyzers flag it (Bandit, for example, flags uses of
randomwith rule B311), and code review should look forrandom.in any path generating something an attacker wants to guess.
import secrets
token = secrets.token_urlsafe(32) # 32 bytes del CSPRNG del sistema, en base64 para URL
print("longitud del token:", len(token), "caracteres; ¿es str?", isinstance(token, str))
print("entero uniforme en [0, 10^6):", 0 <= secrets.randbelow(10**6) < 10**6)
print("comparación en tiempo constante:", secrets.compare_digest("abc", "abc"))The relationship is asymmetric: a CSPRNG is an excellent PRNG (though slower), but an excellent PRNG is not a CSPRNG. Philox and Threefry, despite their origin in block ciphers, are not either, as their authors warn.
The inverse transform as an algorithm
From here we take the source of uniforms as given and build samplers. You already know the first as a theorem: if is a distribution function and its generalized inverse, then with has distribution function (the probability integral transform). The key is equivalence , valid for any right-continuous , with jumps or flat segments.
The figure shows the geometric intuition: the slope of determines how many uniforms fall in each region. Where is steep (high density), a small interval of captures a large interval of ; where flat, none. Atoms appear as vertical jumps capturing an interval of whose length equals their mass.
Closed formulas. Exponential: , ; since is also uniform, it is often written , but that form breaks with , and -np.log1p(-u) is also exact for small . Cauchy: . Weibull, logistic, Pareto and Gumbel also have explicit inverses.
Numerical inversion. For gamma or normal, is evaluated with special functions but has no formula. For each , solve with a bracketing method like Brent (secant and Brent): is monotone and bracket with guarantees convergence. It costs dozens of evaluations of per sample: exact but slow.
Tables with interpolation. Evaluate once on a grid and invert by linear (or better, polynomial) interpolation of pairs . Per-sample cost is a binary search, but error depends on the curvature of , which explodes in tails where density is small. Serious implementations, such as NumericalInversePolynomial of scipy.stats.sampling (the PINV method of Derflinger, Hörmann and Leydold, 2010), control error in , , the natural quantity: if the approximation of is monotone and its error in is at most , the sample distribution function is at distance at most from (in Kolmogorov distance, the same as the KS test), even though error in in a tail can be much larger.
Lab: inversion
import numpy as np, time
from scipy import stats, optimize, special
g = np.random.default_rng(2024)
u = g.random(100_000)
x_exp = -np.log1p(-u) # Exp(1)
x_cau = np.tan(np.pi * (u - 0.5)) # Cauchy estándar
print("KS exponencial p =", round(stats.kstest(x_exp, "expon").pvalue, 4),
" KS Cauchy p =", round(stats.kstest(x_cau, "cauchy").pvalue, 4))
# Gamma(2.5): F es la gamma incompleta regularizada; F^{-1} no tiene fórmula cerrada
F = lambda x: special.gammainc(2.5, x)
uu = g.random(2000)
exacta = special.gammaincinv(2.5, uu) # referencia de SciPy
t0 = time.perf_counter()
x_brent = np.array([optimize.brentq(lambda x: F(x) - ui, 0.0, 60.0, xtol=1e-12) for ui in uu])
t_brent = (time.perf_counter() - t0) / len(uu)
rejilla = np.linspace(0, 30, 4097)
Fr = F(rejilla)
t0 = time.perf_counter()
x_tabla = np.interp(g.random(1_000_000), Fr, rejilla)
t_tabla = (time.perf_counter() - t0) / 1e6
print(f"Brent: error máx en x {np.max(np.abs(x_brent - exacta)):.1e}, {t_brent * 1e6:.1f} µs por muestra")
err_tabla = np.abs(np.interp(uu, Fr, rejilla) - exacta)
print(f"tabla: error máx en x {err_tabla.max():.1e}, {t_tabla * 1e9:.0f} ns por muestra"
f" (cociente de tiempos ≈ {t_brent / t_tabla:.0f})")
peor = uu[np.argmax(err_tabla)]
print(f"el peor caso de la tabla está en u = {peor:.4f} (una cola)")
from scipy.stats.sampling import NumericalInversePolynomial
pinv = NumericalInversePolynomial(stats.gamma(2.5), random_state=1)
print("PINV: error en u máximo", f"{pinv.u_error().max_error:.1e}",
" KS p =", round(stats.kstest(pinv.rvs(100_000), stats.gamma(2.5).cdf).pvalue, 3))Two output details deserve attention. First, the two Kolmogorov–Smirnov values are identical. This is no accident: the KS statistic is invariant under monotone transformations, and comparing with is exactly the same as comparing with the uniform; the test evaluates the uniforms, not the formula. To detect an error in an inversion formula it must be compared with another reference, as with gamma. Second, Brent gives nearly machine precision but costs hundreds of times more per sample than the table, and the table fails precisely where density is small, in the tails. PINV combines the best: one-time setup and certified error on the order of .
Rejection sampling
When even is intractable, but you can evaluate density (even unnormalized), rejection works with only an easy-to-sample proposal and a constant raising it above .
The picture that explains everything: point is uniform under the graph of , a region of area . Conditioning on falling under the graph of (area 1) gives a uniform point under , and the horizontal coordinate of a uniform point under a density has that density. The probability of falling under is the area ratio, . You will give the full analytic proof in the guided exercise.
Three practical consequences:
- Normalization is unnecessary. If you know only and , with , the algorithm works the same with ; acceptance becomes . This is common in Bayesian statistics, where the posterior normalizing constant is unknown.
- The proposal must have tails at least as heavy as the target. If in a tail, no exists. You can sample a normal with a Cauchy proposal, but not a Cauchy with a normal proposal.
- If is too small, the result is silently wrong. Where all proposals are accepted, but too few are proposed, and samples follow normalized density . No exception warns you.
Collapse in high dimensions
Rate is an innocent number in one dimension. In dimensions, for targets and proposals factoring by coordinates, constants multiply: . Acceptance falls exponentially with dimension.
The cleanest example is in the figure: sampling the unit ball of by proposing points from cube . Acceptance is the volume ratio,
which is in the plane, in and in , about 40 million proposals per sample. Almost all the cube’s volume lies in its corners, far from the ball. The same happens with a normal proposal slightly wider than the target: with and , , ratio reaches its maximum at the origin, , and with and acceptance is . Thus pure rejection is a low-dimensional tool, and in high dimensions one turns to MCMC, which no longer produces independent samples but does not pay that exponential price. The same curse reappears in Monte Carlo integration in high dimensions.
Lab: rejection
import numpy as np
from scipy import stats, special
g = np.random.default_rng(7)
def rechazo(f, propuesta, densidad_g, M, n):
"""Vectorizado por tandas; devuelve n muestras y el número de propuestas usadas."""
out, usadas = [], 0
while sum(len(o) for o in out) < n:
m = int(1.2 * M * (n - sum(len(o) for o in out))) + 16
y = propuesta(m)
acepta = g.random(m) * M * densidad_g(y) <= f(y)
out.append(y[acepta]); usadas += m
x = np.concatenate(out)
return x[:n], usadas * n / len(x)
# Beta(2, 5) desde la uniforme: M* = f(moda) = f(1/5)
f_beta = lambda x: 30 * x * (1 - x) ** 4
M = f_beta(0.2)
x, usadas = rechazo(f_beta, g.random, np.ones_like, M, 100_000)
print(f"Beta(2,5): M = {M:.4f}, 1/M = {1 / M:.4f}, aceptación observada = {len(x) / usadas:.4f},"
f" KS p = {stats.kstest(x, 'beta', args=(2, 5)).pvalue:.3f}")
# normal truncada a [a, ∞): ingenua frente a propuesta exponencial desplazada (Robert, 1995)
a = 4.0
print(f"ingenua (normal y quedarse con X > {a}): aceptación = 1 − Φ(a) = {stats.norm.sf(a):.2e}")
lam = (a + np.sqrt(a * a + 4)) / 2 # tasa óptima de la exponencial
f_tn = lambda x: np.exp(-x * x / 2) # sin normalizar
g_tn = lambda x: lam * np.exp(-lam * (x - a))
M_tn = np.exp(lam * lam / 2 - lam * a) / lam # sup de f/g, alcanzado en x = λ
x, usadas = rechazo(f_tn, lambda m: a + g.exponential(1 / lam, m), g_tn, M_tn, 100_000)
Z = np.sqrt(2 * np.pi) * stats.norm.sf(a) # masa de f sin normalizar
print(f"exponencial: aceptación teórica Z/M = {Z / M_tn:.4f}, observada = {len(x) / usadas:.4f},"
f" KS p = {stats.kstest(x, stats.truncnorm(a, np.inf).cdf).pvalue:.3f}")
# dimensión: bola desde el cubo y normal desde una normal más ancha
for d in (2, 5, 8):
pts = g.uniform(-1, 1, size=(200_000, d))
obs = np.mean((pts ** 2).sum(1) <= 1)
exacta = np.pi ** (d / 2) / special.gamma(d / 2 + 1) / 2**d
print(f"bola d = {d:2d}: exacta {exacta:.5f}, observada {obs:.5f}")
for d in (1, 10, 100):
print(f"N(0, I) desde N(0, 1.1² I), d = {d:3d}: aceptación 1.1^-d = {1.1 ** -d:.2e}")The figures confirm the theory. Beta(2, 5) from the uniform accepts 40.7% ( with ). For the normal truncated at , the naive method accepts 3 of every 100000 normals, while the shifted exponential with Robert’s optimal rate accepts 97.5%: proposal choice changes cost by four orders of magnitude. And ball acceptance falls from in the plane to less than in eight dimensions.
Fast normals: polar and Ziggurat
The normal is the most sampled distribution and deserves dedicated algorithms. The starting point is Box–Muller: with independent uniforms,
are two independent standard normals. It costs one logarithm, square root, sine and cosine per pair.
The polar method of Marsaglia and Bray (1964) removes sine and cosine. Generate uniformly in square and reject it if or ; if accepted, return
It is correct for a geometric reason. The accepted point is uniform in the unit disk, so in polar coordinates , with : is uniform on , is uniform on , and both are independent. Also and . Substituting, and : this is Box–Muller with and , and rejection has manufactured sine and cosine for free. It accepts with probability , so consumes an average of uniforms per pair.
The Ziggurat of Marsaglia and Tsang (2000) goes further: in the vast majority of cases it evaluates no function. It covers half-density , (unnormalized: rejection does not need it), with horizontal layers of equal area . The bottom layer consists of rectangle and the entire region under beyond point , the tail; its area, , is set equal to . To sample it, use a rectangle of the same area, : a point with falls in the rectangular part, and one with , occurring with probability equal to the tail’s relative mass, is replaced by a tail sample. Above it, layer is rectangle , with and decreasing to the top; equality of areas gives the recurrence
and is adjusted (by bisection) so the last layer closes exactly at the top, . Since layers have equal area, choosing a random layer and a uniform point within it chooses a uniform point in their union, containing the region under : rejection sampling with a proposal made of rectangles. The algorithm:
- Choose a layer uniform in and , with the base width.
- Fast path: if , the point lies under the curve regardless of height, because and is the layer’s maximum height (at the base, the condition is ): accept .
- Otherwise, if it is the base, the sample is in the tail: generate it with Marsaglia’s tail method (1964), which repeats , until and returns .
- Otherwise you are in the wedge between and : generate uniform height in and accept if . Otherwise return to step 1.
The full normal is obtained with a sign bit. In the real implementation, step 1 and the comparison in step 2 use a single random integer and a precomputed table of : one random number, one lookup and one comparison.
The fraction of attempts resolved by the fast path is , because layer is chosen with probability and, within it, is uniform in . The next cell computes it for each : with 128 layers it is 97.2% and with 256, 98.5%. NumPy uses a 256-layer Ziggurat in Generator for normal, exponential and gamma, and its documentation presents it as 2 to 10 times faster than legacy-interface methods.
On the GPU the calculation changes. Ziggurat and rejection are branching algorithms: if one thread of a warp falls in the wedge and the other 31 do not, all wait for it to finish. GPU libraries therefore prefer branchless methods: cuRAND documentation says its normal-pair functions (curand_normal2) use Box–Muller.
Once you have independent standard normals, any multivariate normal comes from multiplication by the Cholesky factor of (Gaussian sampling with Cholesky); the cost of generating normals becomes secondary to that multiplication.
Lab: normals
import numpy as np, time, math
from scipy import stats, special
g = np.random.default_rng(11)
n = 200_000
def box_muller(n):
u1, u2 = 1.0 - g.random(n // 2), g.random(n // 2) # u1 en (0, 1]: nunca log(0)
r = np.sqrt(-2 * np.log(u1))
return np.concatenate([r * np.cos(2 * np.pi * u2), r * np.sin(2 * np.pi * u2)])
def polar(n):
out, total = [], 0
while total < n:
v = g.uniform(-1, 1, size=(int(0.66 * (n - total)) + 16, 2))
s = (v ** 2).sum(1)
ok = (s < 1) & (s > 0)
v, s = v[ok], s[ok]
k = v * np.sqrt(-2 * np.log(s) / s)[:, None]
out.append(k.ravel()); total += k.size
return np.concatenate(out)[:n]
# tablas del Ziggurat (n = 128) por bisección sobre r
f = lambda x: np.exp(-0.5 * x * x)
finv = lambda y: np.sqrt(-2 * np.log(y))
cola = lambda r: np.sqrt(np.pi / 2) * special.erfc(r / np.sqrt(2))
def tablas(N):
def construir(r):
v = r * f(r) + cola(r); xs = [r]
for _ in range(N - 2):
y = v / xs[-1] + f(xs[-1])
if y >= 1: return None, v
xs.append(finv(y))
return xs, v
lo, hi = 0.5, 10.0
for _ in range(100):
mid = (lo + hi) / 2
xs, v = construir(mid)
if xs is None or xs[-1] * (1 - f(xs[-1])) < v: lo = mid
else: hi = mid
xs, v = construir(hi)
return hi, v, np.array([v / f(hi)] + xs + [0.0])
for N in (8, 32, 128, 256):
r, v, X = tablas(N)
print(f"n = {N:3d}: r = {r:.6f}, v = {v:.6e}, vía rápida = {np.mean(X[1:] / X[:-1]):.4f}")
r, v, X = tablas(128)
def via_lenta(i, xi):
"""Intento que no ha pasado la vía rápida: cola (capa 0) o cuña. None si se rechaza."""
if i == 0:
while True: # cola de Marsaglia (1964)
a, b = -math.log(1 - g.random()) / r, -math.log(1 - g.random())
if 2 * b > a * a:
return r + a
y = f(X[i]) + g.random() * (f(X[i + 1]) - f(X[i]))
return xi if y < f(xi) else None
def intento_completo():
while True:
i = int(g.integers(0, 128)); xi = g.random() * X[i]
if xi < X[i + 1]:
return xi
v = via_lenta(i, xi)
if v is not None:
return v
def ziggurat(n):
capa = g.integers(0, 128, n)
x = g.random(n) * X[capa]
rapida = x < X[capa + 1] # la comparación de la vía rápida, vectorizada
out = x.copy()
lentas = np.flatnonzero(~rapida)
for k in lentas: # cada intento lento se resuelve, uno a uno, en Python
v = via_lenta(int(capa[k]), x[k])
out[k] = v if v is not None else intento_completo() # si se rechaza, se repite el algoritmo entero
signo = np.where(g.random(n) < 0.5, -1.0, 1.0)
return signo * out, rapida.mean(), len(lentas)
for nombre, fn in [("Box-Muller", box_muller), ("polar", polar), ("NumPy (Ziggurat 256)", g.standard_normal)]:
t0 = time.perf_counter(); z = fn(n); dt = time.perf_counter() - t0
print(f"{nombre:22s} KS p = {stats.kstest(z, 'norm').pvalue:.3f} {dt / n * 1e9:6.1f} ns por muestra")
t0 = time.perf_counter(); z, frac, lentas = ziggurat(n); dt = time.perf_counter() - t0
print(f"{'Ziggurat simplificado':22s} KS p = {stats.kstest(z, 'norm').pvalue:.3f} {dt / n * 1e9:6.1f} ns por muestra"
f" (vía rápida {frac:.3f}; {lentas} intentos lentos en Python)")The and for match Marsaglia and Tsang’s paper (, ), and all four samplers pass the Kolmogorov–Smirnov test. Times, however, need care: in NumPy what matters is how many array passes each method makes, not how many functions it evaluates. Vectorized Box–Muller and polar cost practically the same; the simplified Ziggurat is several times slower than both, because it resolves slow attempts (2.8%, about 5500 of 200000) with a Python loop, by far the most expensive part per element; and standard_normal, a Ziggurat in C, beats them all. Ziggurat’s algorithmic advantage (almost never evaluating ) materializes only in compiled scalar code, where each sample is a handful of instructions.
Discrete distributions
To sample a categorical distribution with probabilities , three useful algorithms have very different costs.
The Walker–Vose alias method
Walker (1974) observed that any distribution over values can be written as a uniform mixture of distributions of at most two values. Scale probabilities to , whose mean is 1. Columns with are small and the others large. Each step takes a small and a large , fills column to height 1 with mass from (recording and ), and subtracts from the amount donated, . To sample, choose a uniform column and an ; if return , otherwise .
Proof
Invariant. At the start of each step, the sum of of unclosed columns equals their number. Initially . A step closes column , contributing , and removes from : the sum decreases by , as does the number of open columns. Also remains nonnegative, because since .
Termination. If any small column remains open, by the invariant there must be one with , which is large; so the step is always possible while small ones remain. Each step closes one column, so there are at most steps, each in with two lists. Columns left open at the end all have (by the invariant, if none are small and the mean is 1) and are closed with .
Correctness. The mass of column is never created or destroyed: is distributed between the lower part of its own column, , and the upper parts of columns having it as alias, for each with . Since each column is chosen with probability ,
∎The two-list version is Vose’s (1991), who also studied floating-point robustness: rounding can leave a “large” column with at the end, and the correct way to finish is to close whatever remains in either list with .
The Gumbel-max trick
The standard Gumbel distribution has distribution function and is sampled by inversion: .
Proof
Call and . The density of is , and . Index wins if and all others fall below (ties have probability zero):
With substitution , , the integral is .
∎Its practical value lies in what it does not need: neither normalizing logits (use directly, without softmax), nor sequential cumulative sums. Everything is elementwise plus an argmax, perfectly parallel on a GPU. Taking the largest of gives a sample without replacement (the Gumbel-top- trick), and relaxing argmax with a temperature softmax gives the Gumbel-softmax estimator. It is also one way to implement token sampling. The numerical trap is the same as before: if , and that token always wins, regardless of its logit. Generate in the open interval.
Lab: discrete distributions and speed
import numpy as np, time
from scipy import stats
g = np.random.default_rng(5)
V = 2000 # un «vocabulario» con ley de Zipf
p = 1 / np.arange(1, V + 1) ** 1.1
p /= p.sum()
n = 200_000
def por_cdf(p, n):
return np.searchsorted(np.cumsum(p), g.random(n), side="right").clip(max=len(p) - 1)
def alias_walker(p):
"""Construcción directa O(n²): en cada paso, la columna abierta más baja y la más alta."""
m = len(p)
q = p * m
prob, alias = np.ones(m), np.arange(m)
abierta = np.ones(m, dtype=bool)
for _ in range(m - 1):
s = np.where(abierta, q, np.inf).argmin()
l = np.where(abierta, q, -np.inf).argmax()
if q[s] >= 1 - 1e-12: break
prob[s], alias[s], abierta[s] = q[s], l, False
q[l] -= 1 - q[s]
return prob, alias
def por_alias(prob, alias, n):
j = g.integers(0, len(prob), n)
return np.where(g.random(n) < prob[j], j, alias[j])
def por_gumbel(logits, n, lote=500):
out = []
for _ in range(n // lote):
u = g.random((lote, len(logits)))
u = np.where(u == 0.0, np.finfo(float).tiny, u) # U en (0, 1): ni −∞ ni +∞
out.append(np.argmax(logits - np.log(-np.log(u)), axis=1))
return np.concatenate(out)
t0 = time.perf_counter(); prob, alias = alias_walker(p); t_tabla = time.perf_counter() - t0
logits = np.log(p) + 3.7 # una constante cualquiera: Gumbel-max no normaliza
for nombre, fn in [("CDF + búsqueda binaria", lambda: por_cdf(p, n)),
("alias", lambda: por_alias(prob, alias, n)),
("Gumbel-max", lambda: por_gumbel(logits, n // 40))]:
t0 = time.perf_counter(); x = fn(); dt = time.perf_counter() - t0
obs = np.bincount(x, minlength=V)[:50] # las 50 categorías más probables, más el resto
esp = p[:50] * len(x)
obs = np.append(obs, len(x) - obs.sum()); esp = np.append(esp, len(x) - esp.sum())
print(f"{nombre:24s} χ² p = {stats.chisquare(obs, esp).pvalue:.3f} {dt / len(x) * 1e9:8.1f} ns por muestra")
print(f"construcción de la mesa de alias (versión O(n²) de esta celda): {t_tabla * 1e3:.0f} ms para n = {V}")All three pass the chi-square test. Per-sample alias is several times faster than binary search, which takes about steps per sample versus one lookup and one comparison. Gumbel-max is hundreds of times more expensive than both here, because it generates uniforms and two logarithms per sample. On a GPU, with the logit vector already in memory and one sample per sequence, the calculation reverses: Gumbel-max is an elementwise operation plus a reduction, without the CDF’s cumulative sum. Table construction in this cell is deliberately quadratic; in the code exercise you will write Vose’s linear one.
In libraries
| Tool | What’s inside | Purpose |
|---|---|---|
np.random.default_rng(semilla) | Generator over PCG64 | default sampling in NumPy |
np.random.Generator(np.random.Philox(clave)) | Philox4x64-10 | streams by key, random access with advance |
Generator.random, .integers | 53 bits per float; Lemire’s integer method | unbiased uniforms and integers |
Generator.standard_normal, .exponential | 256-layer Ziggurat | normals and exponentials |
Generator.choice(a, p=...) | categorical with probabilities | general discrete sampling |
scipy.stats.<dist>.rvs(random_state=rng) | distribution-specific methods | sampling any SciPy distribution |
scipy.stats.sampling | PINV, transformed rejection (UNU.RAN) | automatic inversion and rejection for custom densities |
scipy.stats.kstest, chisquare | goodness-of-fit tests | validate a sampler |
torch.Generator(device), torch.manual_seed | Mersenne Twister on CPU, Philox on CUDA | PyTorch randomness with explicit state |
secrets | operating system CSPRNG | tokens, keys and passwords |
torch.manual_seed(s) seeds the CPU generator and each GPU generator together. The CPU one is Mersenne Twister (its state, torch.Generator().get_state(), occupies 5056 bytes), and CUDA uses Philox with seed and offset. To prevent one part of code consuming another’s stream, pass an explicit torch.Generator to torch.randn(..., generator=gen), torch.multinomial or DataLoader. The latter seeds each worker’s global random state, PyTorch state and global NumPy state with different values, but does not touch np.random.Generator created in your Dataset constructor: those are copied unchanged to each worker, the failure from the motivation.
import numpy as np, pickle
class Aumentaciones:
def __init__(self):
self.rng = np.random.default_rng(0) # creado una vez, en el proceso principal
def __call__(self):
return self.rng.integers(0, 360, 4).tolist() # cuatro ángulos de rotación
ds = Aumentaciones()
# el DataLoader envía una copia del dataset a cada trabajador (fork o pickle): la misma copia del estado
trabajadores = [pickle.loads(pickle.dumps(ds)) for _ in range(4)]
print("copias:", [w() for w in trabajadores])
# corrección: cada trabajador deriva su propio flujo de la semilla raíz y de su índice
raiz = np.random.SeedSequence(0)
for w, hijo in zip(trabajadores, raiz.spawn(4)):
w.rng = np.random.default_rng(hijo) # lo que haría un worker_init_fn
print("con SeedSequence.spawn:", [w() for w in trabajadores])Common mistakes
Connections
- The Monte Carlo estimators in the next lesson consume these samplers, and their error is analyzed assuming independent uniforms, exactly what a generator must imitate.
- Randomized quasi-Monte Carlo replaces uniforms with low-discrepancy sequences, and variance-reduction techniques such as stratified sampling build on inversion.
- Metropolis–Hastings and Gibbs use uniforms for acceptance and proposals generated by these algorithms; they address rejection’s collapse in high dimensions.
- Token sampling with temperature, top- and top- samples a categorical distribution: CDF or Gumbel-max on modified logits.
- Managing seeds for reproducible experiments, in generators and streams, relies on
SeedSequence, skipping and this lesson’s counter-based generators. - The difference between a PRNG and a cryptographic generator is critical in privacy; randomized response and differential privacy mechanisms need noise nobody can predict.
Exercises
float32 uniforms with standard conversion from uniform 32-bit words . How many equal exactly 0 on average?Step 1 of 4. What is ?
semilla_base + i. Which statements are correct?More than one answer may be correct.
construir_alias(p), taking an array of probabilities (nonnegative, sum 1) and returning (prob, alias) with Vose's algorithm: scale to , divide indices into two lists (small with and large), and while both types remain take one of each, close the small one and return the large one to the appropriate list. Anything remaining in either list is closed with prob = 1 (rounding). Also implement vectorized muestrear_alias(prob, alias, n, rng), returning n indices: uniform column j and j if rng.random() < prob[j], otherwise alias[j].import numpy as np
def construir_alias(p):
p = np.asarray(p, dtype=float)
n = len(p)
prob = np.ones(n)
alias = np.arange(n)
# tu código: q = n p, listas de pequeños y grandes, y el bucle de Vose
return prob, alias
def muestrear_alias(prob, alias, n, rng):
# tu código: columnas uniformes y una comparación por muestra
return np.zeros(n, dtype=int)Summary
- Congruential generators have lattice structure: RANDU triples lie on 15 planes because . Generators linear over (xorshift, Mersenne Twister) have bits with linear complexity bounded by their state, and therefore fail linear-complexity tests and are predictable. PCG and xoshiro break linearity with a nonlinear output.
- Counter-based generators compute : random access, streams by key and massive parallelism. They are the GPU generators (Philox in cuRAND and PyTorch, Threefry in JAX). Neither they nor statistical PRNGs are cryptographic: for secrets,
secrets. - A uniform float is 53 bits scaled by , with possible: use before a logarithm. A range integer with
x % nis biased; Lemire’s method is exact and almost always costs one multiplication. - Inversion is exact if is explicit, slow with Brent and fast with tables, whose error is measured in . Rejection accepts with probability , needs (and fails silently otherwise), and collapses exponentially with dimension.
- For normals, the polar method avoids sine and cosine with rejection of acceptance , and Ziggurat resolves 97% (128 layers) or 98.5% (256 layers) of attempts with one comparison. For discrete distributions: binary CDF search (), Vose alias ( per sample after setup), and Gumbel-max (unnormalized and parallel).