> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# q-Value Iteration on the 4x3 Gridworld

> Value iteration that keeps the action values, on the 4x3 gridworld.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/mdp/dynamic-programming-algorithms/value-iteration/q-value-iteration/index.ipynb)

This section solves the 4x3 gridworld of [Introduction to MDP](https://aegean.ai/aiml-common/lectures/mdp/mdp-intro/index.md) with q-value iteration, which keeps an action value $q(s, a)$ for every state and action instead of one value $v(s)$ per state. [Value Iteration](https://aegean.ai/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/index.md) solves the same grid, so you can compare the two results directly.

## The 4x3 gridworld

The agent is in one of the 11 free cells $s_{xy}$, where $x = 1, \dots, 4$ counts columns from the left and $y = 1, 2, 3$ counts rows from the bottom. The cell $s_{22}$ is a wall. Entering the exit $s_{43}$ earns $+1$, and entering the exit $s_{42}$ earns $-1$. Reaching either exit ends the episode. Every other move earns $-0.04$.

The actions are the four moves north, east, south and west. A move into the wall or off the grid leaves the agent where it is. The reward depends only on the cell the agent enters, $r(s, a, s') = r(s')$, and the discount factor is $\gamma = 0.9$.

The problem is solved twice. First the moves are deterministic, so the agent always reaches the cell it moves toward. Then the moves are noisy, as in the gridworld of the other sections: the intended move happens with probability 0.8, and each move at a right angle to it with probability 0.1.

> [accordion] Code
>
> ```python theme={null}
> import numpy as np
> import matplotlib.pyplot as plt
> import matplotlib.patches as mpatches
> from cycler import cycler
> from matplotlib import colormaps
> from matplotlib_inline.backend_inline import set_matplotlib_formats
> set_matplotlib_formats("svg")
> FIG_GRAY = "#808080"
> FIG_COLORS = ["#0072B2", "#D55E00", "#009E73", "#cb77a6", "#c28600", "#1d99e0", "#7f7f7f"]
> plt.rcParams.update({
>     "figure.facecolor": "none", "axes.facecolor": "none",
>     "savefig.facecolor": "none", "savefig.transparent": True,
>     "text.color": FIG_GRAY, "axes.labelcolor": FIG_GRAY, "axes.edgecolor": FIG_GRAY,
>     "xtick.color": FIG_GRAY, "ytick.color": FIG_GRAY,
>     "grid.color": FIG_GRAY, "grid.alpha": 0.25,
>     "legend.facecolor": "none", "legend.edgecolor": FIG_GRAY, "legend.framealpha": 0,
>     "axes.prop_cycle": cycler(color=FIG_COLORS),
>     "svg.hashsalt": "aiml", "svg.fonttype": "path",
> })
> ```

![Output from cell 2](https://mintcdn.com/aegeanaiinc/HvSJ_rlBnWVzEbWb/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/q-value-iteration/images/cell_2_output_1.svg?fit=max\&auto=format\&n=HvSJ_rlBnWVzEbWb\&q=85\&s=ab8984489662152cac6d06096d4ac38a)

*The 4x3 gridworld. Entering the exit $s_{43}$ earns $+1$, entering the exit $s_{42}$ earns $-1$, and every other move earns $-0.04$.*

## q-value iteration

The optimal action-value function $q_*(s, a)$ is the return of taking action $a$ in state $s$ and acting optimally afterwards. It satisfies the Bellman optimality equation for action values,

$$
q_*(s, a) = \sum_{s'} p(s' \mid s, a) \bigl[ r(s, a, s') + \gamma \max_{a'} q_*(s', a') \bigr].
$$

q-value iteration turns this equation into an update. Start from $q_0 = 0$ and apply the right-hand side to every pair $(s, a)$, using the previous table $q_k$ inside the max, to get $q_{k+1}$. Stop when no entry changes by more than a small tolerance. Once $q_*$ is known, the optimal policy needs no model at all: in each state, pick the action with the largest $q_*(s, a)$.

This is value iteration with the action values kept. [Value Iteration](https://aegean.ai/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/index.md) stores one number per state, $v_k(s)$, and computes action values only briefly inside each backup. q-value iteration stores one number per state and action. The two produce the same sequence: with $v_k(s) = \max_a q_k(s, a)$, the update above is exactly the value iteration update. Keeping $q$ costs more memory, but it removes the model from policy extraction. From $v_*$ you need the model $p$ again to look one step ahead, while from $q_*$ you only take the argmax in each state. Q-learning estimates the same table from experience, without $p$; its capital $Q$ marks a learned estimate.

The code below builds the model as arrays. `P[s, a, s']` is the probability of moving from `s` to `s'` under action `a`, and `R[s, a, s']` is the reward of that transition. The update works for any model given in this form.

> [accordion] Code
>
> ```python theme={null}
> import numpy as np
>
> STATES = [(x, y) for y in (3, 2, 1) for x in (1, 2, 3, 4) if (x, y) != WALL]
> INDEX = {s: i for i, s in enumerate(STATES)}
> ACTIONS = ["N", "E", "S", "W"]
> MOVES = {"N": (0, 1), "E": (1, 0), "S": (0, -1), "W": (-1, 0)}
> RIGHT_ANGLES = {"N": ("E", "W"), "S": ("E", "W"), "E": ("N", "S"), "W": ("N", "S")}
> GAMMA = 0.9
>
>
> def name(s):
>     """Return the label s_xy of state s = (x, y)."""
>     return f"s{s[0]}{s[1]}"
>
>
> def move(s, direction):
>     """Return the cell reached by moving one cell from s.
>
>     Args:
>         s: current cell (x, y).
>         direction: one of "N", "E", "S", "W".
>
>     Returns:
>         The neighboring cell, or s itself when the move hits the wall or the grid edge.
>     """
>     x, y = s[0] + MOVES[direction][0], s[1] + MOVES[direction][1]
>     if (x, y) == WALL or not (1 <= x <= 4 and 1 <= y <= 3):
>         return s
>     return (x, y)
>
>
> def build_model(slip):
>     """Build the transition and reward arrays of the 4x3 gridworld.
>
>     Args:
>         slip: probability that a move goes at a right angle to the intended
>             direction, split equally between the two right angles. 0 gives
>             deterministic moves.
>
>     Returns:
>         P: array of shape (11, 4, 11); P[s, a, s'] is the probability of moving
>             from state s to state s' under action a (indices into STATES and ACTIONS).
>         R: array of the same shape; R[s, a, s'] is the reward of that transition.
>     """
>     n = len(STATES)
>     P = np.zeros((n, len(ACTIONS), n))
>     R = np.zeros((n, len(ACTIONS), n))
>     for s in STATES:
>         for a_idx, a in enumerate(ACTIONS):
>             if s in EXITS:                      # terminal: stay put, no further reward
>                 P[INDEX[s], a_idx, INDEX[s]] = 1.0
>                 continue
>             for direction, p in [(a, 1 - slip), (RIGHT_ANGLES[a][0], slip / 2), (RIGHT_ANGLES[a][1], slip / 2)]:
>                 if p == 0:
>                     continue
>                 s_next = move(s, direction)
>                 P[INDEX[s], a_idx, INDEX[s_next]] += p
>                 R[INDEX[s], a_idx, INDEX[s_next]] = EXITS.get(s_next, STEP_REWARD)
>     return P, R
>
>
> def q_value_iteration(P, R, gamma=GAMMA, tol=1e-4, max_sweeps=200):
>     """Run synchronous q-value iteration from q_0 = 0.
>
>     Args:
>         P: transition probabilities, P[s, a, s'].
>         R: transition rewards, R[s, a, s'].
>         gamma: discount factor.
>         tol: stop when no entry of q changes by more than tol in a sweep.
>         max_sweeps: upper limit on the number of sweeps.
>
>     Returns:
>         List of q tables q_0, q_1, ..., each of shape (number of states, number of actions).
>     """
>     q = np.zeros(P.shape[:2])
>     history = [q]
>     for _ in range(max_sweeps):
>         # q_{k+1}(s, a) = sum over s' of P(s' | s, a) * (r(s, a, s') + gamma * max_a' q_k(s', a'))
>         q_next = np.einsum("sat,sat->sa", P, R + gamma * q.max(axis=1)[None, None, :])
>         history.append(q_next)
>         if np.abs(q_next - q).max() < tol:
>             break
>         q = q_next
>     return history
>
>
> def greedy_policy(q):
>     """Return the greedy action of every nonterminal state, the first one on ties.
>
>     Args:
>         q: table of action values, shape (number of states, number of actions).
>
>     Returns:
>         Dict from state label s_xy to action.
>     """
>     return {name(s): ACTIONS[int(np.argmax(q[INDEX[s]]))] for s in STATES if s not in EXITS}
>
>
> def print_table(q):
>     """Print q(s, a) for every nonterminal state, one row per state."""
>     print("        " + "".join(f"{a:>8}" for a in ACTIONS))
>     for s in STATES:
>         if s not in EXITS:
>             print(f"{name(s):>6}  " + "".join(f"{v:+8.3f}" for v in q[INDEX[s]]))
> ```

## Deterministic moves

With deterministic moves, each action leads to exactly one next cell $s'$, so the sum in the update has a single term: $q_{k+1}(s, a) = r(s, a, s') + \gamma \max_{a'} q_k(s', a')$.

> [accordion] Code
>
> ```python theme={null}
> history_det = q_value_iteration(*build_model(slip=0.0))
> q_det = history_det[-1]
> print(f"converged after {len(history_det) - 1} sweeps")
> print_table(q_det)
> print("greedy policy:", greedy_policy(q_det))
> ```

```output theme={null}
converged after 7 sweeps
               N       E       S       W
   s13    +0.621  +0.734  +0.519  +0.621
   s23    +0.734  +0.860  +0.734  +0.621
   s33    +0.860  +1.000  +0.734  +0.734
   s12    +0.621  +0.519  +0.427  +0.519
   s32    +0.860  -1.000  +0.621  +0.734
   s11    +0.519  +0.519  +0.427  +0.427
   s21    +0.519  +0.621  +0.519  +0.427
   s31    +0.734  +0.519  +0.621  +0.519
   s41    -1.000  +0.519  +0.519  +0.621
greedy policy: {'s13': 'E', 's23': 'E', 's33': 'E', 's12': 'N', 's32': 'N', 's11': 'N', 's21': 'E', 's31': 'N', 's41': 'W'}
```

![Output from cell 5](https://mintcdn.com/aegeanaiinc/HvSJ_rlBnWVzEbWb/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/q-value-iteration/images/cell_5_output_1.svg?fit=max\&auto=format\&n=HvSJ_rlBnWVzEbWb\&q=85\&s=d8fa31986d66b7dde729533c68d64fb6)

*Each free cell holds the four values $q_*(s, a)$, with each triangle on the side of its move: north at the top, east at the right. The bold number is the greedy action.*

With deterministic moves, $q_*(s, a)$ depends only on how many moves the agent needs to reach the $+1$ exit when it takes $a$ first and then follows the shortest route. If that takes $n$ moves, the agent earns $-0.04$ on each of the first $n - 1$ moves and $+1$ on the last, so

$$
q_*(s, a) = -0.04\,(1 + \gamma + \dots + \gamma^{n-2}) + \gamma^{n-1}.
$$

For $n = 1, \dots, 6$ this gives 1, 0.860, 0.734, 0.621, 0.519 and 0.427. These are the only values in the table, apart from the $-1$ of moving into the $-1$ exit from $s_{32}$ or $s_{41}$. Moving east from $s_{33}$ reaches the $+1$ exit in one move. Moving south from $s_{11}$ bumps into the edge of the grid and leaves the agent in place, so it needs six moves.

Each sweep extends the horizon by one move: $q_k(s, a)$ is the best return of the first $k$ moves when the first one is $a$. The entry for a route of $n$ moves reaches its final value in sweep $n$. The longest route is the six moves that start by moving south from $s_{11}$, so sweep 6 is the last one that changes the table, and sweep 7 only confirms it. The greedy policy is final earlier, from sweep 4.

Some states have two best actions. From $s_{11}$, north and east both reach the $+1$ exit in five moves, one around each side of the wall, and both are worth 0.519. The printed policy lists north because it comes first.

## Noisy moves

Now each move reaches the intended cell with probability 0.8 and goes at a right angle to it with probability 0.1 each way. The update averages over the possible next cells.

> [accordion] Code
>
> ```python theme={null}
> history_noisy = q_value_iteration(*build_model(slip=0.2))
> q_noisy = history_noisy[-1]
> print(f"converged after {len(history_noisy) - 1} sweeps")
> print_table(q_noisy)
> print("greedy policy:", greedy_policy(q_noisy))
>
> policies = [greedy_policy(q) for q in history_noisy[1:]]
> final_from = next(k for k in range(1, len(policies) + 1) if all(p == policies[-1] for p in policies[k - 1:]))
> print(f"greedy policy is final from sweep {final_from} on")
> print("v*(s) = max_a q*(s, a):", {name(s): round(float(q_noisy[INDEX[s]].max()), 3) for s in STATES if s not in EXITS})
> ```

```output theme={null}
converged after 16 sweeps
               N       E       S       W
   s13    +0.523  +0.610  +0.435  +0.498
   s23    +0.650  +0.766  +0.650  +0.537
   s33    +0.801  +0.928  +0.554  +0.648
   s12    +0.487  +0.399  +0.317  +0.399
   s32    +0.585  -0.686  +0.224  +0.503
   s11    +0.374  +0.273  +0.292  +0.307
   s21    +0.267  +0.327  +0.267  +0.288
   s31    +0.428  +0.187  +0.314  +0.286
   s41    -0.753  +0.017  +0.151  +0.189
greedy policy: {'s13': 'E', 's23': 'E', 's33': 'E', 's12': 'N', 's32': 'N', 's11': 'N', 's21': 'E', 's31': 'N', 's41': 'W'}
greedy policy is final from sweep 4 on
v*(s) = max_a q*(s, a): {'s13': 0.61, 's23': 0.766, 's33': 0.928, 's12': 0.487, 's32': 0.585, 's11': 0.374, 's21': 0.327, 's31': 0.428, 's41': 0.189}
```

![Output from cell 7](https://mintcdn.com/aegeanaiinc/HvSJ_rlBnWVzEbWb/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/q-value-iteration/images/cell_7_output_1.svg?fit=max\&auto=format\&n=HvSJ_rlBnWVzEbWb\&q=85\&s=332e281071b71b656493d740aba8cce0)

*The same table with noisy moves. The greedy actions are the same as with deterministic moves, and almost every value is lower.*

A noisy move can fail, so on average the agent needs more moves to reach the $+1$ exit. Each extra move costs $-0.04$ and delays the $+1$ by another factor of 0.9. Moving east from $s_{33}$ is worth 0.928 instead of 1: with probability 0.1 the agent slips north into the edge of the grid and stays in $s_{33}$, and with probability 0.1 it slips south into $s_{32}$.

The greedy policy does not change, although the noise brings a new risk. In $s_{32}$ the agent still moves north, with $q_*(s_{32}, \text{N}) = 0.585$, although a slip east takes it into the $-1$ exit with probability 0.1. Moving west into the wall avoids that risk, but it is worth only 0.503, because the agent then has to take the long way around. In the [DP Gridworld](https://aegean.ai/book/mdp/dp-gridworld-demo.md) demo you can lower the cost of a move and watch the policy in $s_{32}$ switch to west.

The largest value in each row, $\max_a q_*(s, a)$, is the optimal state value $v_*(s)$ that Value Iteration computes for this grid. Both methods stop after 16 sweeps. Here the greedy policy is final from sweep 4, while on the Value Iteration page it is final from sweep 3. The difference is one look-ahead step. The greedy action of $q_k$ looks one step ahead from $v_{k-1} = \max_a q_{k-1}$, so the greedy policy of $q_k$ is the greedy policy of $v_{k-1}$.

![Output from cell 8](https://mintcdn.com/aegeanaiinc/HvSJ_rlBnWVzEbWb/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/q-value-iteration/images/cell_8_output_1.svg?fit=max\&auto=format\&n=HvSJ_rlBnWVzEbWb\&q=85\&s=b4ac1862327e6685999be21a60ca844e)

*The largest change of any entry in each sweep, on a log scale. With deterministic moves the change drops to zero in sweep 7, which the plot cannot show.*

With deterministic moves the largest change in sweep $k$ is exactly $0.9^{k-1}$, the discounted value of the $+1$ exit seen one move further away, and it drops to zero once the longest route is covered. With noisy moves the change shrinks in every sweep but never reaches zero, because a slip can take the agent back to a cell it has left, so the values keep feeding into each other. The loop stops when the change falls below the tolerance of $10^{-4}$.

**Key references**: (Sutton & Barto, 2018)

## References

* Sutton, R., Barto, A. (2018). *Reinforcement Learning: An Introduction*. [Link](https://www.andrew.cmu.edu/course/10-703/textbook/BartoSutton.pdf)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/q-value-iteration).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.