import matplotlib.pyplot as plt
RNG = np.random.default_rng(20260725)
# --- the corridor of @fig-4-reinforce-qac, unchanged --------------------------
# Six states s0 -> ... -> s5. Action 0 ADVANCES, and from s5 it steps off the end,
# collects R_GOAL and ends the episode; action 1 GOES BACK, and at s0 it bumps into
# the wall. Advancing is therefore the good action at every state, which is what makes
# a single probability per state the whole policy worth watching.
N_S, GAMMA, R_GOAL, SD, T_MAX = 6, 0.95, 10.0, 3.0, 80
ALPHA_THETA, ALPHA_W = 0.003, 0.05
BUDGET, N_RUNS, LEVEL = 20_000, 60, 0.75
GRID = np.linspace(0, BUDGET, 201)
def step(s, a):
"""One transition: returns (next state, realized reward, episode over?)."""
r = RNG.normal(R_GOAL if (a == 0 and s == N_S - 1) else 0.0, SD)
if a == 0:
return s + 1, r, s == N_S - 1
return max(s - 1, 0), r, False
def p_advance(theta):
"""pi(advance | s, theta) at every state: the softmax @eq-softmax, two actions.
With |A| = 2 the softmax collapses to a logistic in the preference gap, so the
entire policy is these six numbers and the figure can just plot them.
"""
return 1.0 / (1.0 + np.exp(theta[:, 1] - theta[:, 0]))
def run_qac():
"""One QAC run; returns pi(advance | s, theta) at every grid point, per state.
Identical to the QAC of @fig-4-reinforce-qac. What is recorded differs: there the
run was scored by J(theta), here by the policy itself, sampled on a common grid of
environment steps and held flat between the crossings of that grid.
"""
theta, w = np.zeros((N_S, 2)), np.zeros((N_S, 2))
curve = np.full((len(GRID), N_S), 0.5) # theta_0 = 0 is a coin flip everywhere
k, steps = 1, 0
while steps < BUDGET:
s = 0
a = 0 if RNG.random() < p_advance(theta)[s] else 1
for _ in range(T_MAX):
s2, r, done = step(s, a)
if done:
target = r
else:
a2 = 0 if RNG.random() < p_advance(theta)[s2] else 1
target = r + GAMMA * w[s2, a2] # bootstrap, not a realized return
q_sa = w[s, a] # the critic BEFORE its own update, per @eq-qac-actor
w[s, a] += ALPHA_W * (target - q_sa) # critic, @eq-qac-critic
pa = p_advance(theta)[s] # the score, read at the CURRENT theta
theta[s, a] += ALPHA_THETA * q_sa # actor, @eq-qac-actor
theta[s, 0] -= ALPHA_THETA * q_sa * pa
theta[s, 1] -= ALPHA_THETA * q_sa * (1.0 - pa)
steps += 1
if k < len(GRID) and GRID[k] <= steps:
row = p_advance(theta)
while k < len(GRID) and GRID[k] <= steps:
curve[k] = row
k += 1
if done or steps >= BUDGET:
break
s, a = s2, a2
return curve
curves = np.array([run_qac() for _ in range(N_RUNS)]) # runs x grid x state
med = np.median(curves, axis=0)
# When each RUN first puts probability LEVEL on advancing at each state. A run that
# never gets there inside the budget is censored at the budget rather than dropped,
# which understates the lag at s0 instead of hiding it.
hit = curves >= LEVEL
first = np.where(hit.any(axis=1), GRID[hit.argmax(axis=1)], BUDGET)
lo, mid, hi = np.percentile(first, [25, 50, 75], axis=0)
# ponytail: one runnable check of the figure's claim, on the simulated runs themselves.
# The good action must end near certain everywhere without ever reaching one, the fan
# must open in corridor order while it is opening, and the experience each state needs
# to reach LEVEL must fall monotonically as the state gets nearer the goal.
i3k = int(np.argmin(np.abs(GRID - 3000)))
assert 0.85 < med[-1].min() and med[-1].max() < 1.0, np.round(med[-1], 3)
assert np.all(np.diff(med[i3k]) > 0), np.round(med[i3k], 3)
assert np.all(np.diff(mid) < 0), mid
fig, (axL, axR) = plt.subplots(1, 2, figsize=(9.4, 3.9),
gridspec_kw={"width_ratios": [1.5, 1]})
trim(axL), trim(axR)
# --- left: the six probabilities, from a coin flip toward one ----------------
# s5 touches the reward and s0 is where J is measured, so those two carry colour and
# the four in between stay grey: the fan's ordering is the right panel's job.
axL.plot([0, BUDGET], [LEVEL, LEVEL], color=GREY, lw=0.9, ls="--", zorder=2)
for j in range(N_S):
colour = COL["vermilion"] if j == N_S - 1 else COL["blue"] if j == 0 else GREY
axL.plot(GRID, med[:, j], color=colour, lw=2.0 if colour != GREY else 1.2,
zorder=5 if colour != GREY else 3)
axL.set_xlim(0, BUDGET * 1.02)
axL.set_ylim(0.44, 1.005)
axL.set_xticks([0, 5000, 10000, 15000, 20000])
axL.set_xticklabels(["0", "5k", "10k", "15k", "20k"])
axL.set_yticks([0.5, 0.6, 0.7, 0.8, 0.9, 1.0])
axL.set_xlabel("environment steps (transitions consumed)")
axL.set_ylabel(r"$\pi(\mathrm{advance}\mid s,\theta)$, median over runs")
# Every label sits where no curve goes: the threshold tag on the dashed rule at the
# right margin, the s5 tag in the empty strip above every curve, and the s0 tag plus
# the grey note in the whole empty lower-right quadrant beneath the slowest curve.
label_at(axL, 17400, 0.716, r"$\pi=0.75$", color=GREY, fontsize=8.5)
label_at(axL, 300, 0.468, r"$\theta_{0}=0$: a coin flip at every state",
color=GREY, fontsize=8.5)
label_at(axL, 4500, 0.985, r"$s_{5}$, one step from the goal",
color=COL["vermilion"], fontsize=9.5)
label_at(axL, 6300, 0.632, r"$s_{0}$, the start", color=COL["blue"], fontsize=9.5)
label_at(axL, 6300, 0.560, r"$s_{1}$ to $s_{4}$ in grey", color=GREY, fontsize=8.5)
axL.set_title("Every state's good action climbs toward certainty", fontsize=11)
# --- right: when each state gets there --------------------------------------
# States run up the y-axis so that this panel's vertical order is the left panel's
# fan order, and both panels are read in the same units on x.
axR.plot(mid, range(N_S), color=GREY, lw=1.0, zorder=3)
for j in range(N_S):
colour = COL["vermilion"] if j == N_S - 1 else COL["blue"] if j == 0 else INK
axR.plot([lo[j], hi[j]], [j, j], color=GREY, lw=1.4, zorder=4)
axR.plot([mid[j]], [j], "o", color=colour, ms=6, zorder=5)
axR.set_xlim(0, 8600)
axR.set_ylim(-0.6, 5.6)
axR.set_xticks([0, 2000, 4000, 6000, 8000])
axR.set_xticklabels(["0", "2k", "4k", "6k", "8k"])
axR.set_yticks(range(N_S))
axR.set_yticklabels([rf"$s_{{{j}}}$" for j in range(N_S)])
axR.set_xlabel(r"environment steps to first reach $\pi=0.75$")
label_at(axR, 4500, 5.15, "dot: median across\n"
f"{N_RUNS} runs, bar: their\ninterquartile range",
color=GREY, fontsize=8.5, va="top")
axR.set_title("The far end sharpens first, the tilt travels back", fontsize=11)
fig.tight_layout()
plt.show()