Reinforcement learning2 / 5

Lesson 2 · The problem

Markov decision processes

The problem

Remember the customer from the Markov chains lesson. Each week she orders pizza from shop A, B or C. Next week's shop is random, with chances that depend only on this week's shop:

Tno coupon=[0.80.10.10.20.70.10.10.30.6]←from A←from B←from CT_{\text{no coupon}} = \begin{bmatrix} 0.8 & 0.1 & 0.1 \\ 0.2 & 0.7 & 0.1 \\ 0.1 & 0.3 & 0.6 \end{bmatrix} \qquad \begin{aligned} &\leftarrow \text{from A} \\ &\leftarrow \text{from B} \\ &\leftarrow \text{from C} \end{aligned}

Now you run shop A. You earn 1 for every week she orders from you. Each week you see where she ordered, and you can mail her a coupon. A coupon costs 0.5, and it makes her more likely to order from A next week:

Tcoupon=[0.90.050.050.50.40.10.40.30.3]T_{\text{coupon}} = \begin{bmatrix} 0.9 & 0.05 & 0.05 \\ 0.5 & 0.4 & 0.1 \\ 0.4 & 0.3 & 0.3 \end{bmatrix}

So who gets a coupon? A coupon to a customer at A is mostly wasted, since she stays with chance 0.8 anyway. A coupon to a customer at C triples her chance of coming to A, from 0.1 to 0.4. But each one costs half a pizza's profit.

In the Markov chains lesson, you could only watch the chain. Now you can steer it. That's the step from a Markov chain to a Markov decision process, the model under all of reinforcement learning.

A Markov chain you can steer

Each week, you pick an action in each state, and the action decides which row of transition chances applies. Pick a coupon for a shop below. That shop's row switches from the "no coupon" matrix to the "coupon" matrix. The circles show where the chain settles in the long run: its stationary distribution.

A0.45B0.35C0.200.80.10.10.20.70.10.10.30.6
this week ↓ next →ABCreward
A 0.80.10.10.80
B 0.20.70.10.20
C 0.10.30.60.10

Long run: A 0.45, B 0.35, C 0.20

Average reward per week in the long run: 0.450

The coupon MDP. Each shop's button picks that shop's action, and the action picks the shop's row of the transition matrix. Once every shop has an action, it's an ordinary Markov chain with its own long-run chances.

Things to notice:

  • With no coupons, you get the chain from the Markov chains lesson. She spends 45% of her weeks at A.
  • A coupon only changes its own shop's row. The other rows stay the same.
  • Coupons at B and C push the long-run share at A up to about 70%.

The parts of an MDP

A Markov decision process (MDP) is a Markov chain in which an agent picks an action at every step. The action changes the transition chances, and each step earns a reward. It has five parts:

PartSymbolCoupon MDP
statesS\mathcal{S}A, B, C: where she ordered this week
actionsA\mathcal{A}no coupon, coupon
transition chancesT(s,a,s′)T(s, a, s')the two matrices above
rewardsr(s,a,s′)r(s, a, s')+1 if she orders from A next week, −0.5 for a coupon
discount factorγ\gamma0.9 (next lesson)

The transition function T(s,a,s′)T(s, a, s') is the chance of landing in state s′s' after taking action aa in state ss. For example, T(B,coupon,A)=0.5T(\text{B}, \text{coupon}, \text{A}) = 0.5: row B of the coupon matrix, column A. For every ss and aa, the chances over s′s' add up to 1, so each T(s,a,⋅)T(s, a, \cdot) is a distribution.

The reward function r(s,a,s′)r(s, a, s') is the reward for moving from ss to s′s' with action aa. Here, moving to A earns 1, and a coupon costs 0.5:

r(s,a,s′)=[ s′=A ]⏟1 if she comes to A  −  0.5 [ a=coupon ]⏟the coupon’s costr(s, a, s') = \underbrace{[\,s' = \text{A}\,]}_{1 \text{ if she comes to A}} \; - \; \underbrace{0.5\,[\,a = \text{coupon}\,]}_{\text{the coupon's cost}}

The square brackets mean "1 if this is true, else 0". In some MDPs the reward is itself random. Then r(s,a,s′)r(s, a, s') is its average.

The discount factor γ\gamma says how much future rewards count. It's the subject of the next lesson.

What a step earns on average

Before you take a step, you know the action but not the next state. So the reward you can expect is an average over where you might land, weighted by TT: an expectation.

Worked example

Expected reward this week, for a customer at B

  1. No coupon: she moves to A with chance 0.2 and earns 1, else 0. Expected reward 0.2×1=0.20.2 \times 1 = 0.2.

In symbols, the expected reward for action aa in state ss is

r(s,a)=∑s′T(s,a,s′) r(s,a,s′)r(s, a) = \sum_{s'} T(s, a, s')\, r(s, a, s')

Read it as: for each place you might land, multiply its chance by what landing there earns, then add.

Yet the figure says coupons at B pay off in the long run. A coupon this week moves her to A, and at A she tends to stay for weeks. The reward for one step misses that. Adding up rewards over many steps, so that a move is judged by everything that follows, is the job of the next few lessons.

Only now matters, again

An MDP keeps the Markov property. The next state depends only on the current state and the action, not on anything earlier:

P(St+1=s′∣St=s, At=a, all earlier states and actions)=T(s,a,s′)P(S_{t+1} = s' \mid S_t = s,\ A_t = a,\ \text{all earlier states and actions}) = T(s, a, s')

The rules also stay the same week after week. A coupon to C works the same in week 1 as in week 50. Rules that never change over time are called stationarity. Every MDP in this course is stationary.

DigressionIf history matters, put it in the stateA model where the past matters can still be an MDP, with a bigger state. · 2 min

Say coupons wear thin: a second coupon in a row works less well than the first. Then the next week depends on last week's action too, and "this week's shop" isn't enough to predict it.

The fix is the one from the Markov chains lesson. Make the state "(this week's shop, did she get a coupon last week?)". That's 6 states instead of 3. With this state, the next week depends only on the current state and action again, so it's an MDP.

The cost is size. Each piece of history you add multiplies the number of states. Large problems keep the state small by keeping only what matters for what happens next. When the agent can't see everything that matters, the POMDPs lesson takes over.

Policies

A rule that says which action to take in each state is a policy, written π\pi. The figure's buttons set one. "Coupon at B and C, none at A" is the policy

π(A)=no coupon,π(B)=coupon,π(C)=coupon.\pi(\text{A}) = \text{no coupon}, \qquad \pi(\text{B}) = \text{coupon}, \qquad \pi(\text{C}) = \text{coupon}.

Fix a policy and the agent has no choices left. Each state's row is set, so the MDP becomes an ordinary Markov chain, with a transition matrix TπT^\pi. For this policy, rows B and C come from the coupon matrix:

Tπ=[0.80.10.10.50.40.10.40.30.3]←A: no coupon←B: coupon←C: couponT^\pi = \begin{bmatrix} 0.8 & 0.1 & 0.1 \\ 0.5 & 0.4 & 0.1 \\ 0.4 & 0.3 & 0.3 \end{bmatrix} \qquad \begin{aligned} &\leftarrow \text{A: no coupon} \\ &\leftarrow \text{B: coupon} \\ &\leftarrow \text{C: coupon} \end{aligned}

Its stationary distribution is about (0.696,0.179,0.125)(0.696, 0.179, 0.125). Everything from the Markov chains lesson now applies to it.

One simple way to score a policy is its average reward per week in the long run. Weight each shop's expected reward by the share of weeks she spends there.

Worked example

Long-run reward per week

  1. Never send a coupon. The expected rewards are 0.8 at A, 0.2 at B and 0.1 at C. The long-run shares are (0.45,0.35,0.20)(0.45, 0.35, 0.20).

Predict first

Never sending a coupon earns 0.45 a week in the long run. What about sending a coupon every week, whatever the shop?

Long-run average reward is one way to compare policies. The next lesson brings in the standard way, the discounted return, which also counts how soon rewards arrive.

Policies that flip coins

A policy can also choose at random. Say that at B you send a coupon half the time. A policy that picks actions with set chances is a stochastic policy. We write π(a∣s)\pi(a \mid s) for the chance of action aa in state ss. So π(coupon∣B)=0.5\pi(\text{coupon} \mid \text{B}) = 0.5.

The chain is still a Markov chain. Each row is now a blend of the two matrices' rows:

Tπ(s,s′)=∑aπ(a∣s) T(s,a,s′)T^\pi(s, s') = \sum_{a} \pi(a \mid s)\, T(s, a, s')

For B: 0.5×(0.2,0.7,0.1)+0.5×(0.5,0.4,0.1)=(0.35,0.55,0.1)0.5 \times (0.2, 0.7, 0.1) + 0.5 \times (0.5, 0.4, 0.1) = (0.35, 0.55, 0.1). A policy that always picks the same action is the special case where one action has chance 1.

The slippery grid

Back to the robot from the first lesson. It's on the 4×3 grid, but now its wheels slip. Each move goes the intended way with chance 0.8. With chance 0.1 it slides 90° to the left of that direction, and with chance 0.1 to the right. A slide into a wall or off the edge leaves it where it is.

So the grid is an MDP too:

  • The states are the 11 cells. Two of them, the goal (4,3) and the pit (4,2), are terminal.
  • The actions are N, E, S and W.
  • TT holds the 80/10/10 chances, worked out for every cell and action.
  • The reward is +1 for entering the goal, −1 for entering the pit, and 0 for any other move.

Predict first

The robot is at (3,2), right next to the pit. It tries to move N, away from it. What's the chance it falls in the pit?

Pick a cell and an action. The shaded cells are where the robot can end up, with their chances. The slider sets the chance of sliding to each side. At 0 the grid is the one from the first lesson.

From (1,1)

From (1,1), try N:

(1,2) 0.80 · stay at (1,1) 0.10 · (2,1) 0.10

Intended 0.80, each side 0.10. Bumping a wall or the edge means staying put.

One action, up to three results. The arrow is the move the robot tries; shading shows where it can land. Sliding into a wall or the edge means staying put, so a cell can get chance from two directions.

Things to notice:

  • From (1,1), N lands on (1,2) with chance 0.8, on (2,1) with 0.1, and stays at (1,1) with 0.1 (sliding W off the edge).
  • From (1,3), N bumps the top edge, and a slide W hits the left edge. So it stays put with chance 0.8+0.1=0.90.8 + 0.1 = 0.9. Only a slide E moves it, to (2,3).
  • Each action's chances still add up to 1, whatever the slider says.

Plans and policies

With no slip, the robot could follow a fixed list of moves: N, N, E, E, E. A fixed sequence of actions chosen in advance is a plan. On the slippery grid, a plan has a problem. After one slide, the robot is somewhere the plan didn't expect, and the rest of the plan is wrong for it.

Predict first

Each move goes as intended with chance 0.8, independently. What's the chance that all five moves of the plan N, N, E, E, E go as intended?

The exact chance that the plan ends at the goal is a hair higher: 0.32776. There's one lucky detour. The robot slides right on both N moves (to (2,1), then (3,1)), then slides up on the first two E moves (to (3,2), then (3,3)). The last E then enters the goal. That route has chance 0.14×0.8=0.000080.1^4 \times 0.8 = 0.00008.

A policy doesn't have this problem. It says what to do in every cell, so after a slide it picks a move that suits the cell it's in. Below, the plan and a policy each run 1,000 times. The policy's arrows come from value iteration, a few lessons on. For now, read them as sensible moves.

Tap a cell to inspect it.

Plan: N, N, E, E, E

goal318
pit14
neither668

exact chance of the goal: 0.328 · moves used: 5.0 on average

Tap a cell to inspect it.

Policy: a move for every cell

goal978
pit22
neither0

exact chance of the goal: 0.986 · moves used: 6.6 on average

Chance all five planned moves go as intended: 0.80⁵ = 0.328

The five-move plan against a policy, 1,000 runs each. The grids show one run of each. The plan ends at the goal about a third of the time. The policy keeps going until it gets there, and almost always does.

Things to notice:

  • With slip 0.1 per side, the plan reaches the goal about 330 times in 1,000. The policy reaches it about 980 times, in about 7 moves on average. The exact chances are 0.328 and 0.986.
  • At (3,2), the policy goes N, away from the pit. At (4,1), it goes W rather than N. N would enter the pit with chance 0.8. W slides into the pit with chance only 0.1.
  • Turn the slider up to 0.2 per side. The plan's success drops to about 0.08. The policy plays safe and never enters the pit, at the cost of extra moves: about 12 on average.

This is why reinforcement learning looks for policies, not plans. In a world where moves can go wrong, you need a decision for every state you might end up in.

DeeperRewards on states or on transitionsSome books give a reward for being in a state, R(s). That's a special case of r(s, a, s'). · 3 min

This course puts rewards on transitions: r(s,a,s′)r(s, a, s'), earned when you move from ss to s′s' with action aa. Most RL code and Sutton and Barto's textbook do the same.

Many older notes put the reward on states: R(s)R(s), earned for being in state ss. On the grid, R(goal)=+1R(\text{goal}) = +1, R(pit)=−1R(\text{pit}) = -1 and R(s)=0R(s) = 0 elsewhere. The value of a sequence of states is then

U=R(s0)+γR(s1)+γ2R(s2)+…U = R(s_0) + \gamma R(s_1) + \gamma^2 R(s_2) + \dots

A state reward is a transition reward that only looks at where you land. Set

r(s,a,s′)=R(s′)r(s, a, s') = R(s')

and each step's reward Rt+1R_{t+1} becomes R(St+1)R(S_{t+1}). The sequence of rewards is the same. The only difference is the start state's own reward, R(s0)R(s_0), which the transition version never pays. It's a fixed number for a given start, so it can't change which actions are best:

U=R(s0)+γ (R1+γR2+…)U = R(s_0) + \gamma\,\big(R_1 + \gamma R_2 + \dots\big)

Going the other way doesn't always work. The coupon's cost depends on the action, not on any state, so R(s)R(s) can't express it. You'd have to grow the state to remember the last action. Transition rewards say it directly, which is why this course uses them.

In PyTorch

An MDP with a few states is a few tables of numbers, so it fits in tensors. The coupon MDP's transition chances become one tensor of shape (S,A,S′)=(3,2,3)(S, A, S') = (3, 2, 3): state, action, next state.

The coupon MDP as tensors
coupon = E.coupon_mdp()
T = torch.tensor(coupon.T, dtype=F64)  # (S, A, S') = (3, 2, 3): T[s, a, s'] = chance of s' after a in s
R = torch.tensor(coupon.R, dtype=F64)  # (3, 2, 3): reward for each transition
r = (T * R).sum(dim=-1)     # (3, 2): expected reward r(s, a)

no_coupon, with_coupon = T[:, 0], T[:, 1]  # the two (3, 3) transition matrices
assert torch.allclose(T.sum(dim=-1), torch.ones(3, 2, dtype=F64))  # every row is a distribution
  • T[s, a] is one row: the distribution over the next shop.
  • (T * R).sum(dim=-1) multiplies chances by rewards and adds over the next state: the expected reward r(s,a)r(s, a), shape (3,2)(3, 2).

A policy with one action per state picks one row per state. Indexing with two tensors does that in one go:

Fix a policy, get a Markov chain
def chain_under(policy: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """A deterministic policy (one action per state) picks one row per state: a Markov chain."""
    states = torch.arange(T.shape[0])
    T_pi = T[states, policy]  # (3, 3): row s is T[s, policy[s]]
    r_pi = r[states, policy]  # (3,): the expected reward in each state
    return T_pi, r_pi


def stationary(T_pi: torch.Tensor) -> torch.Tensor:
    """Solve d T = d with the chances adding to 1 (the Markov chains lesson's trick)."""
    n = T_pi.shape[0]
    A = (T_pi - torch.eye(n, dtype=F64)).T  # d (T - I) = 0, written as A d = 0
    A[-1] = 1.0                  # replace one equation with d_A + d_B + d_C = 1
    b = torch.zeros(n, dtype=F64)
    b[-1] = 1.0
    return torch.linalg.solve(A, b)

T[states, policy] pairs each state with its action, so row ss of the result is T[s, policy[s]]. Then stationary solves d Tπ=d\mathbf{d}\,T^\pi = \mathbf{d} with torch.linalg.solve, using the "replace one equation with the sum to 1" trick from the Markov chains lesson. It prints (0.45,0.35,0.20)(0.45, 0.35, 0.20) for "never coupon" and (0.6964,0.1786,0.125)(0.6964, 0.1786, 0.125) for "coupons at B and C".

To sample one step, draw the next state from the row with torch.multinomial, using a seeded torch.Generator so the draws repeat:

One sampled step
def sample_step(s: int, a: int, gen: torch.Generator) -> tuple[int, float]:
    """One step of the MDP: draw s' from row T[s, a], look up its reward."""
    s_next = int(torch.multinomial(T[s, a], num_samples=1, generator=gen))
    return s_next, float(R[s, a, s_next])

Common misconceptions

"A policy is a plan." A plan is a fixed list of moves. A policy gives a move for every state, so it can react when things go wrong. On the slippery grid the plan succeeds about a third of the time; the policy almost always does.

"The Markov property means actions don't matter." The next state depends on the current state and the action. What it doesn't depend on is anything before them.

"The coupon at B loses money, because its expected reward this week is 0 against 0.2." One week's reward misses where she goes next. A coupon moves her to A, where she tends to stay, and that pays in later weeks.

"Stochastic policies are for when you can't decide." A random policy is a well-defined rule: set chances for each action. Some later methods learn exactly such policies. In games, playing at random can even be the best strategy, as the Games course shows.

"An MDP needs a terminal state." The grid has two. The coupon MDP has none: she orders pizza every week, forever. Both are MDPs.

Recap

  • An MDP has states, actions, transition chances T(s,a,s′)T(s, a, s'), rewards r(s,a,s′)r(s, a, s') and a discount factor γ\gamma.
  • It's a Markov chain the agent can steer: in each state, the action picks which row of chances applies.
  • The next state depends only on the current state and action (Markov), and the rules don't change over time (stationary).
  • A policy π(a∣s)\pi(a \mid s) chooses actions in every state. Fixing one turns the MDP into an ordinary Markov chain, TπT^\pi.
  • A plan is a fixed list of moves. On a slippery grid it fails often, because it can't react. Policies can.
  • PyTorch names used: torch.tensor for the (S,A,S′)(S, A, S') table, indexing with tensors, .sum(dim=-1), torch.linalg.solve, torch.multinomial and torch.Generator.