{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "147dc09c",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we code a full version of the DQN algorithm, with a\n",
    "**replay buffer** and a **target network**, and then extend it into\n",
    "**Double-DQN**.\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).\n",
    "\n",
    "Compared with the previous notebook, we:\n",
    "\n",
    "- learn from a **replay buffer** of transitions instead of fresh episodes;\n",
    "- use a **target network** for the bootstrap;\n",
    "- use a better estimate of the maximum (**Double-DQN**)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3eca4c9",
   "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": "066be228",
   "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 matplotlib rl-mind==0.4.* scipy torch tqdm\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f24a137",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import copy\n",
    "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 scipy import stats\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 ReplayBuffer, Transitions\n",
    "from rl_mind.collectors import TransitionCollector\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": "26440a7a",
   "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",
    "- `Transitions` is a batch of $(s, a, r, s', \\text{terminated})$ tuples,\n",
    "  stored in a `ReplayBuffer`;\n",
    "- `TransitionCollector` runs an actor in a `VecEnv` and returns the\n",
    "  corresponding `Transitions`;\n",
    "- `Evaluator` periodically evaluates an actor and keeps the best one;\n",
    "- `Actor` is the base class of the policies (`actor(obs)` = training-time,\n",
    "  `actor.act(obs)` = deterministic evaluation)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31fc13f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ef5432f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# DQN\n",
    "\n",
    "## Definition of the agents\n",
    "\n",
    "The Q-network and the $\\epsilon$-greedy policy are unchanged from the\n",
    "previous notebook (`DiscreteQNetwork` outputs one value per action, `QPolicy`\n",
    "turns it into an $\\epsilon$-greedy actor)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2db28d11",
   "metadata": {},
   "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",
    "        return self.model(obs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4230446e",
   "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": "ba3a7994",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The critic loss\n",
    "\n",
    "Now that we learn from a **replay buffer**, the loss is computed on a flat\n",
    "batch of transitions $(s, a, r, s', \\text{terminated})$ — no time dimension,\n",
    "no masking. The DQN target uses the **target network** $Q_{\\theta'}$ for the\n",
    "bootstrap:\n",
    "\n",
    "$$ Y^{DQN} = r + \\gamma\\,(1-\\text{terminated})\\, \\max_a Q_{\\theta'}(s', a) $$\n",
    "\n",
    "and we regress the online $Q_\\theta(s, a)$ towards it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ae61b2e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_dqn_loss(\n",
    "    gamma: float,\n",
    "    batch: Transitions[Action],\n",
    "    q_network: DiscreteQNetwork,\n",
    "    target_network: DiscreteQNetwork,\n",
    ") -> Tensor:\n",
    "    \"\"\"Compute the DQN loss on a batch of transitions\n",
    "\n",
    "    :param gamma: The discount factor\n",
    "    :param batch: The batch of transitions\n",
    "    :param q_network: The online network $Q_\\\\theta$ — the gradient flows\n",
    "        through the $Q_\\\\theta(s, a)$ it computes\n",
    "    :param target_network: The target network $Q_{\\\\theta'}$, used for the\n",
    "        bootstrap only: its Q-values must be **detached**\n",
    "    :return: The critic loss (a scalar)\n",
    "    \"\"\"\n",
    "    # Compute the loss\n",
    "\n",
    "    q_values = ...         # Q(s, .) from the online network\n",
    "    q_sa = ...             # Q(s, a) for the played actions\n",
    "    # the bootstrap is detached: no gradient flows through the target\n",
    "    with torch.no_grad():\n",
    "        max_next_q = ...   # max_a Q_target(s', a)\n",
    "    target = ...           # do not bootstrap when batch.terminated\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af77d9f3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "769491bf",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class DQNConfig:\n",
    "    env_name: str = \"CartPole-v1\"\n",
    "    seed: int = 4\n",
    "\n",
    "    #: Total number of environment steps\n",
    "    max_steps: int = Profile.pick(100_000, fast_test=6_000)\n",
    "    #: Number of parallel training environments\n",
    "    n_envs: int = 8\n",
    "    #: Environment steps collected before each round of updates\n",
    "    steps_per_round: int = 32\n",
    "    #: Gradient updates per round\n",
    "    updates_per_round: int = 32\n",
    "    #: Steps before learning starts\n",
    "    learning_starts: int = Profile.pick(5_000, fast_test=500)\n",
    "\n",
    "    #: Replay buffer capacity, minibatch size\n",
    "    buffer_size: int = 100_000\n",
    "    batch_size: int = 256\n",
    "\n",
    "    #: Exploration rate\n",
    "    epsilon: float = 0.02\n",
    "    #: Discount factor\n",
    "    gamma: float = 0.99\n",
    "    #: Steps between two hard target-network updates\n",
    "    target_update_interval: int = 1_000\n",
    "    max_grad_norm: float = 0.5\n",
    "\n",
    "    hidden: tuple[int, ...] = (256, 256)\n",
    "    lr: float = 1e-3\n",
    "\n",
    "    #: Steps between two evaluations, and number of evaluation episodes\n",
    "    eval_interval: int = Profile.pick(2_000, fast_test=1_000)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afc89783",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "`compute_loss` is passed in so we can reuse the loop for both DQN and, later,\n",
    "Double-DQN: both take the same arguments (the batch and the two networks) and\n",
    "compute the Q-values they need themselves. The target network is a copy of\n",
    "the online network, refreshed (hard update) every `target_update_interval`\n",
    "steps."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70476026",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_dqn(cfg: DQNConfig, compute_loss, name: str = \"dqn\") -> Evaluator:\n",
    "    \"\"\"Train a DQN agent with a replay buffer and a target network\n",
    "\n",
    "    :param cfg: The hyper-parameters\n",
    "    :param compute_loss: The loss function, `compute_dqn_loss` or (later)\n",
    "        `compute_ddqn_loss`\n",
    "    :param name: The name of the run (for tensorboard)\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, sampling from the buffer)\n",
    "    torch.manual_seed(cfg.seed)\n",
    "\n",
    "    # --- Setup\n",
    "\n",
    "    # `n_envs` copies of the environment, stepped together\n",
    "    env = VecEnv(cfg.env_name, cfg.n_envs, seed=cfg.seed)\n",
    "\n",
    "    # The Q-network Q(s, .), and the target network: a *copy* of it (separate\n",
    "    # parameters), which only changes when we copy the Q-network into it again\n",
    "    # (see the end of the loop)\n",
    "    q_network = DiscreteQNetwork(env.observation_dim, cfg.hidden, env.n_actions)\n",
    "    target_network = copy.deepcopy(q_network)\n",
    "\n",
    "    # The epsilon-greedy policy *wraps* the Q-network (no copy here): each\n",
    "    # time the network is updated, the policy changes too\n",
    "    policy = QPolicy(q_network, cfg.epsilon)\n",
    "\n",
    "    # The optimizer only updates the Q-network: the target network is never\n",
    "    # trained, just copied\n",
    "    optimizer = torch.optim.Adam(q_network.parameters(), lr=cfg.lr)\n",
    "\n",
    "    # The collector runs `policy` (with exploration) in `env` and returns\n",
    "    # transitions (s, a, r, s', terminated) rather than full episodes; the\n",
    "    # replay buffer stores the last `buffer_size` of them\n",
    "    collector = TransitionCollector(env, policy)\n",
    "    buffer = ReplayBuffer(cfg.buffer_size)\n",
    "\n",
    "    # Logging: a directory for this run, and a tensorboard writer in it\n",
    "    run_dir = run_directory(f\"{name}-{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, and\n",
    "    # keeps 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 iteration = one round of collection + updates\n",
    "\n",
    "    last_target_update = 0\n",
    "    pbar = tqdm(total=cfg.max_steps)  # a progress bar, in environment steps\n",
    "    while collector.steps < cfg.max_steps:\n",
    "        # 1. Play `steps_per_round` steps with the current policy, and add\n",
    "        # the resulting transitions to the buffer\n",
    "        buffer.add(collector.collect(cfg.steps_per_round))\n",
    "        pbar.update(collector.steps - pbar.n)\n",
    "\n",
    "        # Do not learn before the buffer holds enough transitions: the first\n",
    "        # minibatches would otherwise be drawn from a handful of transitions,\n",
    "        # and the network would overfit them\n",
    "        if len(buffer) < cfg.learning_starts:\n",
    "            continue\n",
    "\n",
    "        # 2. Several gradient steps, each on a minibatch drawn at random from\n",
    "        # the buffer — mostly *old* transitions, played by earlier versions of\n",
    "        # the policy (DQN is off-policy, so this is fine), and uncorrelated\n",
    "        # (unlike the successive steps of an episode)\n",
    "        for _ in range(cfg.updates_per_round):\n",
    "            batch = buffer.sample(cfg.batch_size)\n",
    "            critic_loss = compute_loss(cfg.gamma, batch, q_network, target_network)\n",
    "\n",
    "            # Reset the gradients (PyTorch accumulates them otherwise),\n",
    "            # back-propagate, clip the gradient norm (large gradients make DQN\n",
    "            # 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",
    "        # 3. Hard update of the target network: every `target_update_interval`\n",
    "        # steps, copy the Q-network's parameters into it. In between, the\n",
    "        # regression target of the loss stays fixed, which stabilizes learning\n",
    "        if collector.steps - last_target_update > cfg.target_update_interval:\n",
    "            last_target_update = collector.steps\n",
    "            target_network.load_state_dict(q_network.state_dict())\n",
    "\n",
    "        # 4. Log the loss (of the last minibatch), and evaluate if\n",
    "        # `eval_interval` steps have passed since the last evaluation (`result`\n",
    "        # is `None` otherwise)\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",
    "    pbar.close()\n",
    "    return evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28743864",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a40d4e63",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15d7878c",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = DQNConfig()\n",
    "dqn = run_dqn(cfg, compute_dqn_loss, name=\"dqn\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1fcf6d90",
   "metadata": {},
   "outputs": [],
   "source": [
    "dqn.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8cc2b41a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Double-DQN\n",
    "\n",
    "In DQN the same (target) network both *selects* and *evaluates* the best next\n",
    "action in the target, which leads to overestimation: an action whose value is\n",
    "overestimated gets selected more often, slowing learning.\n",
    "\n",
    "**Double-DQN** decouples the two. The target\n",
    "\n",
    "$$Y^{DQN} = r + \\gamma\\, Q_{\\theta'}\\big(s', \\arg\\max_a Q_{\\theta'}(s', a)\\big)$$\n",
    "\n",
    "becomes\n",
    "\n",
    "$$Y^{DDQN} = r + \\gamma\\, Q_{\\theta'}\\big(s', \\arg\\max_a Q_{\\theta}(s', a)\\big)$$\n",
    "\n",
    "i.e. the **online** network $Q_\\theta$ selects the next action, while the\n",
    "**target** network $Q_{\\theta'}$ evaluates it.\n",
    "\n",
    "Write `compute_ddqn_loss` below: it has the same signature as\n",
    "`compute_dqn_loss`, and this time you need $Q_\\theta(s', \\cdot)$ *and*\n",
    "$Q_{\\theta'}(s', \\cdot)$ — both detached, since neither takes a gradient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4182d83",
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_ddqn_loss(\n",
    "    gamma: float,\n",
    "    batch: Transitions[Action],\n",
    "    q_network: DiscreteQNetwork,\n",
    "    target_network: DiscreteQNetwork,\n",
    ") -> Tensor:\n",
    "    \"\"\"Compute the Double-DQN loss on a batch of transitions\"\"\"\n",
    "    # Compute the loss\n",
    "\n",
    "    q_values = ...\n",
    "    q_sa = ...\n",
    "    # the online network selects the next action, the target network evaluates it\n",
    "    with torch.no_grad():\n",
    "        next_actions = ...\n",
    "        next_q = ...\n",
    "    target = ...\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98d27a2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "ddqn_cfg = replace(DQNConfig(), seed=3, hidden=(128, 128))\n",
    "ddqn = run_dqn(ddqn_cfg, compute_ddqn_loss, name=\"double-dqn\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7ddeab7",
   "metadata": {},
   "outputs": [],
   "source": [
    "ddqn.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c91e3e1",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Comparing DQN and Double-DQN\n",
    "\n",
    "We plot the two learning curves (mean cumulated reward ± std) and run a Welch\n",
    "t-test on the final evaluations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a3d5432",
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_evaluations(**evaluators: Evaluator):\n",
    "    for name, evaluator in evaluators.items():\n",
    "        steps = [result.step for result in evaluator.history]\n",
    "        means = torch.tensor([result.mean for result in evaluator.history])\n",
    "        stds = torch.tensor(\n",
    "            [float(result.rewards.std()) for result in evaluator.history]\n",
    "        )\n",
    "        (line,) = plt.plot(steps, means, label=name)\n",
    "        plt.fill_between(\n",
    "            steps, means - stds, means + stds, alpha=0.2, color=line.get_color()\n",
    "        )\n",
    "    plt.xlabel(\"steps\")\n",
    "    plt.ylabel(\"cumulated reward\")\n",
    "    plt.legend()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "plot_evaluations(dqn=dqn, ddqn=ddqn)\n",
    "\n",
    "welch = stats.ttest_ind(\n",
    "    dqn.history[-1].rewards.numpy(), ddqn.history[-1].rewards.numpy(), equal_var=False\n",
    ")\n",
    "print(\n",
    "    f\"DQN vs Double-DQN (final evaluation): t={welch.statistic:.2f}, p-value={welch.pvalue:.3f}\"\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "A replay buffer, a target network, and the step to Double-DQN",
   "practical_name": "DQN, complete"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
