{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3541417b",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook, we code the DDPG algorithm, and then you will extend it\n",
    "into TD3.\n",
    "\n",
    "The DDPG algorithm is explained in [this\n",
    "video](https://www.youtube.com/watch?v=0D6a0a1HTtc) and you can also read\n",
    "[the corresponding\n",
    "slides](http://pages.isir.upmc.fr/~sigaud/teach/ddpg.pdf)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a65560f2",
   "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": "75035d24",
   "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": "6f5efac8",
   "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",
    "import rl_mind.envs\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, soft_update\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": "44e67fcb",
   "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",
    "  using torch tensors;\n",
    "- `Transitions` is a batch of $(s, a, r, s', \\textrm{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 a copy of the best\n",
    "  one;\n",
    "- `Actor` is the base class of all the policies: `actor(obs)` returns an\n",
    "  `Action` (its training-time, exploratory behavior) while `actor.act(obs)`\n",
    "  returns the action tensor of its deterministic (evaluation) behavior;\n",
    "- `build_mlp` builds a multi-layer perceptron, and `soft_update` moves a\n",
    "  target network towards its online network (see *Target network update*\n",
    "  below)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad103294",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7240ef28",
   "metadata": {},
   "source": [
    "# DDPG\n",
    "\n",
    "The [DDPG](https://arxiv.org/pdf/1509.02971.pdf) algorithm is an\n",
    "*off-policy*, actor-critic algorithm for **continuous actions**: the data\n",
    "used for learning is sampled from a replay buffer that stores transitions\n",
    "$(s_t, a_t, r_{t+1}, s_{t+1})$ collected by an exploratory version of the\n",
    "current actor.\n",
    "\n",
    "An important detail: a transition also stores whether $s_{t+1}$ is a\n",
    "**terminal** state (`terminated`). When it is, the value of the future is\n",
    "zero and the critic target must not bootstrap; when the episode was merely\n",
    "*truncated* by a time limit, the agent could have continued and we do\n",
    "bootstrap. This is why the target is multiplied by `~batch.terminated`\n",
    "below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1181c1f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Definition of the agents\n",
    "\n",
    "### Critic $Q(s, a)$\n",
    "\n",
    "The critic is a neural network taking the state $s$ and action $a$ as\n",
    "input; its output is a single scalar, the value $Q(s,a)$ of performing $a$\n",
    "in $s$. It is a plain `torch.nn.Module`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03aff965",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class ContinuousQNetwork(nn.Module):\n",
    "    \"\"\"The Q-network $Q(s, a)$ for continuous actions\"\"\"\n",
    "\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...], action_dim: int):\n",
    "        super().__init__()\n",
    "        self.model = build_mlp([obs_dim + action_dim, *hidden, 1])\n",
    "\n",
    "    def forward(self, obs: Tensor, action: Tensor) -> Tensor:\n",
    "        \"\"\"Compute $Q(s, a)$ for a batch: `[B, obs_dim] x [B, action_dim] -> [B]`\"\"\"\n",
    "        return self.model(torch.cat([obs, action], dim=1)).squeeze(-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "060ca9a4",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Actor\n",
    "\n",
    "The actor is also a neural network; it takes a state $s$ as input and\n",
    "outputs an action $a = \\pi(s)$ in $[-1, 1]^d$ (note the final `tanh`). As\n",
    "it is deterministic, its training and evaluation behaviors coincide."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56600953",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class ContinuousDeterministicActor(Actor[Action]):\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...], action_dim: int):\n",
    "        \"\"\"Creates a new actor with continuous actions in `action_dim` dimensions.\n",
    "\n",
    "        :param obs_dim: The dimension of the observation space\n",
    "        :param hidden: A tuple of integers specifying the sizes of the hidden layers\n",
    "        :param action_dim: The dimension of the action space\n",
    "        \"\"\"\n",
    "        super().__init__()\n",
    "        self.model = build_mlp(\n",
    "            [obs_dim, *hidden, action_dim], output_activation=nn.Tanh()\n",
    "        )\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        return Action(value=self.model(obs))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2ca6898",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Exploration\n",
    "\n",
    "A deterministic actor does not explore. In the continuous action domain,\n",
    "the usual solution is to add Gaussian noise to the output of the actor.\n",
    "`GaussianNoise` *wraps* another actor: the noise is added at training time\n",
    "only (`forward`), while the evaluation behavior (`act`) is that of the\n",
    "wrapped actor.\n",
    "\n",
    "In [the original DDPG paper](https://arxiv.org/pdf/1509.02971.pdf), the\n",
    "authors rather used the more sophisticated Ornstein-Uhlenbeck noise, where\n",
    "the noise is correlated between one step and the next. As a follow-up, you\n",
    "could implement this strategy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0aaa54f4",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class GaussianNoise(Actor[Action]):\n",
    "    \"\"\"Adds Gaussian noise to the actions of another actor (at training time)\"\"\"\n",
    "\n",
    "    def __init__(self, actor: Actor[Action], sigma: float):\n",
    "        super().__init__()\n",
    "        self.actor = actor\n",
    "        self.sigma = sigma\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        action = self.actor(obs).value\n",
    "        return Action(value=action + self.sigma * torch.randn_like(action))\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        return self.actor.act(obs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19f47a5b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Losses\n",
    "\n",
    "### Critic loss\n",
    "\n",
    "The critic is learned by minimizing the squared temporal difference error\n",
    "over a batch of transitions sampled from the replay buffer:\n",
    "\n",
    "$$ L(\\phi) = \\mathbb{E}_{(s,a,r,s',d) \\sim \\mathcal{D}}\\left[ \\Big(\n",
    "Q_\\phi(s,a) - \\big(r + \\gamma\\, (1-d)\\, Q_{\\phi_\\text{targ}}(s',\n",
    "\\pi_\\theta(s')) \\big) \\Big)^2 \\right] $$\n",
    "\n",
    "where $d$ tells whether the episode is terminated in $s'$, $\\pi_\\theta$ is\n",
    "the (current) actor, and $Q_{\\phi_\\text{targ}}$ is the **target critic** (a\n",
    "slowly updated copy of the critic, which stabilizes learning). The target\n",
    "$r + \\gamma (1-d) Q_{\\phi_\\text{targ}}(s', \\pi_\\theta(s'))$ is treated as a\n",
    "constant: no gradient flows through it.\n",
    "\n",
    "Note the link with **Double DQN**: there, the online network *selects* the\n",
    "next action ($\\arg\\max_{a'} Q_\\phi(s', a')$) and the target network\n",
    "*evaluates* it. DDPG does the same, with the actor playing the role of the\n",
    "$\\arg\\max$: the current actor selects $a' = \\pi_\\theta(s')$ (it is trained\n",
    "to maximize $Q_\\phi$), and the target critic evaluates $Q_{\\phi_\\text{targ}}(s',\n",
    "a')$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19401a81",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_critic_loss(\n",
    "    gamma: float, batch: Transitions[Action], q_values: Tensor, next_q_values: Tensor\n",
    ") -> Tensor:\n",
    "    \"\"\"Compute the DDPG critic loss from a batch of transitions\n",
    "\n",
    "    :param gamma: The discount factor\n",
    "    :param batch: The batch of transitions\n",
    "    :param q_values: $Q(s_t, a_t)$ from the critic (shape `[B]`)\n",
    "    :param next_q_values: $Q'(s_{t+1}, \\\\pi(s_{t+1}))$ from the target critic\n",
    "        (shape `[B]`)\n",
    "    :return: The critic loss (a scalar)\n",
    "    \"\"\"\n",
    "    # Compute the target (do not bootstrap when `batch.terminated`), then the MSE loss\n",
    "\n",
    "    target = ...\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b3e17e1",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Actor loss\n",
    "\n",
    "The actor loss is straightforward: we want the actor to maximize the\n",
    "Q-values of its actions, thus we minimize the mean of negated Q-values:\n",
    "\n",
    "$$ L(\\theta) = -\\mathbb{E}_{s \\sim \\mathcal{D}}\\left[ Q_\\phi(s,\n",
    "\\pi_\\theta(s)) \\right] $$\n",
    "\n",
    "The gradient flows through the critic into the actor, but only the\n",
    "actor's parameters $\\theta$ are updated with this loss."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8500eacf",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_actor_loss(q_values: Tensor) -> Tensor:\n",
    "    \"\"\"Return the actor loss given $Q(s_t, \\\\pi(s_t))$ (shape `[B]`)\"\"\"\n",
    "    # Compute the actor loss\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60cefd31",
   "metadata": {},
   "source": [
    "### Target network update\n",
    "\n",
    "The target critic $Q_{\\phi_\\text{targ}}$ of the critic loss is not\n",
    "learned: if it were the critic itself, the target of the regression would\n",
    "move with every gradient step, and learning would chase its own tail. As in\n",
    "DQN, it is a *copy* of the critic, but rather than copying the critic every\n",
    "$K$ steps, DDPG lets the copy follow the critic slowly, after each update:\n",
    "\n",
    "$$ \\phi_\\text{targ} \\leftarrow \\tau\\, \\phi + (1 - \\tau)\\, \\phi_\\text{targ} $$\n",
    "\n",
    "This is a *soft* (or Polyak) update: with $\\tau = 0.05$ (`cfg.tau`), the\n",
    "target critic is an exponential moving average of the recent critics,\n",
    "about the last $1/\\tau = 20$ of them. $\\tau = 1$ would be a hard copy, and\n",
    "$\\tau \\to 0$ a target that never moves.\n",
    "\n",
    "`soft_update(source, target, tau)` from `rl_mind.nn` applies this formula\n",
    "to each parameter of `target`, in place and without tracking gradients\n",
    "([documentation](https://master-dac.isir.upmc.fr/rl/rl-mind/api/utilities.html#rl_mind.nn.soft_update)):\n",
    "\n",
    "```python\n",
    "with torch.no_grad():\n",
    "    for p, p_targ in zip(source.parameters(), target.parameters()):\n",
    "        p_targ.mul_(1 - tau).add_(tau * p)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5da09507",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters\n",
    "\n",
    "All the hyper-parameters of the algorithm are gathered in a small\n",
    "dataclass — typed, documented, with visible defaults."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23be0de3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class DDPGConfig:\n",
    "    env_name: str = \"CartPoleContinuous-v1\"\n",
    "    seed: int = 1\n",
    "\n",
    "    #: Total number of environment steps\n",
    "    max_steps: int = Profile.pick(30_000, fast_test=600)\n",
    "    #: Number of parallel training environments\n",
    "    n_envs: int = 1\n",
    "    #: Environment steps between two gradient updates\n",
    "    steps_per_update: int = 1\n",
    "    #: Steps before learning starts\n",
    "    learning_starts: int = Profile.pick(1_000, fast_test=100)\n",
    "\n",
    "    #: Replay buffer capacity\n",
    "    buffer_size: int = 200_000\n",
    "    batch_size: int = 64\n",
    "\n",
    "    #: Discount factor\n",
    "    gamma: float = 0.98\n",
    "    #: Target network update coefficient\n",
    "    tau: float = 0.05\n",
    "    #: Exploration noise\n",
    "    action_noise: float = 0.1\n",
    "\n",
    "    actor_hidden: tuple[int, ...] = (64, 64)\n",
    "    critic_hidden: tuple[int, ...] = (64, 64)\n",
    "    lr_actor: float = 1e-3\n",
    "    lr_critic: float = 1e-3\n",
    "\n",
    "    #: Steps between two evaluations, and number of evaluation episodes\n",
    "    eval_interval: int = Profile.pick(2_000, fast_test=200)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d5e4c10",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "Everything is now explicit: collect transitions, store them into the\n",
    "buffer, sample a batch, update the critic, update the actor, and update\n",
    "the target network. Note that:\n",
    "\n",
    "- the actions of the *next* states are recomputed with the current actor\n",
    "  (`actor(batch.next_obs)`) — the actions stored in the buffer are only\n",
    "  used for the critic update;\n",
    "- the target computation is wrapped in `torch.no_grad()`: gradients must\n",
    "  only flow through $Q_\\phi(s_t, a_t)$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e20c936d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_ddpg(cfg: DDPGConfig) -> Evaluator:\n",
    "    torch.manual_seed(cfg.seed)\n",
    "    env = VecEnv(cfg.env_name, cfg.n_envs, seed=cfg.seed)\n",
    "\n",
    "    # Create the actor, the critic and its target, and the optimizers\n",
    "\n",
    "    # `env.observation_dim` and `env.action_dim` contain the dimension of resp.\n",
    "    # the observation and action spaces\n",
    "    actor = ...\n",
    "    critic = ...\n",
    "    # the target critic is a copy of the critic (`copy.deepcopy`)\n",
    "    target_critic = ...\n",
    "    # one optimizer per network (`cfg.lr_actor`, `cfg.lr_critic`)\n",
    "    actor_optimizer = ...\n",
    "    critic_optimizer = ...\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    # Data collection (with exploration noise), replay buffer and evaluation\n",
    "    collector = TransitionCollector(env, GaussianNoise(actor, cfg.action_noise))\n",
    "    buffer = ReplayBuffer(cfg.buffer_size)\n",
    "    run_dir = run_directory(f\"ddpg-{cfg.env_name}-S{cfg.seed}\")\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=SummaryWriter(run_dir),\n",
    "    )\n",
    "\n",
    "    pbar = tqdm(total=cfg.max_steps)\n",
    "    while collector.steps < cfg.max_steps:\n",
    "        buffer.add(collector.collect(cfg.steps_per_update))\n",
    "        pbar.update(collector.steps - pbar.n)\n",
    "        if len(buffer) < cfg.learning_starts:\n",
    "            continue\n",
    "\n",
    "        batch = buffer.sample(cfg.batch_size)\n",
    "\n",
    "        # Q-values of the actions that were played (this is where gradients flow)\n",
    "\n",
    "        q_values = ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        with torch.no_grad():\n",
    "            # Q-values of the *current* actor's actions in the next states, from the target critic\n",
    "\n",
    "            # as in Double DQN: the actor selects the action, the target\n",
    "            # critic evaluates it\n",
    "            next_q_values = ...\n",
    "            assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Critic update: compute the loss, then a gradient step\n",
    "\n",
    "        critic_loss = ...\n",
    "        ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Actor update: maximize Q(s, pi(s)), with a gradient step on the actor only\n",
    "\n",
    "        actor_loss = ...\n",
    "        ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Soft update of the target critic (`soft_update`)\n",
    "\n",
    "        ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        evaluator.writer.add_scalar(\"loss/critic\", critic_loss.item(), collector.steps)\n",
    "        evaluator.writer.add_scalar(\"loss/actor\", actor_loss.item(), collector.steps)\n",
    "        if result := evaluator.run_if_needed(collector.steps, actor):\n",
    "            pbar.set_description(\n",
    "                f\"eval={result.mean:7.1f} best={evaluator.best_reward:7.1f}\"\n",
    "            )\n",
    "\n",
    "    pbar.close()\n",
    "    return evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13d7bdcd",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba555dbf",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "635311f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "ddpg_config = DDPGConfig()\n",
    "ddpg = run_ddpg(ddpg_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f1859f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "ddpg.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1616446",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# TD3\n",
    "\n",
    "Starting from the above version, you should code [the TD3\n",
    "algorithm](http://proceedings.mlr.press/v80/fujimoto18a/fujimoto18a.pdf).\n",
    "\n",
    "## Differences with DDPG\n",
    "\n",
    "There are three main differences between DDPG and TD3.\n",
    "\n",
    "### Clipped double-Q learning\n",
    "\n",
    "To fight the overestimation bias, the target value for the Bellman backup\n",
    "takes the min over two target critics:\n",
    "\n",
    "$$y(r, s', d) = r + \\gamma (1 - d) \\min_{i=1,2} {Q'}_{\\phi_{i,\n",
    "\\text{targ}}}(s', f(s')) \\qquad (1)$$\n",
    "\n",
    "where $d$ tells whether the episode is terminated and $f(s')$ is the value\n",
    "of some policy (see below) at state $s'$.\n",
    "\n",
    "Both Q-value estimators are learned using the following loss for $i \\in\n",
    "\\{1,2\\}$:\n",
    "\n",
    "$$L(\\phi_i, {\\mathcal D}) = \\mathbb{E}_{(s,a,r,s',d) \\sim {\\mathcal D}}\n",
    "{\\Bigg( Q_{\\phi_i}(s,a) - y(r,s',d) \\Bigg)^2}. \\qquad (2)$$\n",
    "\n",
    "### Target policy smoothing\n",
    "\n",
    "The original implementation of DDPG used a policy and a target policy, as\n",
    "for critics, though it makes little mathematical sense in the case of\n",
    "policies (it is not learned from a shifting regression problem). However,\n",
    "using a target policy was smoothing policy learning, which is good to\n",
    "fight instabilities but slows down performance. Further studies with DDPG\n",
    "showed that using this target policy was not consistently improving\n",
    "learning performance, and the mechanism was dropped in many standard\n",
    "implementations.\n",
    "\n",
    "As TD3 inherits from DDPG, the question of keeping the target policy is\n",
    "left open. It is kept in the paper and in the Stable Baselines 3\n",
    "implementation, so it seems like a good idea to keep it.\n",
    "\n",
    "The target policy is used to update the target value for both critics as\n",
    "in (2). In addition, the action from that target policy is smoothed with\n",
    "additional clipped noise, to make policy learning more robust. So, in (1)\n",
    "above, the function $f$ is given by:\n",
    "\n",
    "$$f(s') = \\pi_{\\theta_\\text{targ}}(s') + \\epsilon, \\quad \\text{where } \\epsilon \\sim\n",
    "\\text{clip}(\\mathcal{N}(0,\\sigma),-c,c)$$\n",
    "\n",
    "where $\\sigma$ is the target policy noise and $c$ is the target policy\n",
    "noise clip.\n",
    "\n",
    "### Delayed policy updates\n",
    "\n",
    "The policy is updated less frequently than the critics, using a\n",
    "`policy_delay` parameter.\n",
    "\n",
    "## Your job\n",
    "\n",
    "Implement `run_td3` below, starting from the DDPG loop above. There are\n",
    "exactly the three mechanisms described in the previous sections to add — and\n",
    "nothing else:\n",
    "\n",
    "1. **Clipped double-Q learning** — replace the single critic and its target\n",
    "   with two critics (`critic_1`, `critic_2`) and their two targets. Compute a\n",
    "   single target from the **minimum** of the two *target* critics, and\n",
    "   regress **both** critics towards it.\n",
    "2. **Target policy smoothing** — the next actions used in that target are\n",
    "   given by the *target actor*, perturbed by a Gaussian noise of standard\n",
    "   deviation `cfg.target_noise`, clipped to ±`cfg.target_noise_clip` (and the\n",
    "   resulting action clipped to the action range).\n",
    "3. **Delayed policy updates** — update the actor (by maximizing the Q-values\n",
    "   of `critic_1`) only every `cfg.policy_delay` gradient steps, and softly\n",
    "   update the three target networks at the same rate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f0696c89",
   "metadata": {},
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class TD3Config(DDPGConfig):\n",
    "    #: Number of critic updates between two policy updates\n",
    "    policy_delay: int = 2\n",
    "    #: Std of the noise added to the target policy actions\n",
    "    target_noise: float = 0.2\n",
    "    #: Clipping of the target policy noise\n",
    "    target_noise_clip: float = 0.5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccf8324e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_td3(cfg: TD3Config) -> Evaluator:\n",
    "    # Take the DDPG code (once done) and modify it\n",
    "\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "    return evaluator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a9cc776",
   "metadata": {},
   "outputs": [],
   "source": [
    "td3_config = TD3Config()\n",
    "td3 = run_td3(td3_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba403c95",
   "metadata": {},
   "outputs": [],
   "source": [
    "td3.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b689d0f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Experimental comparison\n",
    "\n",
    "The `history` of each `Evaluator` contains all the evaluations (steps and\n",
    "rewards), which we can use to compare the two algorithms: we plot the mean\n",
    "cumulated reward (± its standard deviation) along training, and run a\n",
    "Welch t-test on the final evaluations.\n",
    "\n",
    "As an exercise, take an environment where the overestimation bias may\n",
    "matter (e.g. `Pendulum-v1`), and compare the performance of DDPG and TD3.\n",
    "Visualize the Q-values long before convergence to see whether DDPG indeed\n",
    "overestimates them with respect to TD3."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee75918f",
   "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(ddpg=ddpg, td3=td3)\n",
    "\n",
    "# The Welch t-test tells us whether the difference between the final\n",
    "# evaluations is statistically significant (p-value < 0.05)\n",
    "welch = stats.ttest_ind(\n",
    "    ddpg.history[-1].rewards.numpy(), td3.history[-1].rewards.numpy(), equal_var=False\n",
    ")\n",
    "print(\n",
    "    f\"DDPG vs TD3 (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 deterministic actor for continuous actions, then its twin-critic successor",
   "practical_name": "DDPG and TD3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
