Reinforcement learning

How Does a Robot Learn Its Way Across a Grid Without a Map?

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.

Six questionsParts 1 to 3 assume the robot knows the map; parts 4 to 6 take it away

  1. 1The agent and its worldWhat is an agent, and what is it trying to do?
  2. 2How good is a policy?How much is it worth to stand in a cell?
  3. 3Value iterationHow does the robot find the best way home when it knows the map?
  4. 4Learning without a mapWhat if the robot does not know P and R?
  5. 5Too big for a tableWhat if there are too many states to list, and can we learn the policy directly?
  6. 6Where it breaksWhat happens when the reward is not what we meant?

Example: OpenAI's Multi-Agent Hide and SeekNobody programmed these strategies. The agents were rewarded for hiding or for finding, and played

What are the features of an intelligent agent?

  • Actions: make decisions and act from a set of possible actions
  • Perceptions: observe the world and one's own state
  • Plan for long-term consequences: decisions today will affect the state tomorrow and later
  • Information: decisions will determine how much information you collect from the environment
  • No or little supervision: collect more data interactively

The agent acts; the environment answers with a new state and a reward.

ExampleThe gridworld of this lecture. Drive the robot home, and watch it slip

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]\)
upup

Total reward

0

DefinitionsA trip is a chain: state, action, next state, reward, and so on

One trip on the grid.

Markov Decision Process (MDP)Assumes a probabilistic (uncertain) world. Pick an action for the robot at (2,2)

An action goes where it points with probability 0.8, and slips to each side with probability 0.1.

Markov Decision Process (MDP)The Markov assumption: transition probability only depends on previous state

\( P(s_i \mid s_{i-1}, s_{i-2}, s_{i-3}, a_i, a_{i-1}, \ldots) = P(s_i \mid s_{i-1}, a_i) \)

Where the robot goes next depends only on where it is and what it does now.

Goal: Maximize Total RewardsDefinition of total rewards

\( \text{Total Rewards} = R(s_1, a_1) + \gamma R(s_2, a_2) + \gamma^2 R(s_3, a_3) + \ldots \)
\( \text{Total Rewards} = R(s_1) + \gamma R(s_2) + \gamma^2 R(s_3) + \ldots \)

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.

A reward foreverHome pays +20 at every step the robot stays there. Drag gamma

\( 20 + 20\gamma + 20\gamma^2 + \ldots = \dfrac{20}{1 - \gamma} \)

Goal: Maximize Expectation of Total RewardsGiven that decisions are probabilistic, we want to maximize the expected rewards

\( \text{Total Expected Rewards} = \mathbb{E}\left[ R(s_1) + \gamma R(s_2) + \gamma^2 R(s_3) + \ldots \right] \)
example

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?

\( \sum_i P(i)\, C(i) = \tfrac{1}{6} \cdot 1 + \tfrac{1}{6} \cdot 2 + \ldots + \tfrac{1}{6} \cdot 6 = 3.5 \)

Markov Decision Process (MDP)Five ingredients

  1. Set of states: \(S\)
  2. Set of actions: \(A\)
  3. State transition probability: \(P(s' \mid s, a) \equiv P_{sa}(s')\), for \(s, s' \in S\) and \(a \in A\)
  4. Reward function: \(R(s, a)\) or \(R(s)\), which maps states (and actions) to a real number in \(\mathbb{R}\)
  5. Discount factor: \(\gamma < 1\)

NotationThe same symbols on every slide, Tuesday and Thursday

\(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 good is a policy?

How much is it worth to stand in a cell?

How should the agent make decisions?The agent needs a policy for taking action

\( s \xrightarrow{\;\;\pi\;\;} a \)

We are executing some policy \(\pi\) if whenever we are at \(s\), we take action \(a\) according to

\( a = \pi(s) \)

One arrow per cell: \(4^{15}\) = 1,073,741,824 policies. Which one is best?

How good is a policy \(\pi\)?We can define a value function associated with a policy and a Markov decision process

\( V^\pi(s) = \mathbb{E}\left[ R(s_0) + \gamma R(s_1) + \gamma^2 R(s_2) + \ldots \mid s_0 = s, \pi \right] \)

\(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\).

Q-Value of a PolicyExpected utility of taking action \(a\) from state \(s\), then following policy \(\pi\)

\( Q^\pi(s, a) = R(s) + \gamma \sum_{s'} P(s' \mid s, a)\, V^\pi(s') \)

Collect \(R(s)\) now, then the average value of where the action can lead.

How good is a policy \(\pi\)?From the definition to the Bellman equation, one line at a time

\( V^\pi(s) = \mathbb{E}\left[ R(s_0) + \gamma R(s_1) + \gamma^2 R(s_2) + \ldots \mid s_0 = s, \pi \right] \)the definition \( V^\pi(s) = \mathbb{E}\left[ R(s_0) + \gamma \left( R(s_1) + \gamma R(s_2) + \ldots \right) \mid s_0 = s, \pi \right] \)factor out one \(\gamma\) \( V^\pi(s) = R(s) + \gamma\, \mathbb{E}\left[ R(s_1) + \gamma R(s_2) + \ldots \mid s_0 = s, \pi \right] \)\(R(s_0) = R(s)\) is not random \( V^\pi(s) = R(s) + \gamma\, \mathbb{E}\left[ V^\pi(s_1) \mid s_0 = s, \pi \right] \)the bracket is the value of \(s_1\) (Markov) \( V^\pi(s) = R(s) + \gamma \sum_{s' \in S} P(s' \mid s, \pi(s))\, V^\pi(s') \)\(s'\) is the state after \(s\)
The Bellman equation: \( V^\pi(s) = R(s) + \gamma \sum_{s' \in S} P(s' \mid s, \pi(s))\, V^\pi(s') \)

Bellman EquationGives a system of \(|S|\) linear equations, one for each unknown \(V^\pi(s)\)

Equation for \(V^\pi(s_0)\):

$$\begin{aligned} V^\pi(s_0) = R(s_0) + \gamma \big[\, &P(s'_{(1)} \mid s_0, \pi(s_0))\, V^\pi(s'_{(1)}) \\ + \,&P(s'_{(2)} \mid s_0, \pi(s_0))\, V^\pi(s'_{(2)}) \\ + \,&P(s'_{(3)} \mid s_0, \pi(s_0))\, V^\pi(s'_{(3)}) \\ + \,&P(s'_{(4)} \mid s_0, \pi(s_0))\, V^\pi(s'_{(4)}) \,\big] \end{aligned}$$

One such line for each of the 15 cells: a linear system.

Fifteen equations, solvedClick a cell to turn its arrow. The values are the solution of the 15 Bellman equations

Can you beat 67.3 from (1,1) by hand?

What's the optimal value function?In other words, what is the best expected sum of discounted rewards if one gets to choose any policy \(\pi\)?

\( V^\star(s) = \max_\pi V^\pi(s) \)

What's the optimal policy the agent can take if they start at state \(s\)?

\( \pi^\star(s) = \arg\max_{a \in A} \sum_{s' \in S} P(s' \mid s, a)\, V^\star(s') \)

Knowing \(V^\star\) is enough: take the action whose next cells are worth most on average.

Solving for the optimal value functionGiven the optimal policy, we can write its associated Bellman equation

\( \pi^\star(s) = \arg\max_{a \in A} \sum_{s' \in S} P(s' \mid s, a)\, V^\star(s') \)
\( V^\star(s) = R(s) + \gamma \max_{a \in A} \sum_{s' \in S} P(s' \mid s, a)\, V^\star(s') \)

The \(\max\) makes the system nonlinear: no solving it in one step.

Part 3 of 6

Value iteration

How does the robot find the best way home when it knows the map?

How to find the optimal value function?Given the reward function \(R(s)\) and the state transition probability \(P(s' \mid s, a)\)

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.

having found \(V^\star\)
\( \pi^\star(s) = \arg\max_{a \in A} \sum_{s' \in S} P(s' \mid s, a)\, V^\star(s') \)

Value iteration on the boardThe room is the grid. No slipping, so each action goes where it points

✏ exercise · do it now

Start from \(V_0(s) = 0\) everywhere, with \(\gamma = 0.9\).

  1. First sweep: \(V_1(s) = R(s)\). Write \(V_1\) in every cell.
  2. Second sweep: \(V_2(s) = R(s) + \gamma \max_{a} V_1(s')\). Work out \(V_2\) at (1,2), (1,3), (2,3), (2,4), (3,4), (4,3) and (4,4).
  3. Which cells get a new value? In which direction does the information travel?

Pushing into a wall or an edge keeps the robot where it is.

Value iteration on the board · answer\(V_2\), one sweep after \(V_1 = R\)

\(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.

Value iteration, sweep by sweepStep through the sweeps; change gamma and the slip

changed in this sweepthe greedy action

Value iteration in Python · the worldThe grid as two lists and a dictionary. Run each block in turn

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.

Value iteration in Python · the slip\(P(s' \mid s, a)\): where an action can lead, and how often

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.

Value iteration in Python · one sweepThe Bellman update, term by term

\( V(s) = \textcolor{#e5c07b}{R(s)} + \textcolor{#e06c75}{\gamma}\, \textcolor{#61afef}{\max_{a}} \textcolor{#98c379}{\sum_{s'} P(s' \mid s, a)\, V(s')} \)
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_{s'} P\, V(s')\)sum(p * V[n] ...) \(\max_a\)max(... for a ...) \(R(s)\)R.get(s, 0) \(\gamma\)gamma

Value iteration in Python · until nothing movesSweep, measure the largest change, stop when it is under 0.01

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.

Value iteration in Python · read off the policyIn each cell, the action with the best average value. \(V(1,1) = 94.3\)

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.

How to find the optimal policy?Given the reward function \(R(s)\) and the state transition probability \(P(s' \mid s, a)\)

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 vs. Value IterationTwo ways to the same answer

policy iterationvalue iteration
one stepsolve \(|S|\) linear equations, then improve every arrowone sweep of the Bellman update
steps on our grid474 sweeps
with \(\gamma = 0.99\)4758 sweeps
  • There is no agreement which is better.
  • For small MDPs, policy iteration is very fast.
  • But the linear solve step is slow for large state spaces, so value iteration is used more often.

ExamplesProblems that are written as MDPs

  • Grid world problems: Frozen Lake navigation, Cliff Walking, the Taxi problem
  • Resource management: inventory (stocks) control, server allocation, battery management (electric vehicle)
  • Games: Blackjack, chess, tic-tac-toe, Pac-Man navigation
  • Finance and trading: portfolio management, option pricing
  • Robotics and navigation: drone delivery, robot vacuum cleaning, robotic arm reaching
  • Healthcare and medicine: treatment planning, ICU ventilator management
  • Learning and education, manufacturing, environment and energy, transportation

Takeaways from Tuesday

  • An MDP is states, actions, transition probabilities, rewards and a discount. A policy picks an action in every state.
  • The value of a state is the expected discounted reward from there. For a fixed policy it solves |S| linear equations, the Bellman equation.
  • Value iteration repeats the Bellman update with a max until nothing changes: on our grid, 74 sweeps, and the best trip from (1,1) is worth 94.4.
  • All of this needs the map: P and R. On Thursday the robot has to do without it.

Part 4 of 6 · Thursday

Learning without a map

What if the robot does not know P and R?

Where we stopped on TuesdayThe answer value iteration gives, when the robot knows the map

\( V^\star(s) = R(s) + \gamma \max_{a} \sum_{s'} P(s' \mid s, a)\, V^\star(s') \)

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 if we don't know \(P(s' \mid s, a)\) and \(R(s)\)?We are not given state transitions and rewards explicitly, but are given data

What is the state? What is the action?

\(s\)statethe angle of the pole
\(a\)actionthe velocity of the cart

States and actions are discretized:

\(s\)\(\in [\ldots, -3, -2, -1, 0, 1, 2, 3, \ldots]\)degrees
\(a\)\(\in [\ldots, -3, -2, -1, 0, 1, 2, 3, \ldots]\)m/s

Nobody writes down \(P\) for a pole on a cart. But we can push the cart and watch.

What if we don't know \(P(s' \mid s, a)\) and \(R(s)\)?We are given a number of trials

\(s_i^{(j)}\): state at time \(i\) of trial \(j\).   \(a_i^{(j)}\): action taken from that state.

Learning \(P(s' \mid s, a)\)The robot wanders at random and keeps count. How would you estimate \(P\) from its counts?

\( \hat{P}(s' \mid s, a) = \dfrac{\#\text{ of times } s \xrightarrow{a} s'}{\#\text{ of times } s \xrightarrow{a}} \)

\( \hat{R}(s) = \dfrac{\text{sum of } R \text{ in } s}{\#\text{ of times in } s} \)

Find the optimal policy with unknown \(P\) and \(R\)Learn a model of the world, then plan in it

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.

Model-Free Monte Carlo: on-policySkip the map. Estimate \(Q^\pi(s, a)\) from the trips themselves

\( Q^\pi(s, a) = R(s) + \gamma \sum_{s'} \textcolor{#e06c75}{P(s' \mid s, a)}\, V^\pi(s') \)   needs \(P\)

\(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.

\( \hat{Q}^\pi(s, a) = \text{the average of } \textcolor{#f2c94c}{u} \text{ over the trips} \;\approx\; \mathbb{E}[u] \)

Monte Carlo on the gridA fixed policy \(\pi\). Send the robot on trips from (1,1) and average what they paid

the policy \(\pi\)the last trip

Why averaging the trips works\(Q^\pi(s, a)\) is an expectation, and an average of samples estimates an expectation

\( u = R(s_0) + \gamma R(s_1) + \gamma^2 R(s_2) + \ldots \)the utility of one trip that starts with \(s_0 = s\), \(a_0 = a\) \( Q^\pi(s, a) = \mathbb{E}\left[\, u \mid s_0 = s,\; a_0 = a,\; \pi \,\right] \)the definition: take \(a\) in \(s\), then follow \(\pi\) \( \hat{Q}^\pi(s, a) = \dfrac{1}{n} \sum_{i=1}^{n} u_i \;\approx\; \mathbb{E}[u] \)the law of large numbers, over \(n\) trips through \((s, a)\) \( \text{error} \sim \dfrac{\sigma_u}{\sqrt{n}} \)four times the trips for half the error
  • First visit: a trip counts once for \((s, a)\), from the first time it is there, so the samples are independent.
  • On-policy: the trips must be made with \(\pi\) itself, because \(u\) depends on every later action.

Model-Free Monte Carlo: on-policyThe average, kept up to date one trip at a time, with a learning rate \(\eta\)

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.

From the average to the learning rateA running average is an update, and \(\eta\) says how fast it forgets

\( \hat{Q}_n = \dfrac{1}{n} \sum_{i=1}^{n} u_i = \hat{Q}_{n-1} + \dfrac{1}{n} \left( u_n - \hat{Q}_{n-1} \right) \)the average after \(n\) trips, from the one after \(n - 1\) \( \hat{Q} \leftarrow (1 - \eta)\, \hat{Q} + \eta\, u, \quad \eta = \tfrac{1}{n} \)the same line: the exact average \( \hat{Q}_n = (1 - \eta)^n\, \hat{Q}_0 + \eta \sum_{i=1}^{n} (1 - \eta)^{n-i}\, u_i \)a constant \(\eta\): recent trips weigh more, old ones fade \( \dfrac{d}{d\hat{Q}}\; \tfrac{1}{2} \left( \hat{Q} - u \right)^2 = \hat{Q} - u \)so the update is a step of gradient descent on the squared error

A constant \(\eta\) forgets. That is what we want once the policy, and so the target, keeps changing.

SARSA: Using the Reward + Q-valueMonte Carlo waits for the end of the trip. Can the robot learn after one step?

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] \)

Why SARSA's target is right on averageThe utility of a trip is one reward plus the utility of the rest of it

\( u = R(s) + \gamma\, u' \)\(u'\): the utility of the same trip, counted from \((s', a')\) on \( \mathbb{E}\left[\, u' \mid s', a' \,\right] = Q^\pi(s', a') \)the definition of \(Q^\pi\), one step later \( Q^\pi(s, a) = \mathbb{E}\left[\, R(s) + \gamma\, Q^\pi(s', a') \,\right] \)the Bellman equation for \(Q^\pi\): the average is over \(s'\), with \(a' = \pi(s')\) \( \text{target} = R(s) + \gamma\, \hat{Q}^\pi(s', a') \)SARSA: one sampled \(s'\), and the table in place of \(Q^\pi\)
Monte Carlo: \(u\)SARSA: \(R(s) + \gamma \hat{Q}^\pi(s', a')\)
right on averagefrom the first triponly once \(\hat{Q}^\pi\) is right
noisehigh: every step of the trip is randomlow: one random step
readyat the end of the tripafter one step

Q-LearningThe same update. The target takes the best next action, not the one the robot takes

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] \)

Why the maxQ-learning is the Bellman optimality equation, sampled one step at a time

\( Q^\star(s, a) = R(s) + \gamma \sum_{s'} P(s' \mid s, a)\, \max_{a'} Q^\star(s', a') \)Bellman optimality, written for \(Q\) \( \text{target} = R(s) + \gamma \max_{a'} \hat{Q}^\star(s', a') \)one sampled \(s'\) in place of the sum over \(P\) \( \pi^\star(s) = \arg\max_{a} Q^\star(s, a) \)with \(Q^\star\), choosing the best action needs no \(P\)
  • On-policy (SARSA): learns the value of the way the robot acts, its random moves included.
  • Off-policy (Q-learning): learns about \(\pi^\star\) from any trips that keep trying every \((s, a)\).

One update, three targetsEach of them moves the prediction a fraction \(\eta\) of the way to a target

\( \textcolor{#61afef}{\hat{Q}(s, a)} \leftarrow (1 - \eta)\, \textcolor{#61afef}{\hat{Q}(s, a)} + \eta \cdot \text{target} \)
targetit 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

Explore or exploit?The robot learns only about the moves it tries

\( a = \begin{cases} \text{a random action} & \text{with probability } \epsilon \\ \arg\max_{a} \hat{Q}(s, a) & \text{otherwise} \end{cases} \)
  • \(\epsilon = 0\): the robot always takes the move it currently thinks best, and may never find out that another is better.
  • \(\epsilon\) large: it keeps finding things out, but keeps paying for random moves while it does.
  • \(\eta\): how far one surprise moves the estimate. Too small learns slowly; too large forgets.

Q-learning on the gridSet epsilon and eta, then let the robot make trips of 40 steps

the best action so farthe last trip

Q-learning in Python · explore or exploitRun the value iteration blocks first: this uses their world

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
explore, with probability \(\epsilon\)next(r) < eps otherwise the best \(\hat{Q}\)best[0]

lcg is the deck's random numbers, so your run matches the widget's.

Q-learning in Python · one moveThe robot never reads \(P\). It only finds out where the move took it

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.

Q-learning in Python · one updateThe target is the reward plus the best next Q

\( \hat{Q}(s, a) \leftarrow (1 - \eta)\, \hat{Q}(s, a) + \eta\, \textcolor{#e5c07b}{\left[ R(s) + \gamma \max_{a'} \hat{Q}(s', a') \right]} \)
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
the targetR.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])\).

Q-learning in Python · one tripForty steps from (1,1): act, look, update

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.

Q-learning in Python · 100 trips\(\epsilon = 0.1\), \(\eta = 0.5\), seed 1: the widget's first run

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.

Q-learning in Python · what it learnedThe largest Q in every cell, and the action that has it

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.

The Q-learning leagueEach team picks one epsilon and one eta. The same 10 worlds for everyone

team \(\epsilon\) \(\eta\) seed

Score: the mean return of the 100 trips, averaged over 10 worlds.

#team\(\epsilon\)\(\eta\)scoregreedy \(V^\pi(1,1)\)

The league · what the grid saysEvery slider setting, seed 1, scored the same way

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

Too big for a table

What if there are too many states to list, and can we learn the policy directly?

Q-Learning with function approximationA table learns every \((s, a)\) on its own. Let similar pairs share what they learn

\( \textcolor{#61afef}{\hat{Q}^\star(s, a; \mathbf{w})} = \mathbf{w} \cdot \phi(s, a) \)

\(\phi(s, a)\): features of the pair, chosen by us. \(\mathbf{w}\): the weights to learn, in place of the table.

\( \min_{\mathbf{w}} \;\tfrac{1}{2} \Big( \textcolor{#61afef}{\hat{Q}^\star(s, a; \mathbf{w})} - \textcolor{#f2c94c}{\big( R(s) + \gamma \hat{V}^\star(s') \big)} \Big)^2 \)

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.

Continuous Markov Decision Processes (MDP)States and actions are continuous: \(s \in \mathbb{R}\), \(a \in \mathbb{R}\)

  • State \(s\) is the angle of the pole
  • Action \(a\) is the velocity of the cart

Downsides of discretization:

  • Step-wise fit to a continuous problem
  • Curse of dimensionality
\( S \in \mathbb{R}^d \xrightarrow{\text{ discretize each dim. into } k \text{ values }} k^d \text{ states} \)

A cart-pole has \(d = 4\) numbers: \(k = 10\) gives 10,000 states, \(k = 100\) gives 100,000,000.

Value Function ApproximationGiven a physical model \(\dfrac{ds}{dt} = f(s)\), a simulator gives the next state

\(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.

Value Function ApproximationNo physical model? Learn one from the trials

Learn a state-space model

\( s_{t+1} = A s_t + B a_t \)

with \(A\) and \(B\) as fitting parameters (least squares on the pairs \((s_t, a_t) \mapsto s_{t+1}\)).

Fitting Value IterationThe Bellman update with an integral over continuous next states

$$\begin{aligned} V(s) &:= R(s) + \gamma \max_a \int_{s'} P(s' \mid s, a)\, V(s')\, ds' \\ &= R(s) + \gamma \max_a \mathbb{E}_{s' \sim P(\,\cdot \mid s, a)}\left[ V(s') \right] \end{aligned}$$

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).

Deep Reinforcement LearningPolicy gradient: train a policy \(\pi_\theta(a \mid s)\) directly, with no value table

\( J(\theta) = \mathbb{E}_{\pi_\theta}\left[ R(s_0) + \gamma R(s_1) + \ldots \right] \)
\( \nabla_\theta J(\theta) = \mathbb{E}_{\pi_\theta}\left[ \textstyle\sum_t u_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) \right] \)

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.

A policy gradient at a forkLeft always pays 1. Right pays 5 three times in ten. Train the policy and watch \(\pi_\theta(\text{right})\)

\( \pi_\theta(\text{right}) = \dfrac{1}{1 + e^{-\theta}} \)

A policy gradient on the gridOne softmax per cell, \(\pi_\theta(a \mid s) \propto e^{\theta_{s,a}}\). Train for 1,000 trips

No value function, no \(\max\): "do more of what was followed by more reward".

Part 6 of 6

Where it breaks

What happens when the reward is not what we meant?

A reward the robot gamesChange one rule: home pays +20 once and the trip ends there

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.

A reward the robot games · learned from tripsQ-learning finds the loophole too, without a map

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.

Specification gaming in the wildA boat race whose points come from targets, not from finishing

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).

When nobody can write the reward"A helpful answer" has no formula. But people can say which of two answers is better

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:

\( P(y_A \succ y_B) = \sigma\big( r_\phi(x, y_A) - r_\phi(x, y_B) \big) \)

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.

RL from human feedbackHow a language model is tuned into an assistant (Ouyang et al., 2022)

\( \max_\theta \; \mathbb{E}_{x,\; y \sim \pi_\theta}\left[ r_\phi(x, y) \right] - \beta\, \mathrm{KL}\left( \pi_\theta \,\|\, \pi_{\text{ref}} \right) \)

Step 3 is a policy gradient, like the fork. The KL term keeps the model close to where it started.

The reward model can be gamed tooThe battery again, with a learned reward

  • Optimize hard against \(r_\phi\) and its score keeps rising while people's real preference first rises, then falls (Gao et al., 2022).
  • Typical loopholes: longer answers, confident tone, agreeing with the user. Each pays under \(r_\phi\), like the battery under our reward.
  • The defences are the ones you have seen: a penalty for moving far (the KL term), more and better comparisons, and checking behaviour, not just the score.

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.

Open source modelsEnvironments to try all of this on

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

gymnasium.farama.org

A real pendulum, learnedThe cart-pole of part 4, on a real cart

Takeaways

  • Without a map, the robot learns from its own trips: count to build P, or update Q directly with one sampled step (SARSA, Q-learning).
  • Learning needs exploration. In the league, never exploring scored 22.2 at best and the best setting 61.6.
  • When states are too many to list, a function stands in for the table; a policy gradient trains the policy itself.
  • An agent optimizes the reward we wrote, not the one we meant: with home paying once the robot parks on the battery. RLHF learns the reward from people, and can be gamed the same way.