← MAIN
LAB // PLANNING AND LEARNING

GRIDWORLD MDP

Moves slip, rewards pay and pits cost. Two solvers plan from the model; one learns by walking the grid.
VI SWEEPS 0 PI ROUNDS 0 Q EPISODES 0 Q MATCHES OPTIMAL —

HOW TO USE

The goal is to find the policy that earns the most reward over time. Every move can slip sideways, so the best move depends on the whole grid.

Pick a PRESET, or paint your own world with the tools. Any change restarts all three solvers.

Value iteration and policy iteration use the model. Q-learning walks the grid and learns only from what it sees; press RUN and watch it improve.

THE WORLD
Paint with the selected tool. Any change restarts all three solvers.

World: —
Colour is the value: pink below zero, cyan above, brighter with magnitude. Arrows show the chosen action; triangles show Q for up, right, down and left; the orb is the agent.
VALUE ITERATIONRUNNING
BELLMAN RESIDUAL, LOG SCALE
POLICY ITERATIONEVALUATING
EVALUATION RESIDUAL, LOG SCALE. TICKS MARK IMPROVEMENTS
Q-LEARNING AGENTPAUSED
EPISODE RETURN (LINE: 50-EPISODE AVERAGE)
SHARE OF REACHABLE CELLS WITH THE OPTIMAL ACTION
THE MODEL
DISCOUNT γ
WIND: SLIP CHANCE
LIVING REWARD
More settings
REWARD +
PIT −
SEED
CONVERGENCE THRESHOLD ε
THE AGENT
STEP SIZE α
EXPLORATION ε
DECAY PER EPISODE
SPEED
Sweeps per frame for the planners; episodes per second for the agent (thousands at TURBO).

HOW IT WORKS

The grid is a Markov decision process (MDP): a set of cells, four moves, a chance that each move slips sideways, and a reward on each step. Two solvers compute the best behaviour from the full model, and Q-learning finds it from experience alone. All three run in JavaScript1, and the Python package python -m mdplab reproduces the same numbers for the same seed2.

The MDP

An MDP is a tuple (S, A, P, R, \gamma). The states S are the cells the agent can stand on. The actions A are up, right, down and left. A wall is not a state. A reward cell (+) and a pit (−) are terminal: entering one ends the episode. A cliff (C) is not a state either. Entering it pays the cliff value and sends the agent back to the start34.

54
P(s' \mid s, a) = \begin{cases} 1 - p & s' = \text{move}(s, a) \\ p/2 & s' = \text{move}(s, a \pm 1) \end{cases}, \qquad R(s, a, s') = r_{\text{living}} + r_{\text{entered}}(s')

Here p is the slip chance, the directions a \pm 1 are the two sideways moves (left and right of the intended one), and \text{move}(s, d) is the cell reached by moving in direction d. If that move would leave the grid or enter a wall, the result is s itself. r_{\text{living}} is the living reward paid on every step, and r_{\text{entered}}(s') is the payout of the cell entered, which is 0 on empty cells. Outcomes with probability 0 are dropped.

Bellman equations

The value V(s) is the expected discounted return from s under the best behaviour, and Q(s, a) is the value of taking action a first and acting best afterwards. The discount \gamma weights a reward one step later by \gamma, and two steps later by \gamma^2. The Bellman optimality equations relate the two. A terminal cell has value 0, because nothing follows it6.

78
Q(s, a) = \sum_{s'} P(s' \mid s, a)\,\bigl[R(s, a, s') + \gamma\, V(s')\bigr], \qquad V(s) = \max_{a} Q(s, a)

Here \sum_{s'} runs over the outcomes of the action, and V(s') is taken as 0 when s' is terminal. The greedy policy takes the action with the highest Q in each state. When two actions are within 10^{-9} of each other, the lower-index action is taken, so rounding noise cannot change the policy9. Because the optimal values are the unique solution of these equations, the greedy policy from them is optimal.

Value iteration

Value iteration starts with every value at 0 and repeats the Bellman update over every state. One sweep computes every new value from the old ones, so the update is synchronous. The Bellman residual is the largest change in any value during the sweep. The loop stops when it falls below the threshold \varepsilon10.

11
V_{k+1}(s) = \max_{a} Q_k(s, a), \qquad \delta_k = \max_{s} \bigl|V_{k+1}(s) - V_k(s)\bigr|, \qquad \text{stop when } \delta_k < \varepsilon

Here Q_k is computed from V_k with the formula above. The update is a contraction: each sweep shrinks the distance to the optimal values by at least a factor of \gamma. So when the residual is below \varepsilon, the values are within about \varepsilon\gamma / (1 - \gamma) of the optimum. At the defaults (\gamma = 0.95, \varepsilon = 10^{-4}) that bound is about 0.002.

1213
function VALUE-ITERATION(mdp, ε):
    V(s) ← 0 for every state s
    while true:
        new ← the best Q(s, a) over the actions, from the current V, for each state s
        residual ← the largest change |new(s) − V(s)| over all states
        V ← new
        if residual < ε: stop
    return the greedy policy of V

Ideas in the full version. Each sweep reads the old values and writes new ones, so the order of the states does not matter. Terminal cells keep value 0 because they are not states. The residual is the quantity the stopping rule and the chart use. The final policy is read off the converged values, with the same tie rule as every other greedy choice.

Policy iteration

Policy iteration alternates two phases. Evaluation computes the values V^\pi of the current policy \pi, by sweeps of the Bellman update with the action fixed to \pi(s). Improvement sets each state's action to the best one under V^\pi. A state keeps its current action unless another action is better by more than 10^{-9}14.

1516
V^\pi(s) \leftarrow \sum_{s'} P(s' \mid s, \pi(s))\,\bigl[R(s, \pi(s), s') + \gamma\, V^\pi(s')\bigr], \qquad \pi(s) \leftarrow \arg\max_{a}\, Q^\pi(s, a) \ \text{unless } Q^\pi(s, \pi(s)) \ge \max_a Q^\pi(s, a) - 10^{-9}

Here Q^\pi(s, a) is the one-step look-ahead of the formula in the Bellman section, computed from V^\pi. Evaluation stops when its residual is below the threshold \varepsilon, and the page caps it at 5000 sweeps per round. The policy only improves from round to round, and a round with no changes means the policy is optimal, so the loop stops. Each round starts from the values of the previous one, so the evaluation is warm-started.

1417
function POLICY-ITERATION(mdp, ε):
    π ← a seeded random action for every state;  V ← 0
    while the policy is not stable:
        evaluate π: sweep the Bellman update with action π(s) until the residual is below ε
        improve: for each state s, switch π(s) to the best action unless the current one is tied
        stable ← no action changed
    return π, V

Ideas in the full version. The random starting policy comes from the seed, so the same seed replays the same run. The keep-the-current-action rule means a round changes a state only when there is a real improvement, which is what makes the loop stop. The evaluation is an ordinary sweep, so it converges at the rate the discount sets. The number of rounds and evaluation sweeps are the two counts the page shows.

Q-learning and SARSA

Q-learning learns the table Q(s, a) from single steps, without the model. After each step from s with action a, which lands on s' with reward r, the entry moves toward a target. The target uses the best next action, which makes Q-learning off-policy: it learns the greedy policy whatever the agent actually does. SARSA uses the action it will actually take next, which makes it on-policy18.

19
Q(s, a) \leftarrow Q(s, a) + \alpha\,\bigl(\text{target} - Q(s, a)\bigr), \qquad \text{target} = \begin{cases} r & s' \text{ terminal} \\ r + \gamma \max_{a'} Q(s', a') & \text{Q-learning} \\ r + \gamma\, Q(s', a') & \text{SARSA, with } a' \text{ the action taken} \end{cases}

Here \alpha is the step size, r is the living reward plus the payout entered, and \gamma is the discount. The agent chooses actions epsilon-greedily: with probability \epsilon it takes a random action, and otherwise the action with the highest Q, breaking ties at random20. After each episode, \epsilon \leftarrow \max(\epsilon_{\min}, \epsilon \cdot \text{decay})21. A slip is drawn from the same random stream, so the walks depend on the seed only.

1822
function Q-EPISODE(mdp, Q, algorithm, ε):
    s ← start;  a ← CHOOSE(s)
    loop:
        s' ← the cell reached when a slips
        r ← living reward + payout of the cell entered
        if s' is terminal: target ← r
        else if Q-learning: target ← r + γ · max over a′ of Q(s', a′)
        else: a' ← CHOOSE(s');  target ← r + γ · Q(s', a')          # SARSA
        Q(s, a) ← Q(s, a) + α · (target − Q(s, a))
        if s' is terminal or the step limit is reached: stop
        s ← s';  a ← the next action
    ε ← max(ε_min, ε · decay)

Ideas in the full version. The random draws happen in a fixed order: the exploration test and index, then the slip draw, then the tie-break index. Fixing that order is what lets the browser and the Python package produce identical walks. The step limit ends an episode that never reaches a terminal cell, and that episode is not counted as falling. In SARSA the next action is chosen before the update, because its value is part of the target, and the same action is then taken on the next step.

Example. On the cliff walk with the textbook settings (α = 0.5, ε = 0.1 held constant, γ = 0.99, seed 1), 500 episodes of Q-learning leave a greedy route of 13 steps along the row beside the cliff. That route is optimal. After the same 500 episodes, SARSA's greedy route takes 17 steps and runs two rows further from the cliff. The test suite checks the same contrast in online return, where SARSA earns more during learning23.

Parameters and their values

ParameterDefaultWhy this value
Discount γ24250.95 (cliff: 0.99)Looks about 20 steps ahead (1 / (1 − γ)), so a goal in a far corner still matters. The cliff uses 0.99 rather than 1: with γ = 1, a policy that never reaches the goal has no finite value, so the convergence argument fails.
Slip p250.1 (windy: 0.3; cliff: 0)Enough that the agent must plan around the pits, not walk straight through them. The slider stops at 0.5, where the intended move is still more likely than either slip.
Living reward26−0.04 (cliff: −1)A small cost per step, so the agent prefers a shorter route to the same goal. The cliff uses the textbook −1.
Reward + and pit −2625+1 and −1 (cliff: goal 0, fall −100)The goal is worth more than the cost of walking to it, and a pit is as bad as a goal is good. On the cliff, the goal pays 0 and falling pays the textbook −100.
Step size α250.1 (cliff: 0.5)Slips make each step's target noisy, so a small step averages over many walks. The cliff has no slip, so it uses the textbook 0.5.
Exploration ε270.1, decaying to 0.01 (cliff: 0.1, constant)Enough random moves to find the far goal and the pits. The cliff keeps ε = 0.1 constant, so SARSA's cautious route is a consequence of exploration.
Decay per episode270.999 (cliff: 1, constant)Explore early and exploit later: from 0.1 at 0.999, the rate reaches its floor of 0.01 after about 2300 episodes.
Convergence ε (planners)281e−4 (choose 1e−2 to 1e−6)Stop when no value changes by more than this threshold. The values are then within about ε · γ / (1 − γ) of the optimum (about 0.002 at γ = 0.95, ε = 1e−4).
Tie tolerance91e−9Two actions within 1e−9 count as tied, so rounding noise cannot flip a policy. The Python and JavaScript versions use the same value.29
Random seed301Fixes the random starting policy and every episode. The same seed gives the same walks in the browser and in python -m mdplab.

How these were chosen: The layouts, rewards and slip values were set by hand so each lesson shows one thing: a shortcut through a pit, a corridor where the wind matters, a cliff with a textbook penalty. The discount, step size and exploration schedule are standard starting points, not tuned against a benchmark. The cliff's settings follow the cliff-walking example in Sutton and Barto. No parameter sweep is committed.