ch08_policy_gradient.py
Companion code for Policy gradients are score-function estimators. Needs only Python 3 and NumPy: python code/ch08_policy_gradient.py.
"""Chapter 8: policy gradients as score-function estimators.
A small episodic problem (3 states, 2 actions, horizon 4, tabular softmax
policy, noisy rewards) where the true policy gradient is computed exactly by
dynamic programming. We draw many single-trajectory REINFORCE estimates under
five variants and report their empirical mean (compared with the truth) and
their variance:
1. no baseline sum_t g_t * R(tau)
2. constant baseline = E[R] sum_t g_t * (R(tau) - J)
3. optimal constant baseline b*_i = E[G_i^2 R] / E[G_i^2], per component
4. reward-to-go sum_t g_t * G_t
5. reward-to-go minus learned state-value baseline sum_t g_t * (G_t - V(t, S_t))
g_t = grad_theta log pi(A_t | S_t); G = sum_t g_t is the trajectory score.
Baselines 3 and 5 are fitted on a separate pilot sample, so they are constants
with respect to the estimation sample and the estimators stay unbiased.
A short learning comparison follows.
Run: python code/ch08_policy_gradient.py (about 20 seconds)
"""
import numpy as np
rng = np.random.default_rng(8)
NS, NA, H = 3, 2, 4
# dynamics P[s, a, s'], mean rewards r[s, a], reward noise sd
P = np.array([[[0.8, 0.1, 0.1], [0.1, 0.8, 0.1]],
[[0.1, 0.8, 0.1], [0.1, 0.1, 0.8]],
[[0.8, 0.1, 0.1], [0.1, 0.1, 0.8]]])
R = np.array([[1.0, 2.0], [2.5, 1.5], [0.5, 4.0]]) + 3.0 # shifted up: raw returns are large
REWARD_SD = 1.0
S0 = 0
NPAR = NS * NA
def softmax(th):
z = th - th.max(axis=1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
def grad_logpi(pi, s, a):
"""Score of the tabular softmax: e_{s,a} - pi(.|s) placed in the row of s."""
g = np.zeros((NS, NA))
g[s] = -pi[s]
g[s, a] += 1.0
return g.ravel()
# ---- exact quantities ------------------------------------------------------
def exact_J_and_grad(th):
pi = softmax(th)
# backward induction: q[t, s, a], v[t, s]; v[H] = 0
q = np.zeros((H, NS, NA)); v = np.zeros((H + 1, NS))
for t in reversed(range(H)):
q[t] = R + np.einsum("sap,p->sa", P, v[t + 1])
v[t] = (pi * q[t]).sum(axis=1)
d = np.zeros(NS); d[S0] = 1.0 # state distribution at time t
grad = np.zeros((NS, NA))
for t in range(H):
# sum_a pi(a|s) q(s,a) grad log pi(a|s) = pi(a|s) * (q(s,a) - v(s)) for softmax
grad += d[:, None] * pi * (q[t] - v[t][:, None])
d = np.einsum("s,sa,sap->p", d, pi, P)
return v[0, S0], grad.ravel(), v, q
# ---- sampling --------------------------------------------------------------
def sample_batch(th, n):
"""n trajectories. Returns states (n,H), actions (n,H), rewards (n,H)."""
pi = softmax(th)
S = np.zeros((n, H), int); A = np.zeros((n, H), int); Rw = np.zeros((n, H))
s = np.full(n, S0)
cum = np.cumsum(pi, axis=1)
for t in range(H):
a = (rng.random(n)[:, None] > cum[s]).sum(axis=1)
a = np.minimum(a, NA - 1)
Rw[:, t] = R[s, a] + REWARD_SD * rng.standard_normal(n)
S[:, t], A[:, t] = s, a
cp = np.cumsum(P[s, a], axis=1)
s = np.minimum((rng.random(n)[:, None] > cp).sum(axis=1), NS - 1)
return S, A, Rw
def scores(th, S, A):
"""g[n, t, :] = grad log pi(A_t | S_t)."""
pi = softmax(th)
n = S.shape[0]
g = np.zeros((n, H, NPAR))
# vectorised: -pi[s] in row s, +1 at (s, a)
idx = np.arange(n)
for t in range(H):
s, a = S[:, t], A[:, t]
block = np.zeros((n, NS, NA))
block[idx, s, :] = -pi[s]
block[idx, s, a] += 1.0
g[:, t, :] = block.reshape(n, NPAR)
return g
def reward_to_go(Rw):
return np.cumsum(Rw[:, ::-1], axis=1)[:, ::-1]
def estimators(th, n, pilot):
"""Dict name -> (n, NPAR) array of single-trajectory gradient estimates."""
S, A, Rw = sample_batch(th, n)
g = scores(th, S, A)
G = g.sum(axis=1) # trajectory score
Ret = Rw.sum(axis=1)
RTG = reward_to_go(Rw)
out = {}
out["no baseline"] = G * Ret[:, None]
out["constant mean baseline"] = G * (Ret - pilot["J"])[:, None]
out["optimal constant baseline"] = G * (Ret[:, None] - pilot["b_star"][None, :])
out["reward-to-go"] = (g * RTG[:, :, None]).sum(axis=1)
Vtab = pilot["V"][np.arange(H)[None, :], S] # (n, H) learned V(t, S_t)
out["reward-to-go, learned V(t,s)"] = (g * (RTG - Vtab)[:, :, None]).sum(axis=1)
return out
def fit_pilot(th, n):
S, A, Rw = sample_batch(th, n)
g = scores(th, S, A)
G = g.sum(axis=1)
Ret = Rw.sum(axis=1)
b_star = (G ** 2 * Ret[:, None]).mean(axis=0) / (G ** 2).mean(axis=0)
RTG = reward_to_go(Rw)
V = np.zeros((H, NS)) # regression of G_t on (t, S_t): cell means
for t in range(H):
for s in range(NS):
m = S[:, t] == s
V[t, s] = RTG[m, t].mean() if m.any() else 0.0
return {"J": Ret.mean(), "b_star": b_star, "V": V}
def experiment_variance():
th = 0.3 * rng.standard_normal((NS, NA))
J, true_grad, _, _ = exact_J_and_grad(th)
pilot = fit_pilot(th, 200000)
n = 400000
est = estimators(th, n, pilot)
print(f"True J = {J:.4f}; ||true gradient|| = {np.linalg.norm(true_grad):.4f}; "
f"{NPAR} parameters; {n} single-trajectory estimates per row.")
print(f"Baselines fitted on a separate pilot of 200000 trajectories; "
f"mean pilot return {pilot['J']:.3f}.\n")
print("estimator | ||mean - truth|| | max z-score | total variance | rel. to none")
base = None
for name, x in est.items():
m = x.mean(axis=0)
se = x.std(axis=0, ddof=1) / np.sqrt(n)
z = np.abs(m - true_grad) / se
tv = x.var(axis=0, ddof=1).sum()
base = tv if base is None else base
print(f"{name:30s} | {np.linalg.norm(m - true_grad):16.4f} | {z.max():11.2f} | "
f"{tv:14.2f} | {tv / base:11.4f}")
# a few components, first estimator vs best
print("\ncomponent 0..5 of the gradient: truth and empirical means")
print("truth | " + " ".join(f"{x:7.3f}" for x in true_grad))
for name, x in est.items():
print(f"{name:30s} | " + " ".join(f"{x:7.3f}" for x in x.mean(axis=0)))
# ---- learning comparison ---------------------------------------------------
def learn(variant, seed, iters=150, batch=32, lr=0.05):
global rng
rng = np.random.default_rng(seed)
th = np.zeros((NS, NA))
Vtab = np.zeros((H, NS))
for it in range(iters):
S, A, Rw = sample_batch(th, batch)
g = scores(th, S, A)
Ret = Rw.sum(axis=1)
RTG = reward_to_go(Rw)
if variant == "no baseline":
grad = (g.sum(axis=1) * Ret[:, None]).mean(axis=0)
elif variant == "reward-to-go":
grad = (g * RTG[:, :, None]).sum(axis=1).mean(axis=0)
else: # reward-to-go with learned V(t, s), updated after use
Vb = Vtab[np.arange(H)[None, :], S]
grad = (g * (RTG - Vb)[:, :, None]).sum(axis=1).mean(axis=0)
for t in range(H):
for s in range(NS):
m = S[:, t] == s
if m.any():
Vtab[t, s] += 0.2 * (RTG[m, t].mean() - Vtab[t, s])
th = th + lr * grad.reshape(NS, NA)
return exact_J_and_grad(th)[0]
def best_J():
# exact optimum: deterministic policy via backward induction
v = np.zeros(NS)
for _ in range(H):
v = (R + np.einsum("sap,p->sa", P, v)).max(axis=1)
return v[S0]
def experiment_learning():
Jopt = best_J()
th0 = np.zeros((NS, NA))
print(f"\nLearning: 150 SGD steps, batch 32, step 0.05, 40 seeds. "
f"J(uniform) = {exact_J_and_grad(th0)[0]:.3f}, J(optimal) = {Jopt:.3f}")
print("variant | final J mean | final J sd")
for variant in ["no baseline", "reward-to-go", "reward-to-go + learned V"]:
Js = np.array([learn(variant, 1000 + k) for k in range(40)])
print(f"{variant:30s} | {Js.mean():12.3f} | {Js.std():10.3f}")
if __name__ == "__main__":
# sanity: exact gradient matches finite differences
th = 0.3 * rng.standard_normal((NS, NA))
_, gr, _, _ = exact_J_and_grad(th)
fd = np.zeros(NPAR)
for i in range(NPAR):
e = np.zeros(NPAR); e[i] = 1e-5
fd[i] = (exact_J_and_grad(th + e.reshape(NS, NA))[0]
- exact_J_and_grad(th - e.reshape(NS, NA))[0]) / 2e-5
print(f"check: max |exact grad - finite difference| = {np.abs(gr - fd).max():.2e}\n")
experiment_variance()
experiment_learning()