{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4e0721b2",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we code a simple version of the DQN algorithm — **without**\n",
    "a replay buffer nor a target network — so as to better understand its inner\n",
    "mechanisms. The next notebook adds those two ingredients.\n",
    "\n",
    "The DQN algorithm is explained in [this\n",
    "video](https://www.youtube.com/watch?v=CXwvOMJujZk) and you can also read\n",
    "[the corresponding slides](http://pages.isir.upmc.fr/~sigaud/teach/dqn.pdf)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eda1b9a0",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "**On Colab**: run the installation cell below (generated automatically,\n",
    "pinned versions). **Locally**: install the environment with `uv sync`, no\n",
    "need for this cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "679380f7",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from dataclasses import dataclass, replace\n",
    "from torch import Tensor\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "from tqdm.auto import tqdm\n",
    "from rl_mind.profiles import Profile\n",
    "from rl_mind.core import Action, Actor\n",
    "from rl_mind.nn import build_mlp\n",
    "from rl_mind.env import VecEnv\n",
    "from rl_mind.data import Episode\n",
    "from rl_mind.collectors import EpisodeCollector\n",
    "from rl_mind.evaluation import Evaluator\n",
    "from rl_mind.notebook import run_directory, setup_tensorboard, silence_known_warnings\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bae4ca5",
   "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 a small set of *typed* helpers used\n",
    "throughout the RL notebooks. The ones used here:\n",
    "\n",
    "- `VecEnv` runs several copies of a gymnasium environment in parallel;\n",
    "- `Episode` stores one full episode (`obs` `[T, obs_dim]`, `action` `[T]`,\n",
    "  `reward` `[T]`, `final_obs`, `terminated`), plus `all_obs` `[T+1, obs_dim]`\n",
    "  — the observations $s_0, \\ldots, s_T$, i.e. `obs` with `final_obs`\n",
    "  appended;\n",
    "- `EpisodeCollector` runs an actor in a `VecEnv` and returns complete\n",
    "  `Episode`s;\n",
    "- `Evaluator` periodically evaluates an actor and keeps the best one;\n",
    "- `Actor` is the base class of the policies: `actor(obs)` is the\n",
    "  training-time (exploratory) behavior, `actor.act(obs)` the deterministic\n",
    "  (evaluation) one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1acaa29",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bf125c2",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# DQN\n",
    "\n",
    "[DQN](https://daiwk.github.io/assets/dqn.pdf) is a **critic-only** algorithm\n",
    "for discrete actions: a single network $Q(s, a)$ both estimates the action\n",
    "values and, through its argmax, defines the policy.\n",
    "\n",
    "## Definition of the agents\n",
    "\n",
    "### The Q-network\n",
    "\n",
    "The Q-network takes a state and outputs one value per action, $Q(s, \\cdot)$\n",
    "(so its output layer has `n_actions` neurons)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d0a0b67",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class DiscreteQNetwork(nn.Module):\n",
    "    \"\"\"The action-value network $Q(s, \\\\cdot)$ for discrete actions\"\"\"\n",
    "\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...], n_actions: int):\n",
    "        super().__init__()\n",
    "        self.model = build_mlp([obs_dim, *hidden, n_actions])\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Tensor:\n",
    "        \"\"\"Q-values for a batch of observations: `[B, obs_dim] -> [B, n_actions]`\"\"\"\n",
    "        return self.model(obs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4e387cb",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### The policy: $\\epsilon$-greedy exploration\n",
    "\n",
    "The policy is derived from the Q-network. Like Q-learning, DQN needs some\n",
    "exploration to avoid converging too early, so at training time we use\n",
    "**$\\epsilon$-greedy**: with probability $\\epsilon$ a random action, otherwise\n",
    "the greedy action $\\arg\\max_a Q(s, a)$. At evaluation time (`act`) we always\n",
    "take the greedy action.\n",
    "\n",
    "`QPolicy` is an `Actor`: it *wraps* the Q-network and turns its values into\n",
    "actions, so it can be handed to the collector and the evaluator directly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00852602",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class QPolicy(Actor[Action]):\n",
    "    \"\"\"An $\\\\epsilon$-greedy policy over a `DiscreteQNetwork`\"\"\"\n",
    "\n",
    "    def __init__(self, q_network: DiscreteQNetwork, epsilon: float):\n",
    "        super().__init__()\n",
    "        self.q_network = q_network\n",
    "        self.epsilon = epsilon\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        q_values = self.q_network(obs)\n",
    "        greedy = q_values.argmax(-1)\n",
    "        random = torch.randint(q_values.shape[-1], (obs.shape[0],))\n",
    "        explore = torch.rand(obs.shape[0]) < self.epsilon\n",
    "        return Action(value=torch.where(explore, random, greedy))\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        return self.q_network(obs).argmax(-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53f383c2",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The critic loss\n",
    "\n",
    "The `compute_critic_loss` function implements the Bellman backup. In\n",
    "Q-learning the update rule reads\n",
    "\n",
    "$$Q(s_t,a_t) \\leftarrow Q(s_t,a_t) + \\alpha\\,[\\, r_{t+1} + \\gamma \\max_a\n",
    "Q(s_{t+1},a) - Q(s_t,a_t)\\,]$$\n",
    "\n",
    "In DQN the $Q \\leftarrow Q + \\alpha[\\delta]$ step is replaced by a gradient\n",
    "step minimizing the squared temporal difference: we regress $Q(s_t, a_t)$\n",
    "towards the target $r_{t+1} + \\gamma \\max_a Q(s_{t+1}, a)$.\n",
    "\n",
    "Three points to get right:\n",
    "\n",
    "- the target uses $\\max_a Q(s_{t+1}, a)$, **detached** — we do not want the\n",
    "  gradient to flow through the target, only through $Q(s_t, a_t)$;\n",
    "- $Q(s_t, a_t)$ picks, among the `n_actions` outputs, the one for the action\n",
    "  that was actually played — that's what\n",
    "  [`torch.gather`](https://pytorch.org/docs/stable/generated/torch.gather.html)\n",
    "  (or fancy indexing) does;\n",
    "- the successors $s_1, \\ldots, s_T$ of the observations in `episode.obs` are\n",
    "  `episode.all_obs[1:]` — the last one, $s_T$, is `episode.final_obs`, which\n",
    "  is not in `episode.obs` since no action was taken there;\n",
    "- the value of that last successor must be dropped from the target when the\n",
    "  episode **terminated** (no future) — but kept when it was merely\n",
    "  *truncated* (a time limit: the agent could have continued)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "378bfa18",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_critic_loss(\n",
    "    gamma: float, episode: Episode, q_network: DiscreteQNetwork\n",
    ") -> Tensor:\n",
    "    \"\"\"Compute the DQN temporal-difference loss over one episode\n",
    "\n",
    "    :param gamma: The discount factor\n",
    "    :param episode: The episode (tensors of length `T`)\n",
    "    :param q_network: The Q-network (used for both $Q(s_t,a_t)$ and, detached,\n",
    "        the bootstrap $\\\\max_a Q(s_{t+1},a)$ — there is no target network yet)\n",
    "    :return: The critic loss (a scalar)\n",
    "    \"\"\"\n",
    "    # Compute the loss\n",
    "\n",
    "    # Q(s_t, a_t) for the actions that were played (gradient flows here)\n",
    "    q_values = ...\n",
    "    q_sa = ...\n",
    "    # max_a Q(s_{t+1}, a), detached; the successors of `obs` are `all_obs[1:]`\n",
    "    with torch.no_grad():\n",
    "        max_next_q = ...\n",
    "    # bootstrap is 0 for the last step iff the episode terminated\n",
    "    target = ...\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aed9cc49",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da9977a3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class DQNConfig:\n",
    "    env_name: str = \"CartPole-v1\"\n",
    "    seed: int = 3\n",
    "\n",
    "    #: Number of gradient updates\n",
    "    max_updates: int = Profile.pick(700, fast_test=20)\n",
    "    #: Number of parallel training environments\n",
    "    n_envs: int = 8\n",
    "    #: Episodes collected per update\n",
    "    episodes_per_update: int = 8\n",
    "\n",
    "    #: Exploration rate\n",
    "    epsilon: float = 0.1\n",
    "    #: Discount factor\n",
    "    gamma: float = 0.99\n",
    "    max_grad_norm: float = 0.5\n",
    "\n",
    "    hidden: tuple[int, ...] = (256, 256)\n",
    "    lr: float = 2e-3\n",
    "\n",
    "    #: Steps between two evaluations, and number of evaluation episodes\n",
    "    eval_interval: int = Profile.pick(5_000, fast_test=200)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6cd86746",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "The environments run **without** a replay buffer: each update collects a\n",
    "fresh batch of full episodes with the current $\\epsilon$-greedy policy,\n",
    "averages the per-episode critic loss and takes one gradient step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02e62b0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_dqn(cfg: DQNConfig) -> Evaluator:\n",
    "    \"\"\"Train a DQN agent (no replay buffer, no target network)\n",
    "\n",
    "    :param cfg: The hyper-parameters\n",
    "    :return: The evaluator, which holds the evaluation history and the best\n",
    "        policy found (`visualize_best()` shows it playing)\n",
    "    \"\"\"\n",
    "    # Fix the random seed so that two runs with the same `cfg` give the same\n",
    "    # result (network initialization, exploration, ...)\n",
    "    torch.manual_seed(cfg.seed)\n",
    "\n",
    "    # --- Setup\n",
    "\n",
    "    # `n_envs` copies of the environment, stepped together: the collector\n",
    "    # gathers episodes from all of them at once\n",
    "    env = VecEnv(cfg.env_name, cfg.n_envs, seed=cfg.seed)\n",
    "\n",
    "    # The Q-network: observation -> one Q-value per action\n",
    "    q_network = DiscreteQNetwork(env.observation_dim, cfg.hidden, env.n_actions)\n",
    "\n",
    "    # The epsilon-greedy policy *wraps* the Q-network (it does not copy it):\n",
    "    # each time the network is updated, the policy changes too\n",
    "    policy = QPolicy(q_network, cfg.epsilon)\n",
    "\n",
    "    # The optimizer updates the parameters of the Q-network (the only network\n",
    "    # we train here) from the gradient of the loss\n",
    "    optimizer = torch.optim.Adam(q_network.parameters(), lr=cfg.lr)\n",
    "\n",
    "    # The collector runs `policy` (training behavior, i.e. with exploration)\n",
    "    # in `env`, and returns full episodes\n",
    "    collector = EpisodeCollector(env, policy)\n",
    "\n",
    "    # Logging: a directory for this run, and a tensorboard writer in it (the\n",
    "    # curves appear in the tensorboard panel launched below)\n",
    "    run_dir = run_directory(f\"dqn-simple-{cfg.env_name}-S{cfg.seed}\")\n",
    "    writer = SummaryWriter(run_dir)\n",
    "\n",
    "    # The evaluator measures the *greedy* policy (`policy.act`, no\n",
    "    # exploration) every `eval_interval` steps, on its own environments (a\n",
    "    # different seed: we do not evaluate on the training episodes), and keeps\n",
    "    # a copy of the best policy so far\n",
    "    evaluator = Evaluator(\n",
    "        VecEnv(cfg.env_name, cfg.n_eval_envs, seed=cfg.seed + 100),\n",
    "        every=cfg.eval_interval,\n",
    "        run_dir=run_dir,\n",
    "        writer=writer,\n",
    "    )\n",
    "\n",
    "    # --- Training loop: one gradient update per iteration\n",
    "\n",
    "    pbar = tqdm(range(cfg.max_updates))  # a progress bar\n",
    "    for update in pbar:\n",
    "        # 1. Play `episodes_per_update` full episodes with the current policy\n",
    "        episodes = collector.collect(cfg.episodes_per_update)\n",
    "\n",
    "        # 2. The loss: the mean over the episodes of the per-episode TD loss\n",
    "        critic_loss = torch.stack(\n",
    "            [compute_critic_loss(cfg.gamma, ep, q_network) for ep in episodes]\n",
    "        ).mean()\n",
    "\n",
    "        # 3. One gradient step: reset the gradients (PyTorch accumulates them\n",
    "        # otherwise), back-propagate, clip the gradient norm (large gradients\n",
    "        # make DQN unstable), and update the parameters\n",
    "        optimizer.zero_grad()\n",
    "        critic_loss.backward()\n",
    "        torch.nn.utils.clip_grad_norm_(q_network.parameters(), cfg.max_grad_norm)\n",
    "        optimizer.step()\n",
    "\n",
    "        # 4. Log the loss, and evaluate if `eval_interval` steps have passed\n",
    "        # since the last evaluation (`result` is `None` otherwise). The x-axis\n",
    "        # is the number of environment steps, not of updates, so that\n",
    "        # algorithms that do not update at the same pace can be compared\n",
    "        writer.add_scalar(\"loss/critic\", critic_loss.item(), collector.steps)\n",
    "        if result := evaluator.run_if_needed(collector.steps, policy):\n",
    "            pbar.set_description(\n",
    "                f\"eval={result.mean:6.1f} best={evaluator.best_reward:6.1f}\"\n",
    "            )\n",
    "\n",
    "    return evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b97ce66",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9bd4b6db",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77176f00",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = DQNConfig()\n",
    "dqn = run_dqn(cfg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f7d88bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "dqn.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1fd01fff",
   "metadata": {},
   "source": [
    "## What's next?\n",
    "\n",
    "This simple version has no replay buffer and no target network — it is\n",
    "unstable and sample-inefficient. The next notebook (`03-2`) adds:\n",
    "\n",
    "- a **replay buffer** (learning from a stream of transitions rather than one\n",
    "  fresh batch of episodes);\n",
    "- a **target network** for the bootstrap (stabilizing the regression\n",
    "  target);\n",
    "- and, as an exercise, **Double-DQN** to fight the overestimation bias."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "rl-mind",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Deep Q-learning with neither replay buffer nor target network",
   "practical_name": "DQN, the bare algorithm"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
