RLS RL, Read as Statistics

ch09_uncertainty.py

Companion code for Two kinds of uncertainty, and the whole return distribution. Needs only Python 3 and NumPy: python code/ch09_uncertainty.py.

NumPy
"""Chapter 9: uncertainty and distributions.

Two experiments, NumPy only.

(a) Deep-sea exploration. An N x N grid, N steps per episode, the treasure sits
    in the bottom-right corner and moving right costs a little. Epsilon-greedy
    Q-learning needs exponentially many episodes; posterior sampling for RL
    (PSRL, Dirichlet posterior over transitions, Beta posterior over rewards)
    needs few. We report episodes until the first treasure over seeds.

(b) Quantile TD learning. A small Markov reward process whose return from the
    start state is bimodal with a mean near zero. Quantile TD (pinball loss)
    recovers the quantiles of the return distribution; the exact answer comes
    from Monte Carlo. A mean-only TD estimate sees only the mean.
"""
import numpy as np

# ---------------------------------------------------------------- (a) deep sea
SLIP = 0.1          # probability the chosen move is reversed
CAP = 3000          # give up after this many episodes


class DeepSea:
    """State = (row, col). Action 0 = left, 1 = right. Row increases each step."""

    def __init__(self, n, rng):
        self.n, self.rng = n, rng
        self.cost = 0.01 / n  # known cost of moving right

    def reset(self):
        self.row, self.col = 0, 0
        return self.row, self.col

    def step(self, a):
        move = 1 if a == 1 else -1
        if self.rng.random() < SLIP:
            move = -move
        self.col = min(max(self.col + move, 0), self.n - 1)
        self.row += 1
        treasure = float(self.row == self.n - 1 and self.col == self.n - 1)
        r = treasure - (self.cost if a == 1 else 0.0)
        return (self.row, self.col), r, self.row == self.n - 1, treasure > 0


def eps_greedy_first_treasure(n, rng, eps=0.1, alpha=0.1):
    env = DeepSea(n, rng)
    Q = np.zeros((n, n, 2))
    for ep in range(1, CAP + 1):
        s, done = env.reset(), False
        while not done:
            if rng.random() < eps:
                a = int(rng.integers(2))
            else:
                q = Q[s]
                a = int(rng.integers(2)) if q[0] == q[1] else int(np.argmax(q))
            s2, r, done, hit = env.step(a)
            target = r + (0.0 if done else Q[s2].max())
            Q[s + (a,)] += alpha * (target - Q[s + (a,)])
            if hit:
                return ep
            s = s2
    return CAP


def psrl_first_treasure(n, rng):
    """PSRL. Posterior over next column of each (row, col, action): Dirichlet over
    the columns col-1, col, col+1 (clamped to the grid); posterior over the
    reward received on arriving in each state: Beta. Each episode: draw one model
    from the posterior, solve it exactly by backward induction, follow its policy."""
    env = DeepSea(n, rng)
    # counts[row, col, action, k] for next column col + k - 1 (k = 0, 1, 2); prior 0.5
    counts = np.full((n, n, 2, 3), 0.5)
    rew_a = np.ones((n, n))   # Beta(1, 1) on reward at each state
    rew_b = np.ones((n, n))
    cols = np.arange(n)
    nxt = np.clip(cols[:, None] + np.arange(-1, 2)[None, :], 0, n - 1)  # (col, k)
    for ep in range(1, CAP + 1):
        g = rng.gamma(counts)
        P = g / g.sum(-1, keepdims=True)           # sampled transition model
        rbar = rng.beta(rew_a, rew_b)              # sampled arrival rewards
        V = np.zeros(n)                            # value at the last row is 0 after arrival
        policy = np.zeros((n, n), dtype=int)
        for row in range(n - 2, -1, -1):
            Qv = np.zeros((n, 2))
            for a in (0, 1):
                cost = env.cost if a == 1 else 0.0
                # expected (sampled reward at arrival + value) over next col
                nv = rbar[row + 1][nxt] + V[nxt]   # (col, k)
                Qv[:, a] = (P[row, :, a, :] * nv).sum(-1) - cost
            policy[row] = Qv.argmax(1)
            V = Qv.max(1)
        s, done = env.reset(), False
        while not done:
            a = policy[s]
            s2, r, done, hit = env.step(a)
            k = s2[1] - s[1] + 1
            if 0 <= k <= 2 and nxt[s[1], k] == s2[1]:
                counts[s + (a, k)] += 1
            else:                                   # clamped move: find matching slot
                counts[s + (a, int(np.where(nxt[s[1]] == s2[1])[0][0]))] += 1
            rew_a[s2] += float(hit)
            rew_b[s2] += float(not hit)
            if hit:
                return ep
            s = s2
    return CAP


def experiment_a():
    seeds = 20
    print("(a) Deep sea: episodes until the first treasure (cap %d), %d seeds" % (CAP, seeds))
    print("%4s | %-22s | %-22s" % ("N", "eps-greedy med [min,max]", "PSRL med [min,max]"))
    for n in (4, 6, 8, 10, 12):
        row = []
        for algo in (eps_greedy_first_treasure, psrl_first_treasure):
            res = np.array([algo(n, np.random.default_rng(1000 * n + s)) for s in range(seeds)])
            row.append("%6.0f [%4d,%4d] %2d/%d" % (np.median(res), res.min(), res.max(),
                                                    (res < CAP).sum(), seeds))
        print("%4d | %s | %s" % (n, row[0], row[1]))
    print("(last column of each cell: seeds that found the treasure before the cap)")


# ---------------------------------------------------- (b) quantile TD learning
GAMMA = 0.9
NQ = 21
TAU = (np.arange(NQ) + 0.5) / NQ
# states: 0 start, 1 good, 2 bad, 3 terminal
UP, DOWN, SD = 2.0, -1.5, 0.5
STAY = 0.5   # probability of staying in the good/bad state


def mrp_step(s, rng):
    """Returns (reward, next_state)."""
    if s == 0:
        return 0.0, (1 if rng.random() < 0.5 else 2)
    mu = UP if s == 1 else DOWN
    r = mu + SD * rng.standard_normal()
    return r, (s if rng.random() < STAY else 3)


def mc_returns(n, rng):
    out = np.empty(n)
    for i in range(n):
        s, g, disc = 0, 0.0, 1.0
        while s != 3:
            r, s = mrp_step(s, rng)
            g += disc * r
            disc *= GAMMA
        out[i] = g
    return out


def quantile_td(episodes, rng):
    theta = np.zeros((3, NQ))   # quantile estimates per non-terminal state
    V = np.zeros(3)             # mean-only TD(0) for comparison
    visits = np.zeros(3)
    for _ in range(episodes):
        s = 0
        while s != 3:
            r, s2 = mrp_step(s, rng)
            # decaying step size (Robbins-Monro style) with a small floor
            alpha = max(0.001, 3.0 / (visits[s] + 30.0) ** 0.7)
            visits[s] += 1
            if s2 == 3:
                targets = np.array([r])
                v_next = 0.0
            else:
                targets = r + GAMMA * theta[s2]
                v_next = V[s2]
            V[s] += alpha * (r + GAMMA * v_next - V[s])
            # delta[i, j] = target_j - theta_i ; pinball-loss gradient step
            delta = targets[None, :] - theta[s][:, None]
            # gradient step on the pinball loss: tau - P(target < theta_i)
            theta[s] += alpha * (TAU - (delta < 0).mean(1))
            s = s2
    return theta, V


def experiment_b():
    rng = np.random.default_rng(7)
    G = mc_returns(200_000, rng)
    theta, V = quantile_td(150_000, rng)
    exact_q = np.quantile(G, TAU)
    print("\n(b) Quantile TD vs exact (Monte Carlo, 200000 returns) from the start state")
    print("%6s %9s %9s" % ("tau", "exact", "QTD"))
    for i in range(0, NQ, 2):
        print("%6.3f %9.3f %9.3f" % (TAU[i], exact_q[i], theta[0, i]))
    print("mean return, Monte Carlo     : %7.3f" % G.mean())
    print("mean from QTD quantiles      : %7.3f" % theta[0].mean())
    print("mean-only TD(0) estimate V(0): %7.3f" % V[0])
    print("P(G < 0), Monte Carlo        : %7.3f" % (G < 0).mean())
    print("P(G < 0), from QTD quantiles : %7.3f" % (theta[0] < 0).mean())
    print("P(|G - mean| < 0.5), MC      : %7.3f  (mass near the mean)" %
          (np.abs(G - G.mean()) < 0.5).mean())


if __name__ == "__main__":
    experiment_a()
    experiment_b()