13.1 Random variables, expectation, variance, and normal draws by Box-Muller
By the end of the previous chapter you had a reproducible generator, PCG32, that produces uniform numbers in . Neural networks are not initialized with uniform numbers. Almost every weight in AI Engineering, from the first Linear layer in Module system and basic layers to the Llama-family model, starts as a draw from a normal distribution with a carefully chosen spread. The first place this book needs one is orthogonal initialization, which is the QR factorization of a Gaussian matrix.
Concepts from other sections (7)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Unit circle: the circle of radius 1 about the origin; the point at angle is . Read more: 6.2 Trigonometry, rotations, complex numbers, and Euler’s formula
- Standard deviation: , the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics
- Normal distribution / Gaussian distribution: the bell-shaped density with mean and variance ; about 68%, 95%, and 99.7% of its mass lies within one, two, and three standard deviations of the mean, and the central limit theorem makes it the limit of sample means. Read more: Chapter 13: Probability and Statistics
- Cumulative distribution function (CDF): , defined for every random variable, discrete or continuous; it rises from 0 to 1, and for a continuous variable its derivative is the density. Read more: Chapter 13: Probability and Statistics
- Polar coordinates: describing a point by its distance from the origin and angle , with and ; a polar curve sweeps area . Read more: Chapter 8: Calculus 2
- Box-Muller: the transform , that turns two uniforms into two independent standard normals. Read more: 13.9 Probability problem set, part a: axioms, Bayes, random variables, Box-Muller
- Standard error: , the estimated standard deviation of the sample mean. Read more: 13.5 LLN, CLT, confidence intervals, bootstrap
Choosing that spread is a variance calculation, the subject of Variance propagation and initialization: too large and activations explode through 20 layers, too small and they vanish. This section lays the groundwork. It defines random variables, expectation, and variance from the beginning, shows how to compute a variance without destroying its digits, and turns uniforms into normals with the Box-Muller transform, in exactly the order the Rust and Go ports use, so that one seed means the same weights everywhere.
You will need the generator from Modular arithmetic, hashing, and PCG32 (the solution’s rng.py), cosine, sine, and the unit circle from Trig, rotations, and Euler’s formula, and, for background, the Gaussian integral from Calculus 2, which its problem set works through. The reference implementation is course/solutions/python/tinyllm/prob/rv.py, its contract is rv.pyi, and the cross-language draw order is fixed by spec/pcg32.md.
Learning objectives
- Compute the expectation and variance of a discrete distribution, and validate that a table really is a distribution.
- Derive and explain why independent variances add.
- Explain why fails numerically and compute the variance in two passes instead.
- Derive the Box-Muller transform from the polar form of two independent normals and implement it in the spec’s draw order.
Notation
Section titled “Notation”The section uses the following symbols throughout.
| Symbol | Meaning | Type |
|---|---|---|
| a random variable: a quantity whose value is drawn at random | ||
| the values of a discrete and their probabilities, , | float64[k] each | |
| expectation (mean) | scalar | |
| variance; is the standard deviation | scalar | |
| a uniform random variable on | ||
| a probability density: | ||
| the normal distribution; is the standard normal | ||
| the standard normal CDF, | ||
| two uniform draws | float | |
| polar radius and angle | float |
Random variables and distributions
Section titled “Random variables and distributions”A random variable assigns a number to each outcome of a random experiment. A discrete one takes values with probabilities , where every and ; that table is its distribution. A table whose probabilities do not sum to 1 (say, raw counts) or contain a negative entry describes no random variable, and the functions in this section reject it rather than average with it.
A continuous random variable has a density with ; probabilities are areas under , and any single value has probability 0. , uniform on , has on that interval.
Expectation and variance
Section titled “Expectation and variance”Once you have a distribution, the first two things to ask of it are where it sits and how widely it spreads. The expectation answers the first. It is the probability-weighted average of the values,
the long-run average of many independent draws. It is linear: , and for any .
The variance answers the second, as the expected squared distance from the mean:
From linearity, . A shift moves the distribution without spreading it; a scale by spreads it by , so the variance grows by . For independent and , variances add: . A neuron with independent zero-mean terms therefore has variance , which is why Variance propagation and initialization scales initial weights by . Every initialization in the book is sized with this rule.
Two examples recur everywhere. A Bernoulli() variable (1 with probability , else 0) has and : every accuracy you will ever measure is an average of these. A point mass (one value with probability 1) has variance exactly 0.
Computing the variance without cancellation
Section titled “Computing the variance without cancellation”The definition is clear; the arithmetic is where implementations go wrong. Expanding the square gives the textbook shortcut , which is algebraically equal and numerically dangerous. Take with a fair coin: the true variance is . But and , and float64 numbers near are spaced 128 apart, so their difference is a multiple of 128 near zero: the answer comes out 0 or , every digit wrong, sometimes negative.
The two-pass method computes first, then . The deviations are small numbers computed with small errors, and the squares are all non-negative. Stable numerics returns to this problem with Welford’s and Kahan’s algorithms.
The normal distribution
Section titled “The normal distribution”With expectation and variance in hand, you can describe the distribution the rest of the section is about. The standard normal has density : mean 0, variance 1, symmetric, with about 68% of its mass within one standard deviation and 99.7% within three. is . The constant comes from the Gaussian integral , computed by squaring it and switching to polar coordinates, and the same trick in reverse is how normals are generated.
Box-Muller
Section titled “Box-Muller”Two independent standard normals form a point in the plane whose density depends only on the distance from the origin. In polar coordinates , two facts follow:
- the angle is uniform on , by the rotational symmetry;
- the radius satisfies (integrate the density outside the circle of radius ), so is exponential with mean 1.
To sample , invert its survival function: if is uniform on , has exactly that distribution. With two uniforms :
Using instead of matters at the edge. uniform() can return exactly 0.0 (probability , but over draws not never), and would produce an infinite “normal”; lies in , so the log is finite and is finite. Both outputs are independent standard normals; throwing the sine away wastes half the work.
The order is a contract. spec/pcg32.md fixes it: for each pair, draw then , emit (cosine) then (sine). normal(rng, n) fills values pair by pair; for odd it still draws a whole last pair and drops the final sine. (The spec’s generator-level normal() keeps that sine as a spare for the next call; normal(rng, n) is a free function over any generator, so it keeps no state between calls.) Every other port reproduces this order, which is how normals can be compared across languages.
Working it by hand
Section titled “Working it by hand”Before writing code, it helps to have three answers you can check it against.
A fair die. Values , each with probability :
The deviations from 3.5 are , so
Box-Muller by hand. Choose and . Then , so ; and . The pair is .
The first normals of seed 0. PCG32(0) gives and (worked by hand in the PCG32 section). Then , , (just under , so the point lies left of the origin, slightly up), , , and the first two normals are and : the first two entries of normal["0"] in spec/pcg32.vectors.json.
Designing the interface
Section titled “Designing the interface”Four functions cover the section:
def expectation(values, probs) -> float: ... # sum p_i x_i; ValueError unless a distributiondef variance(values, probs) -> float: ... # sum p_i (x_i - mu)^2, two passesdef box_muller(u1: float, u2: float) -> tuple[float, float]: ... # (r cos t, r sin t)def normal(rng, n: int) -> NDArray: ... # float64 [n]; u1, u2 per pair; cosine firstrng is anything with a uniform() method returning the spec’s 53-bit doubles; in this system that is tinyllm.num.rng.PCG32. Any implementation of the spec gives the same uniforms bit for bit.
Building it step by step
Section titled “Building it step by step”The implementation follows from five observations, each of which you should try to predict before reading on.
- A distribution is a validated table. Values and probabilities must be 1-D, the same non-zero length, finite, with and . Anything else (raw counts, a negative entry) is not a random variable, so both
expectationandvarianceshare one validator that raises instead of averaging. The sum test needs a tolerance () because probabilities computed in floating point need not sum to exactly 1. - The expectation is a dot product. . Weighting by (not dividing by ) is what makes it right for non-uniform tables.
- The variance centres first, then squares. cancels catastrophically near . Computing once, then and , keeps every term small and non-negative, so gives exactly and no variance can come out negative.
- Box-Muller samples the polar form. with in and . Taking maps the generator’s onto , so gives instead of .
- The draw order is part of the answer. Per pair, then ; emit cosine then sine. A loop over pairs that writes
z0always andz1only when there is room implements both the even and odd cases, and an odd still consumes two uniforms for the last pair, so the generator ends at the same position as in every other port.
The validator comes first:
def _table(values: ArrayLike, probs: ArrayLike) -> tuple[NDArray, NDArray]: """values and probs as float64 vectors, checked to be a distribution.""" x = np.asarray(values, dtype=np.float64) p = np.asarray(probs, dtype=np.float64) # One shape check covers 2-D input, mismatched lengths, and the empty table. if x.ndim != 1 or p.ndim != 1 or x.shape != p.shape or x.size == 0: raise ValueError(f"values and probs must be 1-D of one non-zero length, got {x.shape} and {p.shape}") if not np.all(np.isfinite(x)): raise ValueError("values must be finite") if np.any(p < 0) or not np.all(np.isfinite(p)): raise ValueError("probs must be finite and >= 0") # A tolerance, not ==: probabilities computed in float64 (a softmax, a # normalized count) are only accurate to rounding. if abs(float(p.sum()) - 1.0) > 1e-9: raise ValueError(f"probs must sum to 1, got {float(p.sum())!r}") return x, pRaw counts such as [3, 1] sum to 4 and are rejected here, which is the point: a caller who forgot to normalize hears about it at once rather than getting an expectation four times too large.
With a validated table, the two moments are short:
def expectation(values: ArrayLike, probs: ArrayLike) -> float: x, p = _table(values, probs) return float(x @ p) # sum_i p_i x_i
def variance(values: ArrayLike, probs: ArrayLike) -> float: x, p = _table(values, probs) mu = float(x @ p) # pass 1: the mean d = x - mu # pass 2: small deviations, computed accurately return float((d * d) @ p) # sum_i p_i (x_i - mu)^2, every term >= 0On the die, mu = 3.5, d is , and the weighted sum of squares is , exactly the hand calculation. On the deviations are exactly , so the result is exactly .
The transform and the sampler that drives it complete the module:
def box_muller(u1: float, u2: float) -> tuple[float, float]: # 1 - u1 lies in (0, 1], so the log is finite and r is in [0, inf). r = math.sqrt(-2.0 * math.log(1.0 - u1)) # R^2 / 2 is exponential(1) theta = 2.0 * math.pi * u2 # a full turn, not half return r * math.cos(theta), r * math.sin(theta) # cosine first: the spec's order
def normal(rng: Any, n: int) -> NDArray: if n < 0: raise ValueError(f"normal: n must be >= 0, got {n}") out = np.empty(n, dtype=np.float64) for i in range(0, n, 2): # one Box-Muller pair per iteration u1 = rng.uniform() # u1 then u2: the cross-language draw order u2 = rng.uniform() z0, z1 = box_muller(u1, u2) out[i] = z0 if i + 1 < n: # odd n: the last sine is dropped, but its out[i + 1] = z1 # uniform was still consumed return outnormal keeps no spare between calls: it is a free function over any object with uniform(), so the only state is the generator’s. n = 0 returns an empty array and draws nothing. The full solution is rv.py.
Why this design
Section titled “Why this design”The costs are modest. expectation is one pass over the table and variance two, both time and extra space for d. normal(rng, n) makes uniform draws and one log, sqrt, cos, sin per pair.
The two-pass variance beats the shortcut outright. also needs two sums and saves nothing in a setting where the whole table is in memory; it only loses digits. Welford’s one-pass update (see Further reading) is the right choice for streams, which is not this function’s job.
Box-Muller wins over its alternatives for a reason specific to this system. The Ziggurat algorithm is faster but needs tables and a rejection loop whose number of draws per normal varies, which makes cross-language reproduction harder. The polar (Marsaglia) method also rejects. Box-Muller uses exactly two uniforms per pair, so the stream position after normal(rng, n) is a simple function of , which is what the Rust and Go ports rely on.
The tradeoff accepted is speed: the Python loop is slow for millions of normals (one Python iteration per pair). Initializers in the book draw at most a few million values, and bit-for-bit agreement with the spec matters more than speed here.
What can go wrong
Section titled “What can go wrong”A correct implementation has to pass checks of several kinds, from hand-worked unit cases to statistical tests of the output’s shape. The table lists them along with why each matters later.
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| the fair die | unit | , | everyone agrees on the definitions |
| Bernoulli and point mass | unit | , ; a point mass has variance 0 | every accuracy metric is a Bernoulli mean (confidence intervals) |
| no catastrophic cancellation | boundary | gives exactly | statistics of large-mean quantities (token counts, timestamps) |
| shift and scale laws | property | and on 50 random tables | the scaling rule of initialization |
| tables that are not distributions | boundary | sums other than 1, negative entries, shape mismatches, empty and 2-D tables raise | unnormalized counts are caught upstream |
| Box-Muller by hand | unit | , and at | the transform itself |
| stays finite | boundary | gives radius 0; just below 1 gives a large finite value | no infinite weights |
| the spec vectors | golden | the first 8 normals of seeds 0, 1, within 4 ulp | the Rust and Go ports draw the same normals |
| odd | unit | normal(rng, 3) uses 4 uniforms and equals the first 3 of normal(rng, 4); n = 0 and n < 0 | the stream position after a call |
| the moments | statistical | 20 000 draws: mean and variance within 3 standard errors of 0 and 1 | a missing factor 2 halves every initial variance |
| the shape | statistical | 20 bins equally likely under : Pearson statistic below 43.82 (19 degrees of freedom, ) | the right moments are not the right shape |
| the two halves of a pair | statistical | the cosine and sine halves have correlation within 3 standard errors of 0 | independent draws |
The mistakes that break these checks are few and recognizable. Averaging the values without the probabilities is right only for uniform tables; the solution weights each value with x @ p. Returning the standard deviation as the variance gives instead of ; the solution returns the weighted sum of squares with no square root. Using gives a variance of 0 or a negative number for large means; the solution centres first with d = x - mu. Skipping validation turns unnormalized counts into silent nonsense; _table checks shape, finiteness, sign, and sum.
The Box-Muller mistakes are subtler, because several of them still produce plausible-looking numbers:
Warning: instead of produces an infinite value once in draws and different values from every other port. Dropping the 2 in gives variance , so every initial weight is too small by . An angle of instead of makes the sine half always positive, the wrong shape. Taking both halves from the cosine gives perfectly correlated pairs.
Emitting the sine first is statistically fine but matches no other language; the solution returns (r * cos, r * sin) and writes z0 first.
Where this leads
Section titled “Where this leads”The normals built here feed two sections directly. Orthogonality, Householder QR, and orthogonal initialization factors normal(rng, rows * cols) in orthogonal_init, and Variance propagation and initialization builds normal_init, Xavier and Kaiming normals, and the propagation rule on top of them. The next section, Categorical sampling, builds on the same uniforms to draw tokens.
Further reading
Section titled “Further reading”- Blitzstein and Hwang, Introduction to Probability, chapters 3 to 5 and 7.5 (Box-Muller).
- Grinstead and Snell, Introduction to Probability, chapter 6.
- Box and Muller, “A Note on the Generation of Random Normal Deviates” (1958).
- Welford, “Note on a Method for Calculating Corrected Sums of Squares and Products” (1962);
torch.var_meanand Chan et al.’s parallel merging extend it to one pass over a stream, mergeable across workers. - The Ziggurat algorithm (numpy’s
standard_normal, Rustrand_distr): almost always one uniform and one table lookup per normal, nolog,sin, orcos. Seerandom_standard_normalin numpy’snumpy/random/src/distributions/distributions.c. - Marsaglia and Bray (1964), the polar method: rejection inside the unit disc replaces and .
torch.nn.init.normal_(torch/nn/init.py) andjax.random.normal(jax/_src/random.py): per-device counter-based generators, many values per call.
Key terms
Section titled “Key terms”- Random variable: a number assigned to each outcome of a random experiment; a discrete one is a table of values and probabilities.
- Expectation: the probability-weighted mean of a random variable’s values.
- Variance: the expected squared distance from the mean; its square root is the standard deviation.
- Catastrophic cancellation: the loss of all significant digits when two large, nearly equal floating-point numbers are subtracted.
- Two-pass variance: computing the mean first, then the weighted sum of squared deviations from it.
- Standard normal: the distribution with density .
- Box-Muller transform: a map from two independent uniforms to two independent standard normals via a radius and angle .
Summary
Section titled “Summary”- A discrete random variable is a table of values and probabilities; its expectation is the probability-weighted mean and its variance the expected squared distance from that mean.
- : shifting does nothing, scaling scales by the square. Every initialization is sized with this rule.
- Compute the variance in two passes (mean first, then squared deviations). subtracts two huge, nearly equal numbers and can return 0 or a negative variance.
- Box-Muller turns two independent uniforms into two independent standard normals: a radius and an angle . Drawn in the spec’s order, the same seed gives the same normals in Python, Rust, and Go.
Review questions
Section titled “Review questions”-
Why does
variancecomputed = x - mubefore squaring instead of returning(x * x) @ p - mu * mu?Answer
For large means both and are near , where float64 spacing is 128, so their difference is a multiple of 128 near zero: 0 or for a true variance of . The deviations are small and exact (or nearly), and their squares are non-negative, so the two-pass sum is accurate and cannot go negative.
-
Why
math.log(1.0 - u1)and notmath.log(u1)? Both are uniform on the unit interval.Answer
Distributionally they are equivalent, but the generator returns values in : is possible and gives an infinite radius. lies in , so the log is finite. It also fixes which value every port computes from a given , so the normals agree across languages.
-
For odd , why draw a whole pair and throw the sine away instead of drawing one uniform?
Answer
Box-Muller needs both uniforms to make even one normal (the radius uses , the angle ). And the spec defines the stream position:
normal(rng, 3)must consume 4 uniforms and equal the first 3 ofnormal(rng, 4), so that the next draw from the generator is the same in Python, Rust, and Go. -
What would happen to the initial weights of Variance propagation and initialization if the radius were , without the 2?
Answer
would be exponential with mean 1 instead of 2, so each coordinate would have variance . Every weight scaled by a carefully derived would actually have standard deviation , and activations would shrink layer after layer. The mean is still 0, so only a variance check notices.
-
Why does
_tablereject a table whose probabilities sum to 4 instead of normalizing it?Answer
A table that does not sum to 1 is almost always a bug upstream (raw counts passed where probabilities were meant). Silently normalizing would hide it in this function and leave it in every other caller that trusts the same array. Raising makes the error visible where it is cheapest to fix.