Reinforcement learning
A robot in one corner. Home in the far corner, worth +20.
Nobody tells it which way to go. It only learns what a cell paid after it gets there.
How can it find the best way home, and what does "best" even mean?
Two sittings: parts 1 to 3 on Tuesday, parts 4 to 6 on Thursday.
Video: OpenAI, Multi-Agent Hide and Seek (2 min 57 s). Paper: Baker et al., Emergent tool use from multi-agent autocurricula (2019).
The agent acts; the environment answers with a new state and a reward.
| States | \(s \in \{(1,1), (1,2), \ldots, (4,4)\}\) |
| Actions | \(a \in \{\text{right}, \text{left}, \text{up}, \text{down}\}\) |
| Rewards | \(R(s) \in [-5, 20]\) |
| Transitions | \(P(s' \mid s, a) \in [0, 1]\) |
Total reward
0
One trip on the grid.
An action goes where it points with probability 0.8, and slips to each side with probability 0.1.
Where the robot goes next depends only on where it is and what it does now.
Utility: the total for the trip.
Discount factor \(\gamma < 1\) favors immediate rewards over future ones.
Independence of actions: here the reward depends on the cell only.
Given a die with 6 faces, numbered 1 to 6. If you throw the die and get face 1, you make $1; if you get 2, you make $2, and so on. What is your expected return?
| \(s, s' \in S\) | a state and the next state |
| \(a \in A\) | an action |
| \(P(s' \mid s, a)\) | the probability of landing in \(s'\) |
| \(R(s)\) | the reward for being in \(s\) |
| \(\gamma\) | the discount factor, here 0.9 |
| \(\pi(s)\) | a policy: the action taken in \(s\) |
| \(V^\pi(s)\) | the value of \(s\) under \(\pi\) |
| \(Q^\pi(s, a)\) | the value of doing \(a\) in \(s\), then following \(\pi\) |
| \(V^\star, \pi^\star\) | the optimal value function and policy |
Part 2 of 6
How much is it worth to stand in a cell?
We are executing some policy \(\pi\) if whenever we are at \(s\), we take action \(a\) according to
One arrow per cell: \(4^{15}\) = 1,073,741,824 policies. Which one is best?
\(V^\pi(s)\) is the expected sum of discounted rewards upon starting in state \(s\), and taking actions according to \(\pi\).
One number per cell. For the best policy on our grid, \(V^\pi(1,1) = 94.4\) and \(V^\pi(4,4) = 200\).
Collect \(R(s)\) now, then the average value of where the action can lead.
Equation for \(V^\pi(s_0)\):
One such line for each of the 15 cells: a linear system.
Can you beat 67.3 from (1,1) by hand?
What's the optimal policy the agent can take if they start at state \(s\)?
Knowing \(V^\star\) is enough: take the action whose next cells are worth most on average.
The \(\max\) makes the system nonlinear: no solving it in one step.
Part 3 of 6
How does the robot find the best way home when it knows the map?
Value iteration algorithm
initialize \(V(s) = 0\), for each state \(s\)
while not converged:
for every state \(s\):
\( V(s) = R(s) + \gamma \max_{a \in A} \sum_{s'} P(s' \mid s, a)\, V(s') \)
end
end
Synchronous: compute new \(V(s)\) for all \(s\), then overwrite old \(V(s)\).
Asynchronous: update \(V(s)\) one at a time.
Start from \(V_0(s) = 0\) everywhere, with \(\gamma = 0.9\).
Pushing into a wall or an edge keeps the robot where it is.
\(V_2(1,3) = 1 + 0.9 \times 1 = 1.9\): pushing up keeps the robot on the coin.
\(V_2(2,3) = 0 + 0.9 \times 5 = 4.5\), \(V_2(3,4) = V_2(4,3) = 0.9 \times 20 = 18.0\), and home itself \(V_2(4,4) = 20 + 0.9 \times 20 = 38.0\).
Each sweep lets a reward reach one more cell: information travels backwards from the rewards.
changed in this sweepthe greedy action
states = [(i, j) for i in range(1, 5)
for j in range(1, 5) if (i, j) != (1, 4)]
R = {(1, 3): 1, (2, 4): 5, (3, 2): 2,
(3, 1): -5, (3, 3): -5, (4, 4): 20}
gamma, slip = 0.9, 0.2
actions = {"right": (0, 1), "left": (0, -1),
"up": (-1, 0), "down": (1, 0)}
def move(s, a): # wall or edge: stay
n = (s[0] + actions[a][0], s[1] + actions[a][1])
return n if n in states else s
R lists only the cells that pay. move into the wall or off the grid: the robot stays.
LR, UD = ["right", "left"], ["up", "down"]
side = {"right": UD, "left": UD, "up": LR, "down": LR}
def P(s, a): # a list of (s', probability)
if s == (4, 4):
return [(s, 1.0)] # home keeps the robot
p = {}
for b, w in [(a, 1 - slip),
(side[a][0], slip / 2),
(side[a][1], slip / 2)]:
p[move(s, b)] = p.get(move(s, b), 0) + w
return list(p.items())
P((2, 2), "down"): 0.8 down, 0.1 to each side.
V = {s: 0.0 for s in states} # V(s) = 0 to start
def sweep(V): # the Bellman update, every cell
new = {}
for s in states:
best = max(sum(p * V[n] for n, p in P(s, a))
for a in actions)
new[s] = R.get(s, 0) + gamma * best
return new
sum(p * V[n] ...)
\(\max_a\)max(... for a ...)
\(R(s)\)R.get(s, 0)
\(\gamma\)gamma
for k in range(1, 1000):
new = sweep(V)
change = max(abs(new[s] - V[s]) for s in states)
V = new
if change < 0.01: # nothing moved: stop
break
print(f"converged after {k} sweeps")
The largest change shrinks by \(\gamma\) at every sweep: 74 sweeps.
def q(s, a): # the average value of a in s
return sum(p * V[n] for n, p in P(s, a))
pi = {s: max(actions, key=lambda a: q(s, a))
for s in states}
for i in range(1, 5):
row = [f"{V[i, j]:6.1f} {pi[i, j]:>5}"
if (i, j) in V else " wall "
for j in range(1, 5)]
print(" ".join(row))
The numbers are V, the arrows pi.
Policy iteration algorithm
initialize \(\pi\) randomly
while not converged:
Let \(V = V^\pi\) (by solving the linear system)
for every state \(s\):
\( \pi(s) = \arg\max_{a \in A} \sum_{s'} P(s' \mid s, a)\, V(s') \)
end
end
On our grid, starting from "always right", the policy stops changing after 4 solves, at the same \(\pi^\star\) as value iteration.
| policy iteration | value iteration | |
|---|---|---|
| one step | solve \(|S|\) linear equations, then improve every arrow | one sweep of the Bellman update |
| steps on our grid | 4 | 74 sweeps |
| with \(\gamma = 0.99\) | 4 | 758 sweeps |
Part 4 of 6 · Thursday
What if the robot does not know P and R?
The best route picks up the coin and the battery and goes around both puddles: \(V^\star(1,1) = 94.4\).
Today the robot is not told \(P\) or \(R\). It can only walk, and see what each cell paid.
What is the state? What is the action?
States and actions are discretized:
Nobody writes down \(P\) for a pole on a cart. But we can push the cart and watch.
\(s_i^{(j)}\): state at time \(i\) of trial \(j\). \(a_i^{(j)}\): action taken from that state.
initialize \(\pi\) randomly
for trials:
for trials:
Execute \(\pi\) in MDP
end
update estimates of \(P(s' \mid s, a)\) and \(R(s)\)
apply value iteration to find new \(V(s)\)
update \(\pi\)
end
This is model-based: the robot builds the map from counts, then uses Tuesday's algorithm.
The next slides skip the map altogether.
\(Q^\pi(s, a)\) is an expected total reward. How do we get an expectation without \(P\)?
\(u\): the utility of one trip. Tuesday's total rewards, counted from \((s, a)\) on.
the policy \(\pi\)the last trip
For each \((s, a, u)\):
\( \textcolor{#61afef}{\hat{Q}^\pi(s, a)} \leftarrow (1 - \eta)\, \textcolor{#61afef}{\hat{Q}^\pi(s, a)} + \eta\, \textcolor{#f2c94c}{u} \)
The same line, as a correction:
\( \hat{Q}^\pi(s, a) \leftarrow \hat{Q}^\pi(s, a) - \eta \left[ \hat{Q}^\pi(s, a) - u \right] \)
Prediction minus target is the error: a step of gradient descent.
A constant \(\eta\) forgets. That is what we want once the policy, and so the target, keeps changing.
For each \((s, a, R, s', a')\):
\( \hat{Q}^\pi(s, a) \leftarrow (1 - \eta)\, \hat{Q}^\pi(s, a) + \eta \left[ \textcolor{#f2c94c}{R(s)} + \gamma\, \textcolor{#61afef}{\hat{Q}^\pi(s', a')} \right] \)
| Monte Carlo: \(u\) | SARSA: \(R(s) + \gamma \hat{Q}^\pi(s', a')\) | |
|---|---|---|
| right on average | from the first trip | only once \(\hat{Q}^\pi\) is right |
| noise | high: every step of the trip is random | low: one random step |
| ready | at the end of the trip | after one step |
For each \((s, a, R, s')\):
\( \hat{Q}^\star(s, a) \leftarrow (1 - \eta)\, \hat{Q}^\star(s, a) + \eta \left[ \textcolor{#f2c94c}{R(s)} + \gamma\, \textcolor{#61afef}{\max_{a'} \hat{Q}^\star(s', a')} \right] \)
| target | it has to wait for | |
|---|---|---|
| Monte Carlo | \( \textcolor{#f2c94c}{u = R(s) + \gamma R(s') + \gamma^2 R(s'') + \ldots} \) | the end of the trip |
| SARSA | \( \textcolor{#f2c94c}{R(s)} + \gamma\, \textcolor{#61afef}{\hat{Q}(s', a')} \) | one step and its next action |
| Q-learning | \( \textcolor{#f2c94c}{R(s)} + \gamma\, \textcolor{#61afef}{\max_{a'} \hat{Q}(s', a')} \) | one step |
data: rewards the robot collectedestimate: a number read from its table
the best action so farthe last trip
def lcg(seed): # the deck's random numbers
while True:
seed = (seed * 1664525 + 1013904223) % 2**32
yield seed / 2**32
def choose(Q, s, eps, r): # explore, or take the best
if next(r) < eps:
return int(next(r) * 4)
top = max(Q[s])
best = [a for a in range(4)
if Q[s][a] >= top - 1e-12]
if len(best) == 1:
return best[0]
return best[int(next(r) * len(best))] # a tie
next(r) < eps
otherwise the best \(\hat{Q}\)best[0]
lcg is the deck's random numbers, so your run matches the widget's.
def step(s, a, r): # a draw from P(s'|s,a)
u, acc = next(r), 0
for n, p in P(s, list(actions)[a]):
acc += p
if u < acc:
return n
return n
One random number u picks the outcome: 0.8 of the time, where the action points.
def update(Q, s, a, n, eta): # one step of learning
target = R.get(s, 0) + gamma * max(Q[n])
Q[s][a] = (1 - eta) * Q[s][a] + eta * target
R.get(s, 0) + gamma * max(Q[n])
move toward it by \(\eta\)(1 - eta) * Q[s][a] + eta * target
For SARSA, the target would use the action it will take next, \(Q[n][a2]\), instead of \(\max(Q[n])\).
def trip(Q, eps, eta, r, T=40): # 40 steps from (1,1)
s, G = (1, 1), 0
a = choose(Q, s, eps, r)
for t in range(T):
G += gamma**t * R.get(s, 0)
n = step(s, a, r)
a2 = choose(Q, n, eps, r)
update(Q, s, a, n, eta)
s, a = n, a2
return G
Every step gives one \((s, a, R, s')\), and one update.
def q_learning(eps, eta, trips=100, seed=1):
r = lcg(seed)
Q = {s: [0.0] * 4 for s in states}
returns = [trip(Q, eps, eta, r)
for _ in range(trips)]
return Q, returns
Q, returns = q_learning(eps=0.1, eta=0.5)
mean = lambda x: sum(x) / len(x)
first, last = mean(returns[:10]), mean(returns[-10:])
print(f"first 10 trips: {first:.1f}", end=" ")
print(f"last 10: {last:.1f}")
print(f"all 100 trips: {mean(returns):.1f}")
First 10 trips: 19.2. Last 10: 77.8.
names = list(actions)
for i in range(1, 5):
row = [f"{max(Q[i, j]):6.1f} "
f"{names[Q[i, j].index(max(Q[i, j]))]:>5}"
if (i, j) in Q else " wall "
for j in range(1, 5)]
print(" ".join(row))
At (1,1) the arrow still points left, into the edge: not finished.
Score: the mean return of the 100 trips, averaged over 10 worlds.
| # | team | \(\epsilon\) | \(\eta\) | score | greedy \(V^\pi(1,1)\) |
|---|
Best: \(\epsilon = 0.15\), \(\eta = 0.4\), with 61.6.
Never exploring is the worst choice: 22.2 at best.
The best exploration is some: not none, and not much.
Part 5 of 6
What if there are too many states to list, and can we learn the policy directly?
\(\phi(s, a)\): features of the pair, chosen by us. \(\mathbf{w}\): the weights to learn, in place of the table.
Q-learning's prediction and target, with \(\hat{V}^\star(s') = \max_{a'} \hat{Q}^\star(s', a'; \mathbf{w})\).
For each \((s, a, R, s')\):
\( \mathbf{w} \leftarrow \mathbf{w} - \eta \left[ \hat{Q}^\star(s, a; \mathbf{w}) - \left( R(s) + \gamma \hat{V}^\star(s') \right) \right] \phi(s, a) \)
A regression with a moving target. Replace \(\mathbf{w} \cdot \phi\) by a neural network: deep Q-learning.
Downsides of discretization:
A cart-pole has \(d = 4\) numbers: \(k = 10\) gives 10,000 states, \(k = 100\) gives 100,000,000.
\(s_{t+1} \sim P(\,\cdot \mid s_t, a_t)\): the simulator is the map, in a form we can sample from but not write as a table.
Learn a state-space model
with \(A\) and \(B\) as fitting parameters (least squares on the pairs \((s_t, a_t) \mapsto s_{t+1}\)).
Sample a few states, simulate their next states, and fit \(V(s) = \theta^\top \phi(s)\) by regression.
The full algorithm: CS229 notes, chapter 15 (cs229.stanford.edu).
For each step \(t\) of each trip, with \(u_t\) the utility from \(t\) on (REINFORCE):
\( \theta \leftarrow \theta + \eta \,(u_t - b)\, \nabla_\theta \log \pi_\theta(a_t \mid s_t) \)
Make the actions that were followed by more reward than usual more likely.
No value function, no \(\max\): "do more of what was followed by more reward".
Part 6 of 6
What happens when the reward is not what we meant?
We meant "get home". We wrote "+5 on the battery, +20 at home".
Nothing is wrong with value iteration. It found the best policy for the reward we wrote.
Early on 83% of the trips end at home. By the end only 8%: the robot parks on the battery.
The better the learner, the more reliably it finds what the reward pays for. This is reward hacking.
Video: CoastRunners 7 (57 s), from OpenAI's "Faulty reward functions in the wild" (Clark and Amodei, 2016).
The agent circles a lagoon, hitting the same three targets as they respawn. It never finishes the race, and outscores human players.
Amodei et al., Concrete problems in AI safety (2016).
Show a person two outputs \(y_A\) and \(y_B\) for the same prompt \(x\). Fit a reward model \(r_\phi(x, y)\) so that the preferred one scores higher:
Logistic regression on differences: the sigmoid of the reward gap.
Christiano et al. (2017): a simulated robot learned a backflip from about 900 such comparisons.
Step 3 is a policy gradient, like the fork. The KL term keeps the model close to where it started.
A question to keep: what does a model learn from predicting the next word, before any of this? That is the model RLHF starts from.
Gymnasium is an open source Python library for developing and comparing reinforcement learning algorithms: one interface between learning algorithms and environments, and a standard set of environments.
import gymnasium as gym
env = gym.make("FrozenLake-v1", is_slippery=True)
s, info = env.reset(seed=0)
s, r, done, truncated, info = env.step(2) # 2 = right