{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1ec38eda",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we implement a simple version of the A2C (Advantage\n",
    "Actor-Critic) algorithm.\n",
    "\n",
    "A2C is explained in [this video](https://www.youtube.com/watch?v=BUmsTlIgrBI)\n",
    "and you can also read [the corresponding\n",
    "slides](http://pages.isir.upmc.fr/~sigaud/teach/a2c.pdf)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d8409f0b",
   "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": "2231ef07",
   "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 Rollout\n",
    "from rl_mind.collectors import RolloutCollector\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": "a15f360a",
   "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",
    "- `Rollout` is a `[T, B]` segment of interaction (`obs`, `action`, `reward`,\n",
    "  `next_obs`, `terminated`, `truncated`), where `next_obs[t]` is the true\n",
    "  successor of `obs[t]`;\n",
    "- `RolloutCollector` runs an actor in a `VecEnv` and returns `Rollout`s;\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": "4c232fa0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fce776b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# A2C\n",
    "\n",
    "A2C is an *on-policy* actor-critic algorithm: it repeatedly collects a short\n",
    "rollout with the current policy and, from it, updates both a **policy**\n",
    "$\\pi_\\theta(a|s)$ and a **value function** $V(s)$. The value function provides\n",
    "a low-variance estimate of the advantage that weights the policy gradient.\n",
    "\n",
    "In this basic version the advantage is the one-step temporal-difference error\n",
    "\n",
    "$$\\delta_t = r_{t+1} + \\gamma\\, V(s_{t+1})\\,(1 - \\text{terminated}) - V(s_t)$$\n",
    "\n",
    "used both to train the critic (minimize $\\delta_t^2$) and to weight the\n",
    "policy gradient ($\\delta_t$ detached).\n",
    "\n",
    "## Definition of the agents\n",
    "\n",
    "### The policy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6cfa9505",
   "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",
    "        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": "8e59cded",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### The critic $V(s)$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18709e09",
   "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",
    "        return self.model(obs).squeeze(-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4a377b2",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The advantage\n",
    "\n",
    "The `compute_advantage` function returns the TD error $\\delta_t$ over the\n",
    "whole rollout. Two points:\n",
    "\n",
    "- the bootstrap term $V(s_{t+1})$ is dropped when $s_{t+1}$ is a **terminal**\n",
    "  state (multiply by `~terminated`);\n",
    "- $V(s_{t+1})$ is **detached** (`next_values` is computed under\n",
    "  `torch.no_grad()` below): the gradient of the critic loss must flow only\n",
    "  through $V(s_t)$, not through the target."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cf8250f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_advantage(\n",
    "    gamma: float, rollout: Rollout, values: Tensor, next_values: Tensor\n",
    ") -> Tensor:\n",
    "    \"\"\"Compute the one-step TD error $\\\\delta_t$ over a rollout\n",
    "\n",
    "    :param gamma: The discount factor\n",
    "    :param rollout: The rollout (tensors `[T, B]`)\n",
    "    :param values: $V(s_t)$, shape `[T, B]` (with gradient)\n",
    "    :param next_values: $V(s_{t+1})$, shape `[T, B]` (detached)\n",
    "    :return: The TD errors $\\\\delta_t$, shape `[T, B]`\n",
    "    \"\"\"\n",
    "    # Compute the TD error\n",
    "\n",
    "    target = ...   # r + gamma * V(s') * (not terminated)\n",
    "    return ...\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "230c6e45",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8354539",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class A2CConfig:\n",
    "    env_name: str = \"CartPole-v1\"\n",
    "    seed: int = 432\n",
    "\n",
    "    #: Number of rollouts (updates)\n",
    "    max_updates: int = Profile.pick(2_000, fast_test=100)\n",
    "    #: Number of parallel training environments\n",
    "    n_envs: int = 10\n",
    "    #: Rollout length (per environment)\n",
    "    n_steps: int = 16\n",
    "\n",
    "    #: Discount factor\n",
    "    gamma: float = 0.95\n",
    "    critic_coef: float = 1.0\n",
    "    actor_coef: float = 0.1\n",
    "    #: Entropy bonus (favours exploration; set to 0 to see the policy collapse)\n",
    "    entropy_coef: float = 1e-3\n",
    "    max_grad_norm: float = 0.5\n",
    "\n",
    "    actor_hidden: tuple[int, ...] = (32,)\n",
    "    critic_hidden: tuple[int, ...] = (32,)\n",
    "    lr: float = 1e-2\n",
    "\n",
    "    #: Steps between two evaluations, and number of evaluation episodes\n",
    "    eval_interval: int = Profile.pick(1_000, fast_test=200)\n",
    "    n_eval_envs: int = 20"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d611777",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "Each iteration collects one rollout and takes a **single** gradient step on\n",
    "the combined loss\n",
    "\n",
    "$$ \\mathcal{L} = c_v\\, \\mathcal{L}_{\\text{critic}} - c_a\\,\n",
    "\\mathcal{L}_{\\text{actor}} - c_e\\, \\mathcal{H}[\\pi] $$\n",
    "\n",
    "The policy log-probabilities are **recomputed** from the rollout (the ones\n",
    "stored during collection have no gradient)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f428ec5f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_a2c(cfg: A2CConfig) -> Evaluator:\n",
    "    torch.manual_seed(cfg.seed)\n",
    "    env = VecEnv(cfg.env_name, cfg.n_envs, seed=cfg.seed, same_step_reset=True)\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 = RolloutCollector(env, policy)\n",
    "    run_dir = run_directory(f\"a2c-{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",
    "        rollout = collector.collect(cfg.n_steps)\n",
    "\n",
    "        values = critic(rollout.obs)\n",
    "        with torch.no_grad():\n",
    "            next_values = critic(rollout.next_obs)\n",
    "        advantage = compute_advantage(cfg.gamma, rollout, values, next_values)\n",
    "\n",
    "        # Assemble the A2C loss\n",
    "\n",
    "        # critic: regress V(s_t) towards the TD target (minimize delta^2)\n",
    "        critic_loss = ...\n",
    "        # actor: policy gradient weighted by the (detached) advantage\n",
    "        dist = policy.dist(rollout.obs)\n",
    "        actor_loss = ...\n",
    "        entropy = ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        loss = (\n",
    "            cfg.critic_coef * critic_loss\n",
    "            - cfg.actor_coef * actor_loss\n",
    "            - cfg.entropy_coef * entropy\n",
    "        )\n",
    "\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        torch.nn.utils.clip_grad_norm_(\n",
    "            [*policy.parameters(), *critic.parameters()], cfg.max_grad_norm\n",
    "        )\n",
    "        optimizer.step()\n",
    "\n",
    "        writer.add_scalar(\"loss/critic\", critic_loss.item(), collector.steps)\n",
    "        writer.add_scalar(\"loss/actor\", actor_loss.item(), collector.steps)\n",
    "        writer.add_scalar(\"loss/entropy\", entropy.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": "e7affe4e",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43e7ceb2",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0e5f464",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = A2CConfig()\n",
    "a2c = run_a2c(cfg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f6114b06",
   "metadata": {},
   "outputs": [],
   "source": [
    "a2c.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "200105a6",
   "metadata": {},
   "source": [
    "## About the entropy bonus\n",
    "\n",
    "A2C is prone to *premature convergence*: the policy becomes deterministic too\n",
    "early, stops exploring, and its performance can then collapse. The entropy\n",
    "bonus $-c_e\\,\\mathcal{H}[\\pi]$ counteracts this by rewarding policies that\n",
    "keep some randomness.\n",
    "\n",
    "Try setting `entropy_coef=0` and compare — you should see the reward climb and\n",
    "then collapse. You can use\n",
    "[`torch.distributions.Categorical`](https://pytorch.org/docs/stable/distributions.html#categorical)`.entropy()`\n",
    "to compute the entropy of a discrete policy (as done above)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa326c58",
   "metadata": {},
   "outputs": [],
   "source": [
    "a2c_no_entropy = run_a2c(replace(cfg, entropy_coef=0.0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42b915d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(\n",
    "    [r.step for r in a2c.history],\n",
    "    [r.mean for r in a2c.history],\n",
    "    label=\"with entropy\",\n",
    ")\n",
    "plt.plot(\n",
    "    [r.step for r in a2c_no_entropy.history],\n",
    "    [r.mean for r in a2c_no_entropy.history],\n",
    "    label=\"no entropy\",\n",
    ")\n",
    "plt.xlabel(\"steps\")\n",
    "plt.ylabel(\"cumulated reward\")\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "A simple advantage actor-critic",
   "practical_name": "A2C, discrete actions"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
