{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3df62a6a",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "There is **almost no reinforcement learning** in this notebook. Before\n",
    "writing algorithms, it is worth spending a session on what they act upon: an\n",
    "*environment*, the way it presents information to the agent, and how data\n",
    "is gathered from it.\n",
    "\n",
    "We meet the infrastructure used throughout the course — gymnasium\n",
    "environments, `VecEnv`, the actors, and the three collectors —\n",
    "`TransitionCollector`, `EpisodeCollector`, `RolloutCollector`, with what\n",
    "each of them can and cannot tell about the agent — and, once the pieces are\n",
    "in place, train the first learning agent of the course,\n",
    "tabular **Q-learning**, the one algorithm that can be written in a handful\n",
    "of lines given that infrastructure.\n",
    "\n",
    "The notebook then closes on a single maze, given to the agent under three\n",
    "different disguises without changing the problem at all. The same problem\n",
    "can be described in many ways, and that choice matters more than it looks\n",
    "— it decides what the agent is even able to represent.\n",
    "\n",
    "Small exercises are scattered through the notebook, marked **Exercise**:\n",
    "the cells that follow them do not run until they are completed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad00a454",
   "metadata": {
    "tags": [
     "colab",
     "pip",
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Installing required packages\n",
    "\n",
    "%pip install swig==4.3.* setuptools\n",
    "\n",
    "# Installing main packages\n",
    "\n",
    "%pip install gymnasium==1.2.* matplotlib numpy rl-mind==0.4.* torch\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce07a253",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import gymnasium as gym\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch\n",
    "import rl_mind.mazemdp_env\n",
    "from torch import Tensor\n",
    "from rl_mind.profiles import Profile\n",
    "from rl_mind.core import Action, Actor\n",
    "from rl_mind.env import VecEnv\n",
    "from rl_mind.data import Episode, Rollout, Transitions\n",
    "from rl_mind.collectors import EpisodeCollector, RolloutCollector, TransitionCollector\n",
    "from rl_mind import RenderWidget, DecimateTrimmer\n",
    "from rl_mind.notebook import silence_known_warnings\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "167ede7b",
   "metadata": {},
   "source": [
    "## The `rl_mind` toolkit\n",
    "\n",
    "The `rl_mind` package ([documentation](https://master-dac.isir.upmc.fr/rl/rl-mind/)),\n",
    "installed with the practicals, provides the pieces we are going to look at:\n",
    "\n",
    "- `VecEnv` runs several copies of a gymnasium environment in parallel and\n",
    "  uses **torch tensors** (similar to numpy ndarrays);\n",
    "- `Actor` is the base class of every policy of the course, and `Action` what\n",
    "  it returns;\n",
    "- the three collectors (`TransitionCollector`, `EpisodeCollector`,\n",
    "  `RolloutCollector`) run an actor in a `VecEnv` and each return a different\n",
    "  shape of data.\n",
    "\n",
    "The goal of this notebook is to:\n",
    "\n",
    "1. Show what is an RL environment (handled by gymnasium);\n",
    "2. Show how `rl_mind` can help you to interact with those environments in an RL setting;\n",
    "3. Describe the different ways to collect data to train your agents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18fb9c10",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5390e528",
   "metadata": {},
   "source": [
    "# 1. RL environments – gymnasium\n",
    "\n",
    "A [gymnasium](https://gymnasium.farama.org/) environment exposes very little:\n",
    "two **spaces** describing what it accepts and what it returns, and two\n",
    "methods, `reset` and `step`. Everything else — a maze, a pendulum, a video\n",
    "game — hides behind that contract.\n",
    "\n",
    "Let us look at two environments that could hardly be more different, `CartPole-v1` and `MazeMDP-v0`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f558c15",
   "metadata": {},
   "outputs": [],
   "source": [
    "MAZE = {\n",
    "    \"width\": 5,\n",
    "    \"height\": 5,\n",
    "    \"ratio\": 0.2,\n",
    "    # a seeded maze: every copy built from this description is the same one\n",
    "    \"seed\": 2,\n",
    "    # always start in the same cell, so that the views below are comparable\n",
    "    \"start_states\": [0],\n",
    "}\n",
    "\n",
    "for name, make_kwargs in [(\"CartPole-v1\", {}), (\"MazeMDP-v0\", {\"kwargs\": MAZE})]:\n",
    "    env = gym.make(name, **make_kwargs)\n",
    "    print(f\"{name}\")\n",
    "    print(f\"    observations: {env.observation_space}\")\n",
    "    print(f\"    actions     : {env.action_space}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18ca9269",
   "metadata": {},
   "source": [
    "Two families of spaces show up here:\n",
    "\n",
    "- `Box(low, high, shape, dtype)` — a vector of real numbers. For `CartPole` the four\n",
    "  numbers are the position and velocity of the cart, the angle and angular\n",
    "  velocity of the pole.\n",
    "- `Discrete(n)` — a single integer in $\\{0, \\ldots, n-1\\}$. For the maze it\n",
    "  is the number of the cell the agent stands on, and for the actions of both\n",
    "  environments it is the number of the chosen action."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0e9a860",
   "metadata": {},
   "source": [
    "## Interacting with an environment\n",
    "\n",
    "`reset()` starts an episode and returns a first observation; `step(action)`\n",
    "returns the next observation, the reward, and **two** distinct flags. Here\n",
    "we use `env.action_space.sample()` since we don't have an agent – this samples\n",
    "using a uniform distribution for each component."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d999bc9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = gym.make(\"CartPole-v1\")\n",
    "obs, info = env.reset(seed=0)\n",
    "print(f\"first observation: {obs}\")\n",
    "\n",
    "action = env.action_space.sample()\n",
    "print(f\"Sampled action: {action} in {env.action_space}\")\n",
    "obs, reward, terminated, truncated, info = env.step(action)\n",
    "print(f\"after one step   : {obs}\")\n",
    "print(f\"reward {reward}, terminated {terminated}, truncated {truncated}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b674f443",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "`terminated` and `truncated` both end the episode, but they do not mean the\n",
    "same thing, and confusing them is a classic source of silent bugs:\n",
    "\n",
    "- **`terminated`** — the episode reached a real terminal state (the pole\n",
    "  fell). There is no future: whatever the agent would have done next is\n",
    "  worth nothing (reward is 0).\n",
    "- **`truncated`** — the episode was cut short from the outside, typically by\n",
    "  a time limit. The agent could have continued, and the future is *not*\n",
    "  worth nothing.\n",
    "\n",
    "Every algorithm of the course relies on that distinction to decide whether\n",
    "to *bootstrap*, i.e. whether to use the value of the state that follows.\n",
    "\n",
    "Let us watch it happen: `CartPole-v1` is limited to 500 steps, so a policy\n",
    "good enough to survive that long gets `truncated`, while a bad one gets\n",
    "`terminated` early.\n",
    "\n",
    "**Exercise.** A policy is a function from an observation to an action.\n",
    "Complete `react_to_the_pole` below so that the cart pushes in the direction\n",
    "the pole is falling (action 1 pushes right).\n",
    "\n",
    "The observation is\n",
    "`[position, velocity, angle, angular velocity]`: position (m) and velocity\n",
    "(m/s) describe the cart, angle (**radians**, positive = leaning right) and\n",
    "angular velocity (rad/s) describe the pole. **The angle alone is not always\n",
    "enough to tell which way the pole is going**: it can be leaning right while\n",
    "already swinging back left, so also look at how fast it is rotating. Once\n",
    "the two flags differ between the two policies, you have a policy that\n",
    "survives the time limit.\n",
    "\n",
    "Note: `react_to_the_pole` reacts to a single observation — a plain\n",
    "`np.ndarray`, no batch. There is only one environment here; once `VecEnv`\n",
    "shows up in part 2, every actor of the course reacts to a *batch* of\n",
    "observations (one row per environment) at once."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9454931",
   "metadata": {},
   "outputs": [],
   "source": [
    "def always_push_right(obs: np.ndarray) -> int:\n",
    "    return 1\n",
    "\n",
    "\n",
    "def react_to_the_pole(obs: np.ndarray) -> int:\n",
    "    # obs = [position, velocity, angle (rad), angular velocity (rad/s)]\n",
    "    # The output is an integer:\n",
    "    # - 0: Push cart to the left\n",
    "    # - 1: Push cart to the right\n",
    "    #\n",
    "    # Push towards the side the pole is falling to\n",
    "\n",
    "    #\n",
    "    return ...\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "\n",
    "for policy in [always_push_right, react_to_the_pole]:\n",
    "    env = RenderWidget(\n",
    "        gym.make(\"CartPole-v1\", render_mode=\"rgb_array\"),\n",
    "        trimmer=DecimateTrimmer(100, keep_ratio=0.5),\n",
    "    )\n",
    "\n",
    "    obs, _ = env.reset(seed=1)\n",
    "    steps, terminated, truncated = 0, False, False\n",
    "    while not (terminated or truncated):\n",
    "        obs, _, terminated, truncated, _ = env.step(policy(obs))\n",
    "        steps += 1\n",
    "    ending = \"terminated (the pole fell)\" if terminated else \"truncated (time limit)\"\n",
    "    print(f\"{policy.__name__:>18}: {steps:>3} steps, {ending}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f464d85",
   "metadata": {},
   "source": [
    "# 2. `VecEnv`: many copies, and tensors\n",
    "\n",
    "Reinforcement learning needs a *lot* of interaction, and a single environment\n",
    "stepped one action at a time is a poor use of a machine. `VecEnv` runs\n",
    "`num_envs` independent copies of an environment and steps them together.\n",
    "\n",
    "It also converts everything to **torch tensors**, so that the data can be fed\n",
    "to a neural network without any bookkeeping. The leading dimension is always\n",
    "the number of environments.\n",
    "\n",
    "Note also that we use visualization helpers from the `rl_mind` library, that you\n",
    "can use to visualize better what an agent is doing when working with\n",
    "environments (at least those that provide image outputs)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e61ed4c4",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "env = RenderWidget(\n",
    "    gym.make(\"CartPole-v1\", render_mode=\"rgb_array\"),\n",
    "    trimmer=DecimateTrimmer(100, keep_ratio=0.5),\n",
    ")\n",
    "obs, _ = env.reset(seed=1)\n",
    "terminated, truncated = False, False\n",
    "while not (terminated or truncated):\n",
    "    obs, reward, terminated, truncated, _ = env.step(react_to_the_pole(obs))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a406289f",
   "metadata": {},
   "source": [
    "`step` returns an `EnvStep`, which carries `obs`, `next_obs`, `reward`,\n",
    "`terminated` and `truncated` (plus `done`, which is simply\n",
    "`terminated | truncated`), one entry per environment.\n",
    "\n",
    "Why both `obs` and `next_obs`? Because when an episode ends in one of the\n",
    "copies, that copy is **reset automatically** — otherwise the whole batch\n",
    "would have to wait for the slowest episode — and the observation you should\n",
    "*act* on next is no longer the observation that *followed* the last action.\n",
    "`VecEnv` keeps the two apart:\n",
    "\n",
    "- `next_obs` is the true successor $s_{t+1}$, the one the algorithms need to\n",
    "  compute a value;\n",
    "- `obs` is what to act upon at the next step.\n",
    "\n",
    "## A minimal torch toolbox\n",
    "\n",
    "The exercises of this notebook only ever need a handful of tensor\n",
    "operations. If `torch` is new to you, here is the short list — everything\n",
    "below is a 1-D tensor, one entry per environment:\n",
    "\n",
    "- `torch.zeros(n)`, `torch.full((n,), value)`, `torch.randint(low, high,\n",
    "  (n,))`, `torch.rand(n)` — create tensors: zeros, a repeated constant,\n",
    "  random integers, random floats in $[0, 1)$.\n",
    "- `t[mask]` / `t[i, j]` — index or mask a tensor like a numpy array; a\n",
    "  *boolean* tensor used as an index keeps only the `True` entries.\n",
    "- `torch.where(cond, a, b)` — element-wise \"if / else\": `a` where `cond` is\n",
    "  `True`, `b` elsewhere.\n",
    "- `t.sum()`, `t.max(dim)` — reduce along a dimension; `t.max(-1).values` is\n",
    "  the max over the last axis, `.indices` the corresponding `argmax`.\n",
    "- `~t` — logical *not* on a boolean tensor (e.g. `~terminated`).\n",
    "- `q.index_put_((row_idx, col_idx), value, accumulate=True)` — add `value`\n",
    "  into `q[row_idx, col_idx]` entry by entry, summing contributions when an\n",
    "  index repeats in the batch (used once, in the Q-learning update).\n",
    "\n",
    "The [PyTorch documentation](https://pytorch.org/docs/stable/torch.html) has\n",
    "more detail on any of these if you need it.\n",
    "\n",
    "**Exercise.** Run 200 random steps in the four environments and count the\n",
    "episodes that end along the way, using the `done` flags (a boolean tensor —\n",
    "see `t.sum()` above). A random policy keeps the pole up for about 20 steps:\n",
    "how many episodes do you expect?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f38d2990",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = VecEnv(\"CartPole-v1\", num_envs=4, seed=0)\n",
    "env.reset()\n",
    "n_ended = 0\n",
    "for _ in range(200):\n",
    "    step = env.step(torch.randint(0, env.n_actions, (env.num_envs,)))\n",
    "    # Count the episodes that end at this step\n",
    "\n",
    "    n_ended += ...\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "print(f\"{n_ended} episodes ended in {200 * env.num_envs} steps\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20aef850",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# 3. Collecting data\n",
    "\n",
    "Since there is no learning yet, we need a policy that does not learn: one\n",
    "that acts at random. Every policy of the course derives from `Actor`, and\n",
    "returns an `Action`. An actor has two behaviours: `actor(obs)` (the\n",
    "`forward` method) is the **training** behaviour, which may explore, and\n",
    "`actor.act(obs)` is the deterministic **evaluation** behaviour. For a random\n",
    "actor the two are the same."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "787a839f",
   "metadata": {},
   "outputs": [],
   "source": [
    "class RandomActor(Actor[Action]):\n",
    "    \"\"\"Picks an action uniformly at random, for a batch of observations\"\"\"\n",
    "\n",
    "    def __init__(self, n_actions: int):\n",
    "        super().__init__()\n",
    "        self.n_actions = n_actions\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        return Action(value=self.act(obs))\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        return torch.randint(0, self.n_actions, (len(obs),))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f4e58ed",
   "metadata": {},
   "source": [
    "## Automatic resets\n",
    "\n",
    "Running an actor in an environment and *storing* what happens is the job of a\n",
    "**collector**. Before meeting them, one detail of `VecEnv` has to be settled,\n",
    "because the collectors depend on it: what exactly happens on the step where\n",
    "an episode ends and the copy is reset. There are two ways of doing it:\n",
    "\n",
    "- **next-step reset** (the default): the ending step returns the last\n",
    "  observation of the finished episode, and the *following* step ignores the\n",
    "  action it is given and returns the first observation of a fresh episode.\n",
    "  That following step is not a valid transition, and has to be discarded.\n",
    "- **same-step reset** (`same_step_reset=True`): the ending step already\n",
    "  returns the first observation of the new episode in `obs`, while `next_obs`\n",
    "  holds the last observation of the episode that just ended. **Every** step is\n",
    "  then a valid transition.\n",
    "\n",
    "The first mode is the natural one when the data is stored transition by\n",
    "transition or episode by episode: one can simply skip the invalid step. The\n",
    "second one is needed when the data must form a dense block of consecutive\n",
    "steps, with no hole in it — which is what the on-policy methods (A2C, PPO)\n",
    "need, as we will see."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07212d0f",
   "metadata": {},
   "outputs": [],
   "source": [
    "for same_step in [False, True]:\n",
    "    env = VecEnv(\"CartPole-v1\", num_envs=1, seed=0, same_step_reset=same_step)\n",
    "    env.reset()\n",
    "\n",
    "    # push right until the pole falls, and look at the step that ends the episode\n",
    "    step = env.step(torch.ones(1, dtype=torch.int64))\n",
    "    while not step.done[0]:\n",
    "        step = env.step(torch.ones(1, dtype=torch.int64))\n",
    "\n",
    "    mode = \"same-step\" if same_step else \"next-step\"\n",
    "    print(f\"{mode} reset, on the step that ends the episode:\")\n",
    "    print(f\"    next_obs (the successor s_t+1) : {step.next_obs[0].numpy().round(3)}\")\n",
    "    print(f\"    obs      (what to act on next) : {step.obs[0].numpy().round(3)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c69ad0f2",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The three collectors\n",
    "\n",
    "There are three collectors, and they differ in the shape of the data they\n",
    "return — because the three families of algorithms need different things:\n",
    "\n",
    "| collector | returns | reset mode | for |\n",
    "|---|---|---|---|\n",
    "| `TransitionCollector` | a flat batch of transitions | next-step (invalid steps are dropped) | off-policy (DQN, DDPG, SAC): the data goes into a replay buffer and gets shuffled, so the order does not matter |\n",
    "| `EpisodeCollector` | complete episodes | next-step (invalid steps are dropped) | episodic methods (REINFORCE), which need the return of a whole episode |\n",
    "| `RolloutCollector` | a `[T, B]` block | **same-step** (required) | on-policy methods (A2C, PPO), which walk *backwards* over time and therefore need the time axis intact |\n",
    "\n",
    "To see what this means in practice, we go back to the maze of part 1, and\n",
    "we need a policy whose episodes are all different — but which still reaches\n",
    "the goal (a random walk in the maze rarely does before the time limit).\n",
    "\n",
    "### A policy worth collecting\n",
    "\n",
    "The maze exposes its whole model: the transition probabilities\n",
    "$P(s' \\mid s, a)$ and the rewards $r(s, a)$. From them, the *optimal*\n",
    "policy can be computed without any interaction, by **value iteration** —\n",
    "the subject of the next practical, so take the function below as given.\n",
    "The reward is 1 for acting in the goal cell (which ends the episode) and 0\n",
    "elsewhere."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7df0c299",
   "metadata": {},
   "outputs": [],
   "source": [
    "def optimal_policy(maze, gamma: float = 0.9, n_iterations: int = 200):\n",
    "    \"\"\"The optimal policy and value function of a maze, by value iteration\n",
    "\n",
    "    :returns: the greedy action of every state, shape `[n_states]`, and the\n",
    "        optimal value $V^*$ of every state\n",
    "    \"\"\"\n",
    "    P = torch.as_tensor(maze.P, dtype=torch.float32)\n",
    "    r = torch.as_tensor(maze.r, dtype=torch.float32)\n",
    "    # No future after acting in a terminal state\n",
    "    not_terminal = torch.ones(len(r))\n",
    "    not_terminal[maze.terminal_states] = 0\n",
    "    v = torch.zeros(len(r))\n",
    "    for _ in range(n_iterations):\n",
    "        q = r + gamma * not_terminal[:, None] * (P @ v)\n",
    "        v = q.max(-1).values\n",
    "    return q.argmax(-1), v\n",
    "\n",
    "\n",
    "maze = gym.make(\"MazeMDP-v0\", kwargs=MAZE).unwrapped\n",
    "pi_star, v_star = optimal_policy(maze)\n",
    "print(f\"optimal action in each state: {pi_star.tolist()}\")\n",
    "print(f\"optimal value of the start state: {v_star[0]:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "363c475c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "The optimal policy is deterministic, and so is the maze: all its episodes\n",
    "are the same. To get some variety, we **mix** it with a random policy:\n",
    "with probability `p_random` the action is drawn at random, otherwise it is\n",
    "the optimal one.\n",
    "\n",
    "**Exercise.** Complete `forward`. Everything is batched: `obs` holds one\n",
    "state per environment, and the returned `Action` one action per\n",
    "environment. Draw the random actions with `torch.randint` (as in\n",
    "`RandomActor`), a boolean mask of the environments that act at random with\n",
    "`torch.rand` (uniform in $[0, 1)$), and pick between the two with\n",
    "`torch.where` (see the toolbox in part 2). Getting used to batched\n",
    "operations and masks, rather than loops over environments, is one of the\n",
    "goals of this exercise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ed7c0f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "class MixedActor(Actor[Action]):\n",
    "    \"\"\"Follows a policy, but acts at random with probability `p_random`\"\"\"\n",
    "\n",
    "    def __init__(self, policy: Tensor, n_actions: int, p_random: float):\n",
    "        super().__init__()\n",
    "        self.policy = policy\n",
    "        self.n_actions = n_actions\n",
    "        self.p_random = p_random\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        \"\"\"The action of the policy in every state of `obs`\"\"\"\n",
    "        return self.policy[obs]\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        # Random with probability p_random, the policy's action otherwise\n",
    "\n",
    "        policy = self.act(obs)\n",
    "        random = ...\n",
    "        explore = ...\n",
    "        # return Action(value=torch.where(explore, random, policy))\n",
    "        assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5aea74b6",
   "metadata": {},
   "source": [
    "Let us run it with the three collectors, for the same number of steps in\n",
    "4 copies of the maze."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "049ab6e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.manual_seed(0)\n",
    "actor = MixedActor(pi_star, maze.action_space.n, p_random=0.3)\n",
    "\n",
    "env = VecEnv(\"MazeMDP-v0\", num_envs=4, seed=0, kwargs=MAZE)\n",
    "transitions = TransitionCollector(env, actor).collect(n_steps=50)\n",
    "print(f\"TransitionCollector: {len(transitions)} transitions\")\n",
    "print(\n",
    "    f\"    obs {tuple(transitions.obs.shape)} | action \"\n",
    "    f\"{tuple(transitions.action.value.shape)} | reward \"\n",
    "    f\"{tuple(transitions.reward.shape)}\"\n",
    ")\n",
    "\n",
    "env = VecEnv(\"MazeMDP-v0\", num_envs=4, seed=0, kwargs=MAZE)\n",
    "episodes = EpisodeCollector(env, actor).collect(n_episodes=8)\n",
    "print(\n",
    "    f\"EpisodeCollector: {len(episodes)} episodes, \"\n",
    "    f\"of lengths {[len(e) for e in episodes]}\"\n",
    ")\n",
    "\n",
    "env = VecEnv(\"MazeMDP-v0\", num_envs=4, seed=0, kwargs=MAZE, same_step_reset=True)\n",
    "rollout = RolloutCollector(env, actor).collect(n_steps=50)\n",
    "print(f\"RolloutCollector: obs {tuple(rollout.obs.shape)}  (time, envs)\")\n",
    "print(f\"    flattened: {tuple(rollout.flatten().obs.shape)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf915919",
   "metadata": {},
   "source": [
    "Notice the shapes. `TransitionCollector` returns **fewer** than\n",
    "`n_steps * num_envs` transitions: it silently drops the invalid steps that\n",
    "follow an automatic reset. `RolloutCollector` cannot afford to drop anything,\n",
    "since that would punch holes in its `[T, B]` block — which is why it demands\n",
    "`same_step_reset=True`.\n",
    "\n",
    "All of these are `TensorStruct`s (except `Episode`, which is a plain\n",
    "dataclass): they can be indexed, sliced and masked like a tensor, but each\n",
    "field keeps its name and its type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96170956",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"one transition   : {tuple(transitions[0].obs.shape)}\")\n",
    "print(f\"the first three  : {tuple(transitions[:3].obs.shape)}\")\n",
    "print(f\"the terminal ones: {len(transitions[transitions.terminated])}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e53c1b36",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Transitions, from any collector\n",
    "\n",
    "A transition $(s, a, r, s', \\text{terminated})$ is the smallest piece of\n",
    "experience, and all three collectors record them — they only arrange them\n",
    "differently. A `Rollout` has the five fields already (plus `truncated`):\n",
    "flattening it and dropping `truncated` gives `Transitions`.\n",
    "\n",
    "**Exercise.** Write `episode_to_transitions(episode)`. An `Episode` holds\n",
    "`obs` ($s_0 \\ldots s_{T-1}$), `action`, `reward` and a single `terminated`\n",
    "flag for its last step; `episode.all_obs` gives $s_0 \\ldots s_T$, so that\n",
    "`all_obs[1:]` are the successors. Build the `terminated` field with\n",
    "`torch.zeros(..., dtype=torch.bool)` (see the toolbox in part 2) and set\n",
    "its last entry."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6676fff",
   "metadata": {},
   "outputs": [],
   "source": [
    "def episode_to_transitions(episode: Episode[Action]) -> Transitions[Action]:\n",
    "    \"\"\"The transitions of an episode, as a flat batch\"\"\"\n",
    "    # Build the five fields; only the last step may be terminal\n",
    "\n",
    "    terminated = ...\n",
    "    # return Transitions(...)\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "\n",
    "def rollout_to_transitions(rollout: Rollout[Action]) -> Transitions[Action]:\n",
    "    \"\"\"The transitions of a rollout, as a flat batch (time, then environment)\"\"\"\n",
    "    flat = rollout.flatten()\n",
    "    return Transitions(\n",
    "        obs=flat.obs,\n",
    "        action=flat.action,\n",
    "        reward=flat.reward,\n",
    "        next_obs=flat.next_obs,\n",
    "        terminated=flat.terminated,\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f267a4d3",
   "metadata": {},
   "source": [
    "With the pure optimal policy (`p_random=0`) and a single environment,\n",
    "nothing is random any more: the three collectors must then record\n",
    "**exactly the same** transitions, the 9 steps of the shortest path."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82eb13aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "optimal = MixedActor(pi_star, maze.action_space.n, p_random=0.0)\n",
    "\n",
    "\n",
    "def maze_env(same_step_reset: bool = False) -> VecEnv:\n",
    "    return VecEnv(\n",
    "        \"MazeMDP-v0\", num_envs=1, seed=0, kwargs=MAZE, same_step_reset=same_step_reset\n",
    "    )\n",
    "\n",
    "\n",
    "episode = EpisodeCollector(maze_env(), optimal).collect(n_episodes=1)[0]\n",
    "n_steps = len(episode)\n",
    "from_collectors = {\n",
    "    \"transition\": TransitionCollector(maze_env(), optimal).collect(n_steps),\n",
    "    \"episode\": episode_to_transitions(episode),\n",
    "    \"rollout\": rollout_to_transitions(\n",
    "        RolloutCollector(maze_env(same_step_reset=True), optimal).collect(n_steps)\n",
    "    ),\n",
    "}\n",
    "\n",
    "\n",
    "def as_tuples(t: Transitions[Action]) -> list[tuple]:\n",
    "    \"\"\"The transitions as a list of (s, a, r, s', terminated) tuples\"\"\"\n",
    "    return list(\n",
    "        zip(\n",
    "            t.obs.tolist(),\n",
    "            t.action.value.tolist(),\n",
    "            t.reward.tolist(),\n",
    "            t.next_obs.tolist(),\n",
    "            t.terminated.tolist(),\n",
    "        )\n",
    "    )\n",
    "\n",
    "\n",
    "for name, t in from_collectors.items():\n",
    "    print(f\"{name:>10}: {as_tuples(t)[-3:]}  (the last three)\")\n",
    "tuples = [as_tuples(t) for t in from_collectors.values()]\n",
    "assert tuples[0] == tuples[1] == tuples[2]\n",
    "print(\"the three lists are identical\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f919163d",
   "metadata": {},
   "source": [
    "With the mixed policy, the three collectors of course do not see the same\n",
    "episodes any more — but they still record the same *kind* of data: every\n",
    "transition of each of them is a genuine transition of the maze. Since we\n",
    "know the model, we can check it: $s'$ is the successor of $(s, a)$ (the maze\n",
    "is deterministic, so $P(s' \\mid s, a) = 1$), $r = r(s, a)$, and the\n",
    "transition is terminal exactly when it acts in the goal cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4105d5b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "P = torch.as_tensor(maze.P)\n",
    "r = torch.as_tensor(maze.r, dtype=torch.float32)\n",
    "goal = torch.as_tensor(maze.terminal_states)\n",
    "\n",
    "for name, t in [\n",
    "    (\"transition\", transitions),\n",
    "    (\"episode\", Transitions.cat([episode_to_transitions(e) for e in episodes])),\n",
    "    (\"rollout\", rollout_to_transitions(rollout)),\n",
    "]:\n",
    "    s, a = t.obs, t.action.value\n",
    "    checks = [\n",
    "        (P[s, a, t.next_obs] == 1).all(),\n",
    "        (t.reward == r[s, a]).all(),\n",
    "        (t.terminated == torch.isin(s, goal)).all(),\n",
    "    ]\n",
    "    print(f\"{name:>10}: {len(t):>3} transitions, all valid: {all(checks)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f05489a1",
   "metadata": {},
   "source": [
    "### Returns: two collectors out of three\n",
    "\n",
    "What the three collectors do *not* share is the structure around the\n",
    "transitions: which episode each one belongs to, and at which time step.\n",
    "That structure is what a **return** needs,\n",
    "\n",
    "$$ G_0 = r_1 + \\gamma\\, r_2 + \\gamma^2 r_3 + \\ldots = \\sum_{t=0}^{T-1}\n",
    "\\gamma^t\\, r_{t+1} $$\n",
    "\n",
    "In the maze, the undiscounted sum of rewards is not very informative: it\n",
    "is 1 whenever the goal is reached. The *discounted* return, on the other\n",
    "hand, is $\\gamma^{T-1}$: the shorter the episode, the higher the return.\n",
    "\n",
    "**Exercise.** Compute the discounted return of an episode (`torch.arange`\n",
    "gives the time steps $0 \\ldots T-1$)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b1f833ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "GAMMA = 0.9\n",
    "\n",
    "\n",
    "def discounted_return(episode: Episode[Action], gamma: float) -> float:\n",
    "    \"\"\"The discounted return $G_0$ of an episode\"\"\"\n",
    "    # Sum the rewards, discounted by gamma^t\n",
    "\n",
    "    # return ...\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "\n",
    "print(f\"undiscounted: {[e.cumulated_reward for e in episodes]}\")\n",
    "print(f\"discounted  : {[round(discounted_return(e, GAMMA), 3) for e in episodes]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5890d68f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "A rollout does not come cut into episodes, but it keeps everything needed\n",
    "to cut it: the time axis, one column per environment, and the `done` flags\n",
    "(`terminated | truncated`) that mark where each episode ends.\n",
    "\n",
    "**Exercise.** Compute the discounted returns of the episodes of a rollout.\n",
    "Walk along the time axis of each environment, accumulating the discounted\n",
    "rewards, and output the return when an episode ends. The episode still\n",
    "running at the end of the rollout is incomplete: drop it. (The first\n",
    "episode of each column is complete, since the environments are reset on the\n",
    "first `collect`.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8af79d13",
   "metadata": {},
   "outputs": [],
   "source": [
    "def rollout_returns(rollout: Rollout[Action], gamma: float) -> list[float]:\n",
    "    \"\"\"The discounted returns of the episodes that end within the rollout\"\"\"\n",
    "    n_steps, num_envs = rollout.reward.shape\n",
    "    returns = []\n",
    "    # Accumulate each column, and output a return at each `done`\n",
    "\n",
    "    ...\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "    return returns"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a23b48c",
   "metadata": {},
   "source": [
    "The two collectors should now agree on the *average* return of the mixed\n",
    "policy (not on the individual episodes, which are random); and with\n",
    "`p_random=0`, both should give the optimal value of the start state,\n",
    "computed by value iteration above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "622a1b2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "for p_random in [0.3, 0.0]:\n",
    "    actor = MixedActor(pi_star, maze.action_space.n, p_random)\n",
    "    env = VecEnv(\"MazeMDP-v0\", num_envs=4, seed=0, kwargs=MAZE)\n",
    "    from_episodes = [\n",
    "        discounted_return(e, GAMMA)\n",
    "        for e in EpisodeCollector(env, actor).collect(n_episodes=40)\n",
    "    ]\n",
    "    env = VecEnv(\"MazeMDP-v0\", num_envs=4, seed=0, kwargs=MAZE, same_step_reset=True)\n",
    "    from_rollout = rollout_returns(RolloutCollector(env, actor).collect(150), GAMMA)\n",
    "    print(\n",
    "        f\"p_random={p_random}: mean return {np.mean(from_episodes):.3f} \"\n",
    "        f\"({len(from_episodes)} episodes) vs {np.mean(from_rollout):.3f} \"\n",
    "        f\"({len(from_rollout)} episodes of the rollout)\"\n",
    "    )\n",
    "print(f\"V*(start) = {v_star[0]:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5112e701",
   "metadata": {},
   "source": [
    "And the `TransitionCollector`? Look at the first transitions of a batch\n",
    "collected in 4 environments:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "532de35e",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = VecEnv(\"MazeMDP-v0\", num_envs=4, seed=0, kwargs=MAZE)\n",
    "batch = TransitionCollector(env, MixedActor(pi_star, maze.action_space.n, 0.3)).collect(\n",
    "    n_steps=3\n",
    ")\n",
    "print(f\"s : {batch.obs.tolist()}\")\n",
    "print(f\"s': {batch.next_obs.tolist()}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "521e8937",
   "metadata": {},
   "source": [
    "The transitions of the four environments are **interleaved** (one per\n",
    "environment at each step), and nothing says which environment a\n",
    "transition came from, nor at which step of its episode it was taken — yet\n",
    "$\\gamma^t$ needs $t$. As soon as a step is dropped after a reset, the\n",
    "interleaving is not even regular any more. Worse, an episode is spread\n",
    "over several `collect` calls, and an episode cut by the time limit leaves\n",
    "no trace at all: `Transitions` has no `truncated` field. **The returns\n",
    "cannot be computed from a `TransitionCollector`.**\n",
    "\n",
    "This is not a flaw: the off-policy methods it feeds never need a return.\n",
    "They **bootstrap** — they estimate the future from $s'$ with their own\n",
    "value function, one transition at a time, as Q-learning will do in part 4.\n",
    "All they need from a transition is $(s, a, r, s', \\text{terminated})$, and\n",
    "they shuffle the transitions in a replay buffer anyway.\n",
    "\n",
    "**Exercise (think).** With a single environment, the transitions come in\n",
    "order. Could you then rebuild the episodes, and their returns? What would\n",
    "be missing?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a578a742",
   "metadata": {},
   "source": [
    "**Exercise.** Over 200 steps of a fresh `TransitionCollector` on 4\n",
    "environments, compute the number of dropped steps and the number of terminal\n",
    "transitions that were recorded. Explain how the two are related, and why\n",
    "they may differ by a few units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad2161e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = VecEnv(\"CartPole-v1\", num_envs=4, seed=0)\n",
    "transitions = TransitionCollector(env, RandomActor(env.n_actions)).collect(n_steps=200)\n",
    "# The dropped steps and the terminal transitions\n",
    "\n",
    "n_dropped = ...\n",
    "n_terminal = ...\n",
    "assert False, 'Not implemented yet'\n",
    "\n",
    "print(f\"dropped steps {n_dropped}, terminal transitions {n_terminal}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "958b9ac3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "**Exercise.** `RandomActor` ignores its observations. Write an actor for the\n",
    "maze that always plays the same action (one call to `torch.full`, see the\n",
    "toolbox in part 2, does it), and use `EpisodeCollector` to measure how long\n",
    "its episodes last. What do you expect, and what do you observe? (Remember\n",
    "the time limit met in part 1.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "578f3c3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ConstantActor(Actor[Action]):\n",
    "    \"\"\"Always plays the same action\"\"\"\n",
    "\n",
    "    def __init__(self, action: int):\n",
    "        super().__init__()\n",
    "        self.action = action\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        return Action(value=self.act(obs))\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        # The same action for every observation of the batch\n",
    "\n",
    "        # return ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "\n",
    "env = VecEnv(\"MazeMDP-v0\", num_envs=2, seed=0, kwargs=MAZE)\n",
    "for action in range(env.n_actions):\n",
    "    episodes = EpisodeCollector(env, ConstantActor(action)).collect(n_episodes=2)\n",
    "    print(f\"action {action}: episodes of lengths {[len(e) for e in episodes]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c152b632",
   "metadata": {},
   "source": [
    "Every action hits the 200-step limit without a single `terminated=True`:\n",
    "this is not a bug, the constant action walks the agent into a wall after a\n",
    "step or two and it stays there, so it never reaches the goal. Seeing it\n",
    "helps: below is one constant-action episode, rendered with the maze's own\n",
    "notebook widget (lighter than `RenderWidget`, which is meant for\n",
    "environments — like `CartPole` above — that only render as images)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "352f4223",
   "metadata": {},
   "outputs": [],
   "source": [
    "maze = gym.make(\"MazeMDP-v0\", kwargs=MAZE, render_mode=\"human\").unwrapped\n",
    "maze.reset()\n",
    "maze.init_draw(\"A constant action\")\n",
    "for _ in range(15):\n",
    "    maze.step(1)\n",
    "    maze.render()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "512cce01",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# 4. A first learning agent: Q-learning\n",
    "\n",
    "We now have an environment, several copies of it, an actor and three ways of\n",
    "collecting data. What is missing is an actor that *learns*. The simplest one\n",
    "is tabular **Q-learning**, and it fits the infrastructure in a handful of\n",
    "lines.\n",
    "\n",
    "Q-learning keeps a table $Q(s, a)$ with one entry per state and action —\n",
    "which is only possible with the *native* view of the maze (an observation is\n",
    "the integer index of the cell, as introduced in part 1), which indexes the\n",
    "table directly. For a transition\n",
    "$(s, a, r, s')$, the entry is moved towards the bootstrapped target:\n",
    "\n",
    "$$ Q(s, a) \\leftarrow Q(s, a) + \\alpha\\,\\big[\\, r + \\gamma\\,(1 -\n",
    "\\text{terminated})\\,\\max_{a'} Q(s', a') - Q(s, a) \\,\\big] $$\n",
    "\n",
    "where $\\alpha$ is the learning rate. When $s'$ is **terminal**, there is no\n",
    "future and the bootstrap term is dropped — this is the `terminated` flag\n",
    "of part 1 at work. Note that the maze has a time limit of 200 steps: an\n",
    "episode cut by it is *truncated*, not terminated, and its last transition\n",
    "bootstraps like any other.\n",
    "\n",
    "## The actor\n",
    "\n",
    "The actor owns the table. Its two behaviours are now different: in\n",
    "training it explores with an **$\\epsilon$-greedy** rule (a random action\n",
    "with probability $\\epsilon$, the greedy one otherwise), and in evaluation\n",
    "(`act`) it is greedy.\n",
    "\n",
    "**Exercise.** Complete `forward`. This is the `MixedActor` of part 3\n",
    "again, with $\\epsilon$ as `p_random` and the greedy action of the table in\n",
    "place of the optimal policy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fd21e50b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class QTableActor(Actor[Action]):\n",
    "    \"\"\"An epsilon-greedy actor over a Q-table\"\"\"\n",
    "\n",
    "    def __init__(self, n_states: int, n_actions: int, epsilon: float):\n",
    "        super().__init__()\n",
    "        self.q = torch.zeros(n_states, n_actions)\n",
    "        self.epsilon = epsilon\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        \"\"\"The greedy action of every state in `obs`\"\"\"\n",
    "        return self.q[obs].argmax(-1)\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        # Epsilon-greedy: random with probability epsilon, greedy otherwise\n",
    "\n",
    "        greedy = self.act(obs)\n",
    "        random = ...\n",
    "        explore = ...\n",
    "        # return Action(value=torch.where(explore, random, greedy))\n",
    "        assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21a7419e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The update\n",
    "\n",
    "A `TransitionCollector` returns a batch of transitions at once, so the\n",
    "update is written for a **batch**: every quantity below is a tensor with one\n",
    "entry per transition, and the table is indexed with the tensors of states\n",
    "and actions directly.\n",
    "\n",
    "**Exercise.** Compute the target and the TD error. `q[batch.next_obs]`\n",
    "indexes the table with a batch of states at once, giving one row of\n",
    "$Q(s', \\cdot)$ per transition; `.max(-1).values` reduces each row to its\n",
    "max. `~batch.terminated` is the boolean mask, negated (see the toolbox in\n",
    "part 2), that zeroes the bootstrap term for terminal transitions. The last\n",
    "line applies the update; it uses `index_put_` with `accumulate=True`\n",
    "because two transitions of the batch may share the same $(s, a)$, in which\n",
    "case both corrections must be applied."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c409b20",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def q_learning_update(\n",
    "    q: Tensor, batch: Transitions[Action], alpha: float, gamma: float\n",
    ") -> Tensor:\n",
    "    \"\"\"Apply the Q-learning update to `q` for a batch of transitions\n",
    "\n",
    "    :returns: the TD errors, shape `[N]`\n",
    "    \"\"\"\n",
    "    state, action = batch.obs, batch.action.value\n",
    "    # The bootstrapped target and the TD error (no bootstrap from a terminal state)\n",
    "\n",
    "    q_next = ...\n",
    "    target = ...\n",
    "    td_error = ...\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "    q.index_put_((state, action), alpha * td_error, accumulate=True)\n",
    "    return td_error"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50183f04",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Evaluation\n",
    "\n",
    "The reward of the maze is 1 when the goal is reached and 0 elsewhere, so the\n",
    "cumulated reward says only *whether* the goal was reached. A better measure\n",
    "of progress is the **length** of a greedy episode: it decreases as the\n",
    "policy improves, and is capped by the time limit until the goal is found.\n",
    "\n",
    "We measure it with the tools of part 3: `EpisodeCollector` runs an actor's\n",
    "training behaviour, so we wrap the Q-table actor in an actor whose training\n",
    "behaviour *is* the evaluation one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55c17a9a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class GreedyActor(Actor[Action]):\n",
    "    \"\"\"Runs the evaluation behaviour (`act`) of another actor\"\"\"\n",
    "\n",
    "    def __init__(self, actor: Actor[Action]):\n",
    "        super().__init__()\n",
    "        self.actor = actor\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        return Action(value=self.actor.act(obs))\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        return self.actor.act(obs)\n",
    "\n",
    "\n",
    "def greedy_episode_length(actor: Actor[Action], env: VecEnv) -> float:\n",
    "    \"\"\"The mean length of one greedy episode per environment\"\"\"\n",
    "    episodes = EpisodeCollector(env, GreedyActor(actor)).collect(env.num_envs)\n",
    "    return float(np.mean([len(e) for e in episodes]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e632850",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The training loop\n",
    "\n",
    "Everything is in place. Each iteration performs **one step in every\n",
    "environment**, updates the table with the resulting batch, and lowers\n",
    "$\\epsilon$ linearly from 1 to 0.05 over the first half of the training.\n",
    "The number of environment steps is what we count: it is the cost of\n",
    "training, and the budget every experiment below is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca98df23",
   "metadata": {},
   "outputs": [],
   "source": [
    "def train_q_learning(\n",
    "    num_envs: int,\n",
    "    total_steps: int,\n",
    "    alpha: float = 0.5,\n",
    "    gamma: float = 0.9,\n",
    "    eval_every: int = 100,\n",
    "    seed: int = 0,\n",
    "):\n",
    "    torch.manual_seed(seed)\n",
    "    env = VecEnv(\"MazeMDP-v0\", num_envs, seed=seed, kwargs=MAZE)\n",
    "    eval_env = VecEnv(\"MazeMDP-v0\", 1, seed=seed + 1, kwargs=MAZE)\n",
    "\n",
    "    actor = QTableActor(env.n_states, env.n_actions, epsilon=1.0)\n",
    "    collector = TransitionCollector(env, actor)\n",
    "    history = []\n",
    "    next_eval = 0\n",
    "    while collector.steps < total_steps:\n",
    "        batch = collector.collect(n_steps=1)\n",
    "        q_learning_update(actor.q, batch, alpha, gamma)\n",
    "        actor.epsilon = max(0.05, 1.0 - 2 * collector.steps / total_steps)\n",
    "\n",
    "        if collector.steps >= next_eval:\n",
    "            history.append((collector.steps, greedy_episode_length(actor, eval_env)))\n",
    "            next_eval += eval_every\n",
    "    return actor, history\n",
    "\n",
    "\n",
    "# Uses 8000 steps (600 in fast test mode)\n",
    "TOTAL_STEPS = Profile.pick(8_000, fast_test=600)\n",
    "actor, history = train_q_learning(num_envs=4, total_steps=TOTAL_STEPS)\n",
    "print(f\"greedy episode length: {history[0][1]:.0f} -> {history[-1][1]:.0f} steps\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2646029",
   "metadata": {},
   "outputs": [],
   "source": [
    "steps, lengths = zip(*history)\n",
    "plt.plot(steps, lengths)\n",
    "plt.xlabel(\"environment steps\")\n",
    "plt.ylabel(\"greedy episode length\")\n",
    "plt.title(\"Q-learning on the maze\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "693d9b32",
   "metadata": {},
   "source": [
    "The learned table can be drawn on the maze itself: $V(s) = \\max_a Q(s, a)$\n",
    "as colours, and the greedy policy as arrows. Since the maze is seeded, a\n",
    "fresh copy built for drawing is the very same maze the agent was trained\n",
    "on."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "331cb847",
   "metadata": {},
   "outputs": [],
   "source": [
    "maze = gym.make(\"MazeMDP-v0\", kwargs=MAZE, render_mode=\"human\").unwrapped\n",
    "maze.reset()\n",
    "maze.init_draw(\"The maze\")\n",
    "maze.draw_v_pi(\n",
    "    actor.q.max(-1).values.numpy(), actor.q.argmax(-1).numpy(), title=\"Q-learning\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d44db8d",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "This question is open-ended.\n",
    "\n",
    "**Exercise (parallel environments).** Train with 1, 4 and 16 environments\n",
    "for the same budget of environment steps and plot the three learning curves\n",
    "against the number of steps. Does running more copies make the *learning*\n",
    "faster, or only the *collection*? Give an argument: how many updates does\n",
    "each transition get, and how many transitions does each update see?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "36fbbb61",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compare the learning curves for several values of num_envs\n",
    "\n",
    "...\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05482a7e",
   "metadata": {},
   "source": [
    "**Exercise (other collectors).** The Q-learning update only needs\n",
    "transitions, so any of the three collectors can feed it, through the\n",
    "conversions of part 3 (`episode_to_transitions`, `rollout_to_transitions`).\n",
    "Try training with an `EpisodeCollector`, then with a `RolloutCollector`\n",
    "(mind the reset mode it demands), and compare the learning curves with the\n",
    "one above for the same number of environment steps. With episodes, try\n",
    "updating on the whole episode at once, then replaying it **backwards**,\n",
    "one transition at a time: what changes, and why?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e58faab",
   "metadata": {},
   "source": [
    "# 5. The same maze, three ways\n",
    "\n",
    "The maze below is *one* problem: an agent walking on a grid. What changes\n",
    "from one cell to the next is only **how a position is described** to the\n",
    "agent — and that choice is not neutral, as we saw with the Q-table above,\n",
    "which only works because it sees the state as a plain integer.\n",
    "\n",
    "The trick is a gymnasium `ObservationWrapper`: it declares a new\n",
    "observation space and translates each observation; `VecEnv` applies it to\n",
    "every copy. The maze always starts in the same cell here, so the three\n",
    "views below describe **the same state**: watch it turn into a number, then\n",
    "a vector of zeros and ones, then two coordinates."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2e2838d",
   "metadata": {},
   "source": [
    "### a. As a state number (the native view)\n",
    "\n",
    "The maze speaks `Discrete`: an observation is the index of the cell. `VecEnv`\n",
    "turns it into a tensor of **integers**, which can index a table directly —\n",
    "this is what the tabular algorithms use (and what part 4 does)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c19db62c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "env = VecEnv(\"MazeMDP-v0\", num_envs=1, seed=0, kwargs=MAZE)\n",
    "obs = env.reset()\n",
    "print(f\"observation: {obs}  {obs.dtype}\")\n",
    "print(f\"n_states = {env.n_states}, n_actions = {env.n_actions}\")\n",
    "\n",
    "# a table with one row per state, read with the observations themselves\n",
    "q_table = torch.zeros(env.n_states, env.n_actions)\n",
    "print(f\"q_table[obs] -> {tuple(q_table[obs].shape)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf7362f4",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### b. As a one-hot vector\n",
    "\n",
    "A neural network cannot take a state *number* as input: it would read an\n",
    "order and a distance into it that do not exist. The usual translation is a\n",
    "**one-hot** vector — as many components as states, all zero except a one at\n",
    "the index of the current state. Nothing is lost or gained, it is the same\n",
    "information, but the space becomes a `Box`. This wrapper is given; it is\n",
    "the model for the one you will write next."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d658f61",
   "metadata": {},
   "outputs": [],
   "source": [
    "class OneHotWrapper(gym.ObservationWrapper):\n",
    "    \"\"\"Present a `Discrete` observation as a one-hot `Box` vector\"\"\"\n",
    "\n",
    "    def __init__(self, env):\n",
    "        super().__init__(env)\n",
    "        self.n_states = env.observation_space.n\n",
    "        self.observation_space = gym.spaces.Box(\n",
    "            0.0, 1.0, shape=(self.n_states,), dtype=np.float32\n",
    "        )\n",
    "\n",
    "    def observation(self, obs):\n",
    "        one_hot = np.zeros(self.n_states, dtype=np.float32)\n",
    "        one_hot[obs] = 1.0\n",
    "        return one_hot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a63aa2dd",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "env = VecEnv(\"MazeMDP-v0\", num_envs=1, seed=0, kwargs=MAZE, wrappers=[OneHotWrapper])\n",
    "obs = env.reset()\n",
    "print(f\"observation: {tuple(obs.shape)}  {obs.dtype}\")\n",
    "print(f\"observation_dim = {env.observation_dim}\")\n",
    "print(obs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b31c534",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### c. As coordinates\n",
    "\n",
    "A third description: the $(x, y)$ position of the agent in the grid. Two\n",
    "numbers instead of `n_states`, and this time they *do* carry a geometry —\n",
    "two nearby cells have nearby coordinates, so a network can generalize from\n",
    "one to the other. The unwrapped environment gives the coordinates of every\n",
    "state in `coord_x` and `coord_y` (`env.unwrapped.coord_x[state]`). This\n",
    "wrapper is given; the next one is for you to write."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e0a0d9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "class CoordinatesWrapper(gym.ObservationWrapper):\n",
    "    \"\"\"Present a maze state as its $(x, y)$ position in the grid\"\"\"\n",
    "\n",
    "    def __init__(self, env):\n",
    "        super().__init__(env)\n",
    "        maze = env.unwrapped\n",
    "        # the coordinates are bounded by the extent of the grid\n",
    "        size = float(max(maze.coord_x.max(), maze.coord_y.max()))\n",
    "        self.observation_space = gym.spaces.Box(0.0, size, shape=(2,), dtype=np.float32)\n",
    "\n",
    "    def observation(self, obs):\n",
    "        maze = self.env.unwrapped\n",
    "        return np.array([maze.coord_x[obs], maze.coord_y[obs]], dtype=np.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cfedf38d",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = VecEnv(\n",
    "    \"MazeMDP-v0\", num_envs=1, seed=0, kwargs=MAZE, wrappers=[CoordinatesWrapper]\n",
    ")\n",
    "obs = env.reset()\n",
    "print(f\"observation: {tuple(obs.shape)}  {obs.dtype}\")\n",
    "print(obs)\n",
    "\n",
    "# take one step to the right and check that the coordinates move by one cell\n",
    "step = env.step(torch.tensor([1]))\n",
    "print(f\"after one step: {step.obs}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a22a6432",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "**Exercise.** Neural networks are happier with inputs of order 1. Write\n",
    "`NormalizedCoordinatesWrapper`, which returns the same two coordinates\n",
    "scaled between 0 and 1. Reuse `CoordinatesWrapper` (inherit from it) rather\n",
    "than starting over. Why is this normalization usually preferable as the\n",
    "input of a network?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69312f89",
   "metadata": {},
   "outputs": [],
   "source": [
    "class NormalizedCoordinatesWrapper(CoordinatesWrapper):\n",
    "    \"\"\"Present a maze state as its $(x, y)$ position, scaled in $[0, 1]$\"\"\"\n",
    "\n",
    "    def __init__(self, env):\n",
    "        super().__init__(env)\n",
    "        # The extent of the grid, and the new observation space\n",
    "\n",
    "        self.size = ...\n",
    "        self.observation_space = ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def observation(self, obs):\n",
    "        # Scale the coordinates returned by `CoordinatesWrapper`\n",
    "\n",
    "        # return ...\n",
    "        assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f1cf47a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "env = VecEnv(\n",
    "    \"MazeMDP-v0\",\n",
    "    num_envs=1,\n",
    "    seed=0,\n",
    "    kwargs=MAZE,\n",
    "    wrappers=[NormalizedCoordinatesWrapper],\n",
    ")\n",
    "print(f\"observation: {env.reset()}\")\n",
    "print(f\"space      : {env.observation_space}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02961fd1",
   "metadata": {},
   "source": [
    "Three descriptions, one problem. Keep in mind that the choice is **not**\n",
    "neutral: the state number makes tabular methods possible but forbids any\n",
    "generalization; the one-hot vector allows a network without giving it\n",
    "anything to generalize *with*; the coordinates make two neighbouring cells\n",
    "look alike, which is what allows an agent to learn something about a state\n",
    "it has never visited. Choosing what the agent sees is part of the problem,\n",
    "not a detail of implementation.\n",
    "\n",
    "(Real environments often go further and return several pieces at once — a\n",
    "racing game gives the kart's position, the items on the track, the engine\n",
    "state... gymnasium describes this with a `Dict` space, and `VecEnv` then\n",
    "returns a `TensorStruct`, one named tensor field per key. We will not need\n",
    "it in this course.)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f409b73",
   "metadata": {},
   "source": [
    "# What's next\n",
    "\n",
    "The table of part 4 has one row per state: it works because the maze is\n",
    "tiny and because the agent sees the *state number*. Give it the coordinate\n",
    "view of part 5c instead, and nothing indexes a table with two floats. The\n",
    "next session replaces the table with a neural network that takes such\n",
    "observations — Deep Q-Networks — and everything else in this notebook\n",
    "stays as it is: the same `VecEnv`, the same actors, the same\n",
    "`TransitionCollector`, the same `terminated` flag in the target."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "rl-mind",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "The infrastructure of the course, and a first tabular Q-learning agent",
   "practical_name": "Environments, actors and collectors"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
