{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "18ffcdb1",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook, we will implement the REINFORCE algorithm and several of\n",
    "its variants (discounted rewards, learned baselines).\n",
    "\n",
    "The REINFORCE algorithm is explained in a series of 3 videos: [video\n",
    "1](https://www.youtube.com/watch?v=R7ULMBXOQtE), [video\n",
    "2](https://www.youtube.com/watch?v=dKUWto9B9WY) and [video\n",
    "3](https://www.youtube.com/watch?v=GcJ9hl3T6x8). You can also read the\n",
    "corresponding slides:\n",
    "[slides1](http://pages.isir.upmc.fr/~sigaud/teach/ps/3_pg_derivation1.pdf),\n",
    "[slides2](http://pages.isir.upmc.fr/~sigaud/teach/ps/4_pg_derivation2.pdf),\n",
    "[slides3](http://pages.isir.upmc.fr/~sigaud/teach/ps/5_pg_derivation3.pdf)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ee15c5a",
   "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": "e878f1df",
   "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 Actor, StochasticAction\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": "337552e8",
   "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",
    "- `Episode` stores one full episode: `obs` (`[T, obs_dim]`), `action`\n",
    "  (tensors of shape `[T, ...]`), `reward` (`[T]`), the last observation\n",
    "  `final_obs` and whether the episode `terminated` (as opposed to being\n",
    "  truncated by a time limit); `all_obs` (`[T+1, obs_dim]`) is `obs` with\n",
    "  `final_obs` appended, i.e. the observations $s_0, \\ldots, s_T$;\n",
    "- `EpisodeCollector` runs an actor in a `VecEnv` and returns complete\n",
    "  `Episode`s;\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, stochastic behavior) while `actor.act(obs)`\n",
    "  returns the action tensor of its deterministic (evaluation) behavior."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ef625013",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9eed6680",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# REINFORCE\n",
    "\n",
    "[REINFORCE](https://link.springer.com/content/pdf/10.1007/BF00992696.pdf)\n",
    "is an *episodic*, *on-policy* policy-gradient algorithm: it collects full\n",
    "episodes with the current **stochastic** policy, and follows the gradient\n",
    "\n",
    "$$\n",
    "\\nabla_\\theta \\mathbb{E}_\\tau[R(\\tau)]\n",
    "\\approx\n",
    "\\frac{1}{m} \\sum_{i=1}^m \\sum_{t=0}^{H_i-1} A(s_t^{(i)})\\,\n",
    "\\nabla_\\theta \\log \\pi_\\theta(a_t^{(i)} | s_t^{(i)})\n",
    "$$\n",
    "\n",
    "with $m$ the number of episodes used to estimate the gradient, $H_i$ the\n",
    "length of episode $i$, and $A$ an *advantage* function whose different\n",
    "flavors (summed rewards, discounted rewards, with or without a baseline)\n",
    "are the subject of this notebook.\n",
    "\n",
    "## Definition of the agents\n",
    "\n",
    "### The policy\n",
    "\n",
    "The policy is a neural network that maps a state to a **distribution**\n",
    "over the (discrete) actions, using\n",
    "[`torch.distributions`](https://pytorch.org/docs/stable/distributions.html).\n",
    "During training (`forward`), the action is *sampled* from the\n",
    "distribution; during evaluation (`act`), we take the most probable action.\n",
    "\n",
    "Note that the returned `StochasticAction` also stores the log-probability\n",
    "of the sampled action."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "edea9ac8",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class DiscretePolicy(Actor[StochasticAction]):\n",
    "    \"\"\"A stochastic policy for discrete actions, $\\\\pi(a|s)$\"\"\"\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 dist(self, obs: Tensor) -> torch.distributions.Categorical:\n",
    "        \"\"\"The distribution over actions for a batch of observations\"\"\"\n",
    "        return torch.distributions.Categorical(logits=self.model(obs))\n",
    "\n",
    "    def forward(self, obs: Tensor) -> StochasticAction:\n",
    "        dist = self.dist(obs)\n",
    "        action = dist.sample()\n",
    "        return StochasticAction(value=action, log_prob=dist.log_prob(action))\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        return self.model(obs).argmax(-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e53da329",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### The critic $V(s)$\n",
    "\n",
    "The value network takes an observation as input and outputs the value\n",
    "$V(s)$ of this observation. It will be used as a *baseline* to reduce the\n",
    "variance of the gradient estimate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3eef95e3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class ValueNetwork(nn.Module):\n",
    "    \"\"\"The value network $V(s)$\"\"\"\n",
    "\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...]):\n",
    "        super().__init__()\n",
    "        self.model = build_mlp([obs_dim, *hidden, 1])\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Tensor:\n",
    "        \"\"\"Compute $V(s)$ for a batch: `[B, obs_dim] -> [B]`\"\"\"\n",
    "        return self.model(obs).squeeze(-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffdb7e92",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da031076",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class ReinforceConfig:\n",
    "    env_name: str = \"CartPole-v1\"\n",
    "    seed: int = 1\n",
    "\n",
    "    #: Number of gradient updates\n",
    "    max_updates: int = Profile.pick(700, fast_test=15)\n",
    "    #: Number of parallel training environments\n",
    "    n_envs: int = 8\n",
    "    #: Number of episodes collected for each update\n",
    "    episodes_per_update: int = 8\n",
    "\n",
    "    #: Discount factor\n",
    "    gamma: float = 0.99\n",
    "    #: Weight of the critic loss (when a baseline is learned)\n",
    "    critic_coef: float = 1.0\n",
    "\n",
    "    actor_hidden: tuple[int, ...] = (32,)\n",
    "    critic_hidden: tuple[int, ...] = (36,)\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=200)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13ecbfd9",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "The training loop is parametrized by the two functions that define the\n",
    "REINFORCE flavor:\n",
    "\n",
    "- `compute_advantage(cfg, episode, values)` computes the advantage\n",
    "  $A(s_t)$ at each step of an episode (a tensor of shape `[T]`). `values`\n",
    "  contains the critic values $V(s_0), \\ldots, V(s_T)$ — a tensor of shape\n",
    "  `[T+1]` that *includes the final observation* — and can be ignored by\n",
    "  the variants without a baseline;\n",
    "- `compute_critic_loss(cfg, episode, values)` computes the loss of the\n",
    "  critic (`None` when no baseline is learned).\n",
    "\n",
    "Note that the advantage is `.detach()`-ed in the policy loss: the policy\n",
    "gradient must not flow through the critic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3cf33ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_reinforce(\n",
    "    cfg: ReinforceConfig, variant: str, compute_advantage, compute_critic_loss=None\n",
    ") -> Evaluator:\n",
    "    torch.manual_seed(cfg.seed)\n",
    "    env = VecEnv(cfg.env_name, cfg.n_envs, seed=cfg.seed)\n",
    "\n",
    "    policy = DiscretePolicy(env.observation_dim, cfg.actor_hidden, env.n_actions)\n",
    "    critic = ValueNetwork(env.observation_dim, cfg.critic_hidden)\n",
    "    optimizer = torch.optim.Adam(\n",
    "        [*policy.parameters(), *critic.parameters()], lr=cfg.lr\n",
    "    )\n",
    "\n",
    "    collector = EpisodeCollector(env, policy)\n",
    "    run_dir = run_directory(f\"reinforce-{variant}-{cfg.env_name}-S{cfg.seed}\")\n",
    "    writer = SummaryWriter(run_dir)\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",
    "    pbar = tqdm(range(cfg.max_updates))\n",
    "    for update in pbar:\n",
    "        episodes = collector.collect(cfg.episodes_per_update)\n",
    "\n",
    "        step_losses: list[Tensor] = []\n",
    "        critic_losses: list[Tensor] = []\n",
    "        for episode in episodes:\n",
    "            # The values V(s_0) ... V(s_T): `all_obs` is `obs` with the final\n",
    "            # observation appended, so this vector has T+1 entries\n",
    "            values = critic(episode.all_obs)\n",
    "\n",
    "            # Compute the policy loss terms (one value per step) for this episode\n",
    "\n",
    "            # Compute the advantage...\n",
    "            advantage = ...\n",
    "            # ... and the log-probability of the actions that were played\n",
    "            # (`policy.dist(...)` gives the action distribution at each step)\n",
    "            log_probs = ...\n",
    "            step_losses.append(...)\n",
    "            assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "            if compute_critic_loss is not None:\n",
    "                critic_losses.append(compute_critic_loss(cfg, episode, values))\n",
    "\n",
    "        # Average over all the steps of all the episodes\n",
    "        loss = torch.cat(step_losses).mean()\n",
    "        writer.add_scalar(\"loss/actor\", loss.item(), collector.steps)\n",
    "        if critic_losses:\n",
    "            critic_loss = torch.stack(critic_losses).mean()\n",
    "            writer.add_scalar(\"loss/critic\", critic_loss.item(), collector.steps)\n",
    "            loss = loss + cfg.critic_coef * critic_loss\n",
    "\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\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": "3240d781",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9208c044",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "711678a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "params = ReinforceConfig()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4238858a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# First variant: summing all the rewards of the episode\n",
    "\n",
    "The most basic variant of the policy-gradient algorithms uses, at every\n",
    "step, the sum of *all* the rewards of the episode:\n",
    "$A(s_t) = \\sum_{k=1}^{H} r_k$.\n",
    "\n",
    "This is implemented by the `sum_of_rewards` function below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c92e7a8d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sum_of_rewards(cfg: ReinforceConfig, episode: Episode, values: Tensor) -> Tensor:\n",
    "    \"\"\"The advantage at each step is the total reward of the episode\"\"\"\n",
    "    return torch.full_like(episode.reward, episode.cumulated_reward)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "722b4573",
   "metadata": {},
   "outputs": [],
   "source": [
    "reinforce_sum = run_reinforce(params, \"sum\", sum_of_rewards)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f92d14e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "reinforce_sum.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60e8efae",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Exercises\n",
    "\n",
    "## Second variant: summing the discounted rewards to go\n",
    "\n",
    "As explained in the [second\n",
    "video](https://www.youtube.com/watch?v=dKUWto9B9WY) and [the corresponding\n",
    "slides](http://pages.isir.upmc.fr/~sigaud/teach/ps/4_pg_derivation2.pdf),\n",
    "using the *discounted* rewards *after* the current step (and ignoring the\n",
    "rewards before it) results in a lower variance:\n",
    "$A(s_t) = G_t = \\sum_{k=t}^{H-1} \\gamma^{k-t}\\, r_{k+1}$.\n",
    "\n",
    "By taking inspiration from the `sum_of_rewards` function above, code a\n",
    "`discounted_rewards_to_go` function.\n",
    "\n",
    "Hint: proceed *backwards*, starting from the last step of the episode\n",
    "($G_{H-1} = r_H$, then $G_t = r_{t+1} + \\gamma G_{t+1}$)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "372624cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def discounted_rewards_to_go(\n",
    "    cfg: ReinforceConfig, episode: Episode, values: Tensor\n",
    ") -> Tensor:\n",
    "    \"\"\"The advantage at each step is the discounted sum of future rewards $G_t$\"\"\"\n",
    "    # Implement the function (ignore `values`)\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8b7027b",
   "metadata": {},
   "outputs": [],
   "source": [
    "reinforce_discounted = run_reinforce(params, \"discounted\", discounted_rewards_to_go)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e74b3d82",
   "metadata": {},
   "outputs": [],
   "source": [
    "reinforce_discounted.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "095d0357",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Third variant: baseline learned with temporal differences\n",
    "\n",
    "We now reduce the variance further by subtracting a *baseline* from the\n",
    "rewards to go: the value $V(s_t)$ estimated by the critic,\n",
    "$A(s_t) = G_t - V(s_t)$.\n",
    "\n",
    "Code the `discounted_rewards_minus_baseline` function (remember that\n",
    "`values` has shape `[T+1]`: it includes the value of the final\n",
    "observation)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed98fe01",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def discounted_rewards_minus_baseline(\n",
    "    cfg: ReinforceConfig, episode: Episode, values: Tensor\n",
    ") -> Tensor:\n",
    "    # Implement the function\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ed1d5ae",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "The critic itself is learned simultaneously, here with **temporal\n",
    "differences**: $V(s_t)$ is regressed towards the target\n",
    "$r_{t+1} + \\gamma V(s_{t+1})$.\n",
    "\n",
    "Two important details:\n",
    "\n",
    "- The target is computed with `values[1:].detach()`: we want to apply\n",
    "  gradient descent on $V(s_t)$ towards the target, *not* to move the\n",
    "  target itself. In practice, `x.detach()` detaches a tensor from the\n",
    "  computation graph, so no gradient flows through it.\n",
    "- The trick to deal with terminal states: if the final state of the\n",
    "  episode is terminal, $V(s_T)$ does not make sense (there is no future),\n",
    "  so its target contribution must be ignored — we multiply the last value\n",
    "  by 0 in that case. If the episode was *truncated* (time limit), the\n",
    "  agent could have continued and we keep bootstrapping. This trick is used\n",
    "  in many RL libraries, e.g. SB3.\n",
    "\n",
    "Code the `td_critic_loss` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "06f3f563",
   "metadata": {},
   "outputs": [],
   "source": [
    "def td_critic_loss(cfg: ReinforceConfig, episode: Episode, values: Tensor) -> Tensor:\n",
    "    \"\"\"Mean squared temporal-difference error of the critic over one episode\"\"\"\n",
    "    # Implement the function\n",
    "\n",
    "    # `bootstrap` is 0 for the last step if the episode terminated, 1 elsewhere\n",
    "    bootstrap = ...\n",
    "    target = ...\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2275fbf2",
   "metadata": {},
   "outputs": [],
   "source": [
    "reinforce_td = run_reinforce(\n",
    "    params, \"td\", discounted_rewards_minus_baseline, td_critic_loss\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae16bbb1",
   "metadata": {},
   "outputs": [],
   "source": [
    "reinforce_td.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e0c1ec1",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Fourth variant: Monte-Carlo baseline\n",
    "\n",
    "The `td_critic_loss` function above uses the temporal-difference approach\n",
    "to critic estimation. In this part, we compare it to the **Monte-Carlo**\n",
    "estimation approach.\n",
    "\n",
    "As explained in [this video](https://www.youtube.com/watch?v=GcJ9hl3T6x8)\n",
    "and [these\n",
    "slides](http://pages.isir.upmc.fr/~sigaud/teach/ps/5_pg_derivation3.pdf),\n",
    "the MC approach directly regresses $V(s_t)$ towards the discounted rewards\n",
    "to go:\n",
    "\n",
    "$$\\phi_{j+1} = \\mathop{\\mathrm{argmin}}_{\\phi} \\frac{1}{m\\times H}\n",
    "\\sum_{i=1}^m \\sum_{t=0}^{H-1} \\left( G_t^{(i)} -\n",
    "\\hat{V}^\\pi_{\\phi}(s_t^{(i)}) \\right)^2 $$\n",
    "\n",
    "The inner sum of discounted rewards is exactly what\n",
    "`discounted_rewards_to_go` computes; the rest is a mean squared error.\n",
    "Code the `mc_critic_loss` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd8c57a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def mc_critic_loss(cfg: ReinforceConfig, episode: Episode, values: Tensor) -> Tensor:\n",
    "    \"\"\"Mean squared Monte-Carlo error of the critic over one episode\"\"\"\n",
    "    # Implement the function\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9cba6429",
   "metadata": {},
   "outputs": [],
   "source": [
    "reinforce_mc = run_reinforce(\n",
    "    params, \"mc\", discounted_rewards_minus_baseline, mc_critic_loss\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5cbbed2",
   "metadata": {},
   "outputs": [],
   "source": [
    "reinforce_mc.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3befa3f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Comparing the variants\n",
    "\n",
    "The `history` of each `Evaluator` contains all the evaluations, which we\n",
    "can plot to compare the variants.\n",
    "\n",
    "Most probably, the Monte-Carlo variant will not work as well: initially,\n",
    "the learned critic is a poor estimate of the true $V(s)$, and regressing\n",
    "directly towards noisy full returns is a slowly-converging objective."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3794289",
   "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(\n",
    "    sum=reinforce_sum,\n",
    "    discounted=reinforce_discounted,\n",
    "    td=reinforce_td,\n",
    "    mc=reinforce_mc,\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "The policy gradient and its variants: discounted rewards, learned baselines",
   "practical_name": "REINFORCE"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
