Skip to main content
This appendix collects the probability tools that the RL chapters use repeatedly. Each section gives a short derivation and then checks the result numerically in torch, so that the identity is something you have seen hold rather than something you take on faith. The chapters link here when they need a result. Nothing here is specific to language models, but every example is chosen because it reappears in one. The one function saved here, mc_mean_and_stderr, is used wherever the book reports a Monte Carlo estimate with an error bar.

A.1 Monte Carlo Estimates and Error Bars

Almost every quantity in RL is an expectation we cannot compute exactly: the objective J(θ)J(\theta), a gradient, a pass rate. We estimate it by sampling. Given i.i.d. samples x1,…,xnx_1, \dots, x_n of a random variable XX with mean μ\mu and variance σ2\sigma^2, the sample mean Xˉ=1n∑ixi\bar X = \frac{1}{n}\sum_i x_i is unbiased, E[Xˉ]=μ\mathbb{E}[\bar X] = \mu, and its variance is Var(Xˉ)=1n2∑i=1nVar(xi)=σ2n.\mathrm{Var}(\bar X) = \frac{1}{n^2} \sum_{i=1}^n \mathrm{Var}(x_i) = \frac{\sigma^2}{n}. The standard error σ/n\sigma/\sqrt{n} is the standard deviation of the estimate. In practice σ\sigma is unknown and is replaced by the sample standard deviation ss. By the central limit theorem, Xˉ±1.96 s/n\bar X \pm 1.96\, s/\sqrt{n} is an approximate 95% confidence interval. The error shrinks as 1/n1/\sqrt{n}: four times as many samples halve it.
Check the coverage claim. A Bernoulli variable with p=0.3p = 0.3 stands in for a binary reward. We draw 10,000 independent experiments of n=200n = 200 samples each and count how often the interval contains the true mean.
Output:
The estimated standard error matches the theoretical value p(1−p)/n\sqrt{p(1-p)/n}, and the nominal 95% interval covers the true mean in close to 95% of experiments. The approximation degrades when nn is small or pp is near 0 or 1, which is exactly the regime of a hard task’s pass rate. Chapter 17 uses the bootstrap and exact intervals for those cases.

A.2 The Variance of Sums

A trajectory’s return is a sum of rewards, and a policy-gradient estimate is a sum of per-token terms. The variance of a sum is Var(∑i=1nXi)=∑iVar(Xi)+2∑i<jCov(Xi,Xj).\mathrm{Var}\Big(\sum_{i=1}^n X_i\Big) = \sum_{i} \mathrm{Var}(X_i) + 2\sum_{i<j} \mathrm{Cov}(X_i, X_j). For independent terms the covariances vanish and the variance grows linearly in nn. For positively correlated terms it grows faster. With equal variances σ2\sigma^2 and pairwise correlation ρ\rho, the variance of the mean of nn terms is Var(Xˉ)=σ2n(1+(n−1)ρ),\mathrm{Var}(\bar X) = \frac{\sigma^2}{n}\big(1 + (n-1)\rho\big), which does not go to zero as n→∞n \to \infty when ρ>0\rho > 0. Samples that share a cause, such as GG completions of the same prompt or many tokens of one trajectory, carry less information than their count suggests. The effective sample size is neff=n/(1+(n−1)ρ)n_{\text{eff}} = n / (1 + (n-1)\rho). We generate correlated samples by giving every member of a group a shared component plus an independent one, and compare the measured variance of the group mean with the formula.
Output:
At ρ=0.5\rho = 0.5, sixteen correlated samples are worth fewer than two independent ones. This is why the book reports error bars over independent units, such as tasks or seeds, rather than over tokens.

A.3 Control Variates

Suppose we want E[f(X)]\mathbb{E}[f(X)] and know another function g(X)g(X) whose mean E[g]\mathbb{E}[g] is known exactly. Then for any constant cc, μ^c=f(X)−c (g(X)−E[g])\hat\mu_c = f(X) - c\,\big(g(X) - \mathbb{E}[g]\big) is still unbiased, and its variance is Var(f)−2c Cov(f,g)+c2 Var(g)\mathrm{Var}(f) - 2c\,\mathrm{Cov}(f,g) + c^2\,\mathrm{Var}(g). Minimizing over cc gives c∗=Cov(f,g)Var(g),Var(μ^c∗)=Var(f) (1−corr(f,g)2).c^* = \frac{\mathrm{Cov}(f, g)}{\mathrm{Var}(g)}, \qquad \mathrm{Var}(\hat\mu_{c^*}) = \mathrm{Var}(f)\,\big(1 - \mathrm{corr}(f,g)^2\big). The more correlated gg is with ff, the more variance it removes, and the mean of gg does not need to be close to the mean of ff. The baseline in policy gradients is a control variate: Chapter 6 subtracts b⋅∇log⁡πb \cdot \nabla\log\pi, whose expectation is exactly zero by Section A.5. Here we check the formula with f(X)=eXf(X) = e^X and g(X)=Xg(X) = X for X∼N(0,1)X \sim \mathcal{N}(0, 1), where E[eX]=e1/2\mathbb{E}[e^X] = e^{1/2}.
Output:
Both estimators agree with the true mean e1/2≈1.6487e^{1/2} \approx 1.6487. The control variate cuts the per-sample variance by about 60%, the fraction corr(eX,X)2\mathrm{corr}(e^X, X)^2. The optimal coefficient here equals E[eX]=e1/2\mathbb{E}[e^X] = e^{1/2}, because Cov(eX,X)=E[XeX]=e1/2\mathrm{Cov}(e^X, X) = \mathbb{E}[X e^X] = e^{1/2}.

A.4 Importance Sampling

We often need an expectation under one distribution pp but have samples from another, qq. In RL, pp is the current policy and qq is the older policy or inference engine that generated the data. If q(x)>0q(x) > 0 wherever p(x)f(x)≠0p(x) f(x) \ne 0, Ex∼p[f(x)]=∑xp(x)f(x)=∑xq(x)p(x)q(x)f(x)=Ex∼q[w(x)f(x)],w(x)=p(x)q(x).\mathbb{E}_{x \sim p}[f(x)] = \sum_x p(x) f(x) = \sum_x q(x) \frac{p(x)}{q(x)} f(x) = \mathbb{E}_{x \sim q}\big[w(x) f(x)\big], \qquad w(x) = \frac{p(x)}{q(x)}. The importance-weighted estimator is unbiased. Its variance is not free: Varq(wf)=Ep[w(x)f(x)2]−(Ep[f])2,\mathrm{Var}_q(w f) = \mathbb{E}_p\big[w(x) f(x)^2\big] - \big(\mathbb{E}_p[f]\big)^2, and the factor ww inside the expectation makes the variance large where pp puts much more mass than qq. A useful diagnostic is the effective sample size of the weights, neff=(∑iwi)2/∑iwi2n_{\text{eff}} = (\sum_i w_i)^2 / \sum_i w_i^2, which equals nn when all weights are equal and approaches 1 when one weight dominates. Check unbiasedness on a categorical distribution, using a qq close to pp and one far from it.
Output:
Both estimates are consistent with the exact value 3.0, but the far proposal has a standard error several times larger and an effective sample size that is a small fraction of the nominal one. A few rare samples with large weights carry most of the estimate.

Products of ratios

For a trajectory of TT steps, the importance weight is a product of per-step ratios, w(τ)=∏tπθ(at∣st)/πold(at∣st)w(\tau) = \prod_t \pi_\theta(a_t\mid s_t)/\pi_{\text{old}}(a_t\mid s_t). Even when each factor has mean 1 and small spread, the product’s variance grows exponentially with TT. Model each per-token log-ratio as an independent Gaussian with mean −σ2/2-\sigma^2/2, which makes each ratio have mean exactly 1.
Output:
The weight is unbiased in principle at every length, but at T=1000T = 1000 the sample mean is already wrong because a few huge weights that would restore it are too rare to have been drawn, and the effective sample size collapses. The exact variance is eTσ2−1e^{T\sigma^2} - 1. This is why PPO and its successors use per-token ratios with clipping rather than trajectory ratios, an approximation that Chapter 8 states precisely.

A.5 The Log-Derivative Trick

The gradient of an expectation with respect to the parameters of the sampling distribution is ∇θEx∼pθ[f(x)]=∑x∇θpθ(x) f(x)=∑xpθ(x) ∇θlog⁡pθ(x) f(x)=Ex∼pθ[f(x) ∇θlog⁡pθ(x)],\nabla_\theta \mathbb{E}_{x \sim p_\theta}[f(x)] = \sum_x \nabla_\theta p_\theta(x)\, f(x) = \sum_x p_\theta(x)\, \nabla_\theta \log p_\theta(x)\, f(x) = \mathbb{E}_{x \sim p_\theta}\big[f(x)\, \nabla_\theta \log p_\theta(x)\big], using ∇p=p ∇log⁡p\nabla p = p\, \nabla \log p. The right-hand side can be estimated from samples without differentiating ff, which may be a test suite. This is the score-function or REINFORCE estimator, and ∇θlog⁡pθ(x)\nabla_\theta \log p_\theta(x) is the score. Setting f≡1f \equiv 1 gives the identity that makes baselines legal: Ex∼pθ[∇θlog⁡pθ(x)]=∇θ∑xpθ(x)=∇θ1=0.\mathbb{E}_{x \sim p_\theta}\big[\nabla_\theta \log p_\theta(x)\big] = \nabla_\theta \sum_x p_\theta(x) = \nabla_\theta 1 = 0. Check both on a softmax distribution over five outcomes. Autograd gives the exact gradient of ∑xpθ(x)f(x)\sum_x p_\theta(x) f(x); the score-function estimator averages f(x)∇log⁡pθ(x)f(x)\nabla\log p_\theta(x) over samples.
Output:
For a softmax, the score with respect to the logits is ex−pθ\mathbf{e}_x - p_\theta, the one-hot vector of the sampled outcome minus the probabilities. The estimate agrees with autograd to about three decimals, and the average score is zero up to Monte Carlo noise. Chapter 6 applies this identity to whole trajectories, where the environment’s transition probabilities drop out of the score because they do not depend on θ\theta.

A.6 KL Divergence

The Kullback–Leibler divergence from qq to pp is KL(p ∥ q)=Ex∼p[log⁡p(x)q(x)].\mathrm{KL}(p \,\Vert\, q) = \mathbb{E}_{x \sim p}\Big[\log \frac{p(x)}{q(x)}\Big]. Three properties are used throughout the book. Nonnegativity. By Jensen’s inequality applied to the concave log⁡\log, −KL(p∥q)=Ep[log⁡(q/p)]≤log⁡Ep[q/p]=log⁡1=0-\mathrm{KL}(p\Vert q) = \mathbb{E}_p[\log(q/p)] \le \log \mathbb{E}_p[q/p] = \log 1 = 0, with equality only when p=qp = q. Asymmetry. KL(p∥q)≠KL(q∥p)\mathrm{KL}(p\Vert q) \ne \mathrm{KL}(q\Vert p) in general. Forward KL, KL(pdata∥πθ)\mathrm{KL}(p_{\text{data}} \Vert \pi_\theta), is what maximum likelihood minimizes; it penalizes πθ\pi_\theta for missing modes of the data. Reverse KL, KL(πθ∥πref)\mathrm{KL}(\pi_\theta \Vert \pi_{\text{ref}}), is the usual RL regularizer; it is estimated with samples from the policy and penalizes the policy for putting mass where the reference has little. Chapter 10 and Chapter 16 discuss the consequences. The chain rule. For sequences generated autoregressively, p(y)=∏ip(yi∣y<i)p(y) = \prod_i p(y_i \mid y_{<i}), so the log-ratio is a sum over tokens and KL(p ∥ q)=∑iEy<i∼p[KL(p(⋅∣y<i) ∥ q(⋅∣y<i))].\mathrm{KL}(p \,\Vert\, q) = \sum_i \mathbb{E}_{y_{<i} \sim p}\Big[\mathrm{KL}\big(p(\cdot \mid y_{<i}) \,\Vert\, q(\cdot \mid y_{<i})\big)\Big]. The sequence KL is the expected sum of per-token KLs along prefixes sampled from pp. This is what justifies per-token KL penalties. Check it exactly on a two-token sequence model with a vocabulary of three.
Output:
The two forward computations agree to all printed digits, and the reverse KL differs, which illustrates the asymmetry.

A.7 Estimating KL from Samples

In training we cannot sum over all sequences, so KL is estimated from samples x∼qx \sim q (the policy) of the log-ratio between the policy and a reference pp. With r=p(x)/q(x)r = p(x)/q(x), the three estimators in John Schulman’s note Approximating KL Divergence (2020) for KL(q∥p)\mathrm{KL}(q \Vert p) are k1=−log⁡r,k2=12(log⁡r)2,k3=(r−1)−log⁡r.k_1 = -\log r, \qquad k_2 = \tfrac{1}{2}(\log r)^2, \qquad k_3 = (r - 1) - \log r. k1k_1 is unbiased, because its expectation is the definition, but it is negative for many samples and has high variance. k3k_3 is also unbiased, because Eq[r−1]=0\mathbb{E}_q[r - 1] = 0, so it is k1k_1 plus a control variate in the sense of Section A.3. It is always nonnegative, since log⁡r≤r−1\log r \le r - 1. k2k_2 is biased but has low variance when pp and qq are close. Check this numerically.
Output:
When the distributions are close (first row), all three means are near the true KL, and k2k_2 and k3k_3 have a much smaller standard deviation than k1k_1. When they are far apart, k2k_2‘s bias becomes visible while k1k_1 and k3k_3 remain unbiased. Which estimator to use, and what gradient each one produces when it is placed in a loss rather than a reward, are questions for Chapter 10.

Summary

  • A Monte Carlo mean has standard error σ/n\sigma/\sqrt{n} for independent samples; mc_mean_and_stderr computes it, and correlated samples have a smaller effective sample size.
  • A control variate with a known mean keeps an estimator unbiased and removes the fraction corr2\mathrm{corr}^2 of its variance. Policy-gradient baselines are control variates.
  • Importance sampling is unbiased, but its variance grows with the mismatch between distributions and grows exponentially with the length of a product of ratios.
  • The log-derivative trick turns the gradient of an expectation into an expectation of f∇log⁡pf \nabla\log p; the score has mean zero.
  • KL is nonnegative and asymmetric, and a sequence KL is the expected sum of per-token KLs. Of the sample estimators, k1k_1 and k3k_3 are unbiased and k3k_3 is never negative.

Exercises

  1. Show that the variance of the importance-sampling estimator is minimized by q(x)∝p(x) ∣f(x)∣q(x) \propto p(x)\,|f(x)|. Why can’t this choice be used in practice?
  2. In Section A.4, change σ\sigma in the products-of-ratios experiment to 0.03. At what TT does the effective sample size fall below 10%? Compare with the prediction 1/(eTσ2)1/(e^{T\sigma^2}).
  3. Prove that k3≥0k_3 \ge 0 for every sample, and that Eq[k3]=KL(q∥p)\mathbb{E}_q[k_3] = \mathrm{KL}(q\Vert p).
  4. Repeat the control-variate experiment with g(X)=X2g(X) = X^2, whose mean is 1. Compute c∗c^* and the variance reduction. Why is it smaller than for g(X)=Xg(X) = X?
  5. Change an assumption in Section A.1: draw the 200 samples as 25 groups of 8 that share a per-group success probability drawn uniformly from [0,0.6][0, 0.6]. Does the naive standard error still give 95% coverage? Use Section A.2 to explain the result.
  6. Design review: a teammate computes a 95% interval for a pass rate from 4,000 rollouts, which are 8 samples on each of 500 tasks, treating all 4,000 as independent. What is wrong, and what should the interval be computed over?