RLS RL, Read as Statistics

ch05_td.py

Companion code for TD learning as bootstrapping. Needs only Python 3 and NumPy: python code/ch05_td.py.

NumPy
"""Chapter 5: TD learning as bootstrapping (RL, Read as Statistics).

Three demonstrations, all on random walks with gamma = 1:

1. Why a TD target has lower variance than a Monte Carlo return, with the
   law of total variance checked against simulation (one state, V exact).
2. Bias, variance and MSE of n-step TD estimates after a fixed number of
   episodes, on a 19-state random walk, as a function of n and alpha.
   n = "MC" is constant-alpha Monte Carlo (every-visit).
3. Certainty equivalence: batch TD(0) equals the value of the maximum-
   likelihood model; batch Monte Carlo is the average of observed returns.
   The A/B example of Sutton & Barto (2018), section 6.3, then a 5-state
   random-walk comparison of the two.

NumPy only. Run: python code/ch05_td.py
"""
import numpy as np

rng = np.random.default_rng(5)

# ---------------------------------------------------------------- 1. variance
def target_variance_demo(n_states=19, s=10, reps=200_000):
    """Var of the MC return vs Var of the one-step TD target at state s,
    when V is the exact v_pi.  Reward is 1 on the right exit, else 0."""
    v = np.arange(1, n_states + 1) / (n_states + 1)       # true values
    # MC return from s: Bernoulli(v[s-1]) (the exit side).
    ret = rng.random(reps) < v[s - 1]
    # TD target: R + V(S') where S' = s -/+ 1 with prob 1/2 each, R = 0
    # (no terminal neighbours when 1 < s < n_states).
    nxt = np.where(rng.random(reps) < 0.5, s - 1, s + 1)
    tgt = v[nxt - 1]
    vs = v[s - 1]
    print("1. Variance of the target at state s=%d (V exact, true v=%.3f)" % (s, vs))
    print("   %-26s %10s %10s" % ("", "exact", "simulated"))
    print("   %-26s %10.4f %10.4f" % ("Var(G)  = v(1-v)", vs * (1 - vs), ret.var()))
    print("   %-26s %10.4f %10.4f" % ("Var(R+V(S')) = 1/400", 1 / 400, tgt.var()))
    print("   %-26s %10.4f %10.4f" % ("mean of G", vs, ret.mean()))
    print("   %-26s %10.4f %10.4f" % ("mean of R+V(S')", vs, tgt.mean()))
    print()


# ----------------------------------------------- 2. n-step TD, bias / variance
def simulate_paths(runs, episodes, n_states, start):
    """State paths of the symmetric random walk, shared by all configurations
    (common random numbers).  States 1..n_states, exits at 0 and n_states+1.
    Returns paths (runs, episodes, Tmax) with -1 padding, lengths T (number
    of steps taken = index of the terminal time) and outcome z in {0, 1}."""
    N = runs * episodes
    pos = np.full(N, start)
    cols = [pos.copy()]
    alive = np.ones(N, bool)
    T = np.zeros(N, int)
    while alive.any():
        pos = np.where(alive, pos + np.where(rng.random(N) < 0.5, -1, 1), pos)
        T += alive
        alive &= (pos > 0) & (pos <= n_states)
        cols.append(np.where(alive, pos, -1))
    paths = np.stack(cols, axis=1).astype(np.int16)           # terminal -> -1
    z = (pos == n_states + 1).astype(float)
    return (paths.reshape(runs, episodes, -1), T.reshape(runs, episodes),
            z.reshape(runs, episodes))


def run_nstep_td(paths, T, z, n_states, n, alpha, v0=0.0):
    """Online n-step TD on every run in parallel.  n=None means Monte Carlo.
    All rewards are 0 except the final one (z), and gamma = 1, so the n-step
    return from time tau is V(S_{tau+n}) if tau+n < T, else z."""
    runs, episodes, _ = paths.shape
    V = np.full((runs, n_states + 2), v0)
    V[:, 0] = V[:, -1] = 0.0                                   # terminals
    r = np.arange(runs)
    for e in range(episodes):
        P, Te, ze = paths[:, e], T[:, e], z[:, e]
        for tau in range(int(Te.max())):
            act = tau < Te
            s = np.where(act, P[:, tau], 1)
            if n is None:
                boot = np.zeros(runs, bool)
            else:
                boot = (tau + n) < Te
            nxt = P[:, min(tau + (n or 0), P.shape[1] - 1)]
            nxt = np.where(boot, nxt, 0)
            target = np.where(boot, V[r, nxt], ze)
            V[r, s] += np.where(act, alpha * (target - V[r, s]), 0.0)
    return V[:, 1:-1]


def nstep_experiment():
    n_states, start, runs, episodes = 19, 10, 1000, 10
    truth = np.arange(1, n_states + 1) / (n_states + 1)
    paths, T, z = simulate_paths(runs, episodes, n_states, start)
    ns = [1, 2, 4, 8, 16, 32, 64, None]
    alphas = [0.05, 0.1, 0.2, 0.3, 0.4, 0.6]
    res = {}
    for n in ns:
        for a in alphas:
            V = run_nstep_td(paths, T, z, n_states, n, a)
            bias2 = ((V.mean(0) - truth) ** 2).mean()          # averaged over states
            var = V.var(0).mean()
            res[(n, a)] = (bias2, var, bias2 + var)
    name = lambda n: "MC" if n is None else str(n)
    print("2. 19-state random walk, %d episodes, %d independent runs" % (episodes, runs))
    print("   Quantities are averaged over the 19 states; V0 = 0; truth v(s) = s/20.")
    print()
    a0 = 0.2
    print("   bias^2, variance, MSE at alpha = %.1f" % a0)
    print("   %-4s %10s %10s %10s %10s" % ("n", "bias^2", "variance", "MSE", "bias/var"))
    for n in ns:
        b, v, m = res[(n, a0)]
        print("   %-4s %10.5f %10.5f %10.5f %10.2f" % (name(n), b, v, m, b / v))
    print()
    print("   MSE by n (rows) and alpha (columns)")
    print("   %-4s" % "n" + "".join("%9.2f" % a for a in alphas) + "   best alpha")
    for n in ns:
        row = [res[(n, a)][2] for a in alphas]
        print("   %-4s" % name(n) + "".join("%9.5f" % m for m in row)
              + "   %.2f" % alphas[int(np.argmin(row))])
    print()
    print("   best MSE over alpha, with its bias^2 and variance")
    print("   %-4s %6s %10s %10s %10s" % ("n", "alpha", "bias^2", "variance", "MSE"))
    for n in ns:
        a = min(alphas, key=lambda a: res[(n, a)][2])
        b, v, m = res[(n, a)]
        print("   %-4s %6.2f %10.5f %10.5f %10.5f" % (name(n), a, b, v, m))
    print()


# ------------------------------------------------ 3. certainty equivalence
def batch_mc_td(episodes, states):
    """episodes: list of [(state, reward), ...] with reward received on leaving
    the state; the last step ends in a terminal.  Returns (V_mc, V_td)."""
    idx = {s: i for i, s in enumerate(states)}
    k = len(states)
    ret_sum, ret_cnt = np.zeros(k), np.zeros(k)
    trans, rew_sum, cnt = np.zeros((k, k)), np.zeros(k), np.zeros(k)
    for ep in episodes:
        G = 0.0
        for j in range(len(ep) - 1, -1, -1):                   # gamma = 1
            s, r = ep[j]
            G += r
            ret_sum[idx[s]] += G
            ret_cnt[idx[s]] += 1
            cnt[idx[s]] += 1
            rew_sum[idx[s]] += r
            if j + 1 < len(ep):
                trans[idx[s], idx[ep[j + 1][0]]] += 1
    V_mc = np.where(ret_cnt > 0, ret_sum / np.maximum(ret_cnt, 1), 0.5)
    seen = cnt > 0
    P = trans / np.maximum(cnt, 1)[:, None]                    # MLE transitions
    r_hat = rew_sum / np.maximum(cnt, 1)                       # MLE mean rewards
    V_td = np.full(k, 0.5)
    A = np.eye(k)[np.ix_(seen, seen)] - P[np.ix_(seen, seen)]
    V_td[seen] = np.linalg.solve(A, r_hat[seen])               # v = r + P v
    return V_mc, V_td


def batch_td_iterate(episodes, states, alpha=0.01, sweeps=20000):
    """Batch TD(0): sweep the data repeatedly, add up the increments, apply
    them once per sweep.  Should converge to the certainty-equivalence value."""
    idx = {s: i for i, s in enumerate(states)}
    V = np.zeros(len(states))
    for _ in range(sweeps):
        d = np.zeros_like(V)
        for ep in episodes:
            for j, (s, r) in enumerate(ep):
                nxt = V[idx[ep[j + 1][0]]] if j + 1 < len(ep) else 0.0
                d[idx[s]] += r + nxt - V[idx[s]]
        V += alpha * d
    return V


def ab_example():
    data = [[("A", 0), ("B", 0)]] + [[("B", 1)]] * 6 + [[("B", 0)]]
    states = ["A", "B"]
    mc, td = batch_mc_td(data, states)
    it = batch_td_iterate(data, states)
    print("3a. Sutton & Barto A/B example: 8 episodes (A,0,B,0), 6 x (B,1), (B,0)")
    print("   %-26s %8s %8s" % ("", "V(A)", "V(B)"))
    print("   %-26s %8.4f %8.4f" % ("batch MC (mean return)", *mc))
    print("   %-26s %8.4f %8.4f" % ("batch TD(0), iterated", *it))
    print("   %-26s %8.4f %8.4f" % ("ML model, solved exactly", *td))
    print()


def random_walk_batch(runs=500, checkpoints=(1, 2, 5, 10, 25, 50)):
    """5-state walk from C, reward 1 at the right exit.  After k episodes,
    compute batch MC and batch TD(0) (via the ML model) and the RMS error
    over the five states, averaged over runs."""
    states = [1, 2, 3, 4, 5]
    truth = np.arange(1, 6) / 6
    err = {k: [[], []] for k in checkpoints}
    for _ in range(runs):
        eps = []
        for k in range(1, max(checkpoints) + 1):
            s, ep = 3, []
            while 1 <= s <= 5:
                s2 = s + (1 if rng.random() < 0.5 else -1)
                ep.append((s, 1.0 if s2 == 6 else 0.0))
                s = s2
            # episode as a list of (state, reward-on-leaving); states in order
            eps.append(ep)
            if k in err:
                mc, td = batch_mc_td(eps, states)
                err[k][0].append(np.sqrt(((mc - truth) ** 2).mean()))
                err[k][1].append(np.sqrt(((td - truth) ** 2).mean()))
    print("3b. 5-state random walk, RMS error over states, mean of %d runs" % runs)
    print("   %-9s %10s %10s" % ("episodes", "batch MC", "batch TD"))
    for k in checkpoints:
        print("   %-9d %10.4f %10.4f" % (k, np.mean(err[k][0]), np.mean(err[k][1])))
    print()


if __name__ == "__main__":
    target_variance_demo()
    nstep_experiment()
    ab_example()
    random_walk_batch()