{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ffcf2599",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we implement A2C for **continuous** actions, with several\n",
    "kinds of Gaussian policies and the Generalized Advantage Estimation (GAE).\n",
    "\n",
    "A2C is explained in [this video](https://www.youtube.com/watch?v=BUmsTlIgrBI)\n",
    "and [these slides](http://pages.isir.upmc.fr/~sigaud/teach/a2c.pdf); GAE is\n",
    "introduced in [Schulman et al.](https://arxiv.org/pdf/1506.02438.pdf)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc74f6b5",
   "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": "fbe45051",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import rl_mind.envs\n",
    "from abc import ABC, abstractmethod\n",
    "from dataclasses import dataclass, replace\n",
    "from torch import Tensor\n",
    "from torch.distributions import Distribution, Independent, Normal\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": "b6b5b5c1",
   "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 the typed helpers used throughout the\n",
    "RL notebooks. This one uses\n",
    "`VecEnv`, `Rollout` / `RolloutCollector` (a `[T, B]` on-policy segment),\n",
    "`Evaluator`, and the `Actor` base class. Importing `rl_mind.envs` registers\n",
    "the continuous `CartPoleContinuous-v1` environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a28ba534",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d901266",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Continuous Gaussian policies\n",
    "\n",
    "For continuous actions the policy outputs a **Gaussian distribution**\n",
    "$\\mathcal{N}(\\mu, \\Sigma)$ over actions, from which actions are sampled. The\n",
    "mean $\\mu$ always depends on the state; the variants below differ in how the\n",
    "(diagonal) covariance is parameterized.\n",
    "\n",
    "The common `GaussianPolicy` base implements sampling (`forward`) and the\n",
    "deterministic behavior (`act` returns the mean); each subclass only provides\n",
    "`dist(obs)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9facc310",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class GaussianPolicy(Actor[StochasticAction], ABC):\n",
    "    \"\"\"Base class for continuous Gaussian policies\"\"\"\n",
    "\n",
    "    @abstractmethod\n",
    "    def dist(self, obs: Tensor) -> Distribution:\n",
    "        \"\"\"The action distribution for a batch of observations\"\"\"\n",
    "        ...\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.dist(obs).mean"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb1f4c93",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Constant variance\n",
    "\n",
    "The simplest case: an isotropic Gaussian with a **fixed** standard deviation.\n",
    "`Independent(Normal(mean, std), 1)` turns the per-dimension Gaussians into one\n",
    "multivariate distribution with diagonal covariance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14704248",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class ConstantVarianceActor(GaussianPolicy):\n",
    "    def __init__(\n",
    "        self, obs_dim: int, hidden: tuple[int, ...], action_dim: int, std: float = 2.0\n",
    "    ):\n",
    "        super().__init__()\n",
    "        self.model = build_mlp([obs_dim, *hidden, action_dim])\n",
    "        self.std = std\n",
    "\n",
    "    def dist(self, obs: Tensor) -> Distribution:\n",
    "        return Independent(Normal(self.model(obs), self.std), 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c825c4b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Tunable variance\n",
    "\n",
    "Here the standard deviation is a **learned parameter**, but still independent\n",
    "of the state (uniform stochasticity over the state space). A `softplus`\n",
    "ensures it stays positive: $\\sigma = \\log(1 + e^{\\theta})$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc106a55",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class TunableVarianceActor(GaussianPolicy):\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...], action_dim: int):\n",
    "        super().__init__()\n",
    "        self.model = build_mlp([obs_dim, *hidden, action_dim])\n",
    "        self.std_param = nn.Parameter(torch.randn(action_dim))\n",
    "        self.softplus = nn.Softplus()\n",
    "\n",
    "    def dist(self, obs: Tensor) -> Distribution:\n",
    "        std = self.softplus(self.std_param)\n",
    "        return Independent(Normal(self.model(obs), std), 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfd60923",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### State-dependent variance\n",
    "\n",
    "The most expressive (and most common) case: both the mean **and** the\n",
    "standard deviation are predicted from the state, sharing a *backbone*\n",
    "network. Beware: networks initialize near 0, so an initial std near 0 gives\n",
    "almost no exploration — the entropy bonus (below) keeps it reasonable.\n",
    "\n",
    "**Exercise**: complete the mean/std heads and the distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0955e430",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class StateDependentVarianceActor(GaussianPolicy):\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...], action_dim: int):\n",
    "        super().__init__()\n",
    "        self.backbone = build_mlp([obs_dim, *hidden])\n",
    "        # Add the mean and (pre-softplus) std heads\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "        self.softplus = nn.Softplus()\n",
    "\n",
    "    def dist(self, obs: Tensor) -> Distribution:\n",
    "        # Compute the mean and std from the backbone output\n",
    "\n",
    "        features = ...\n",
    "        mean = ...\n",
    "        std = ...\n",
    "        assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "365ff8f0",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### The critic $V(s)$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2d2d7d0",
   "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": "0b0bb3ab",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Generalized Advantage Estimation\n",
    "\n",
    "This time the advantage is the GAE, a $\\lambda$-weighted average of $n$-step\n",
    "TD errors that trades off bias and variance ($\\lambda = 1$ recovers the plain\n",
    "A2C advantage). It is the same recursion used in the PPO notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3330b19a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_gae(\n",
    "    gamma: float, lam: float, rollout: Rollout, values: Tensor, next_values: Tensor\n",
    ") -> Tensor:\n",
    "    \"\"\"Compute the GAE advantages over a rollout (tensors `[T, B]`)\"\"\"\n",
    "    advantages = torch.zeros_like(rollout.reward)\n",
    "    gae = torch.zeros_like(rollout.reward[0])\n",
    "    for t in reversed(range(rollout.reward.shape[0])):\n",
    "        delta = (\n",
    "            rollout.reward[t]\n",
    "            + gamma * next_values[t] * (~rollout.terminated[t]).float()\n",
    "            - values[t]\n",
    "        )\n",
    "        gae = delta + gamma * lam * (~rollout.done[t]).float() * gae\n",
    "        advantages[t] = gae\n",
    "    return advantages"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e886c31",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2f89d61",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "ACTORS = {\n",
    "    \"constant\": ConstantVarianceActor,\n",
    "    \"tunable\": TunableVarianceActor,\n",
    "    \"state-dependent\": StateDependentVarianceActor,\n",
    "}\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class A2CConfig:\n",
    "    env_name: str = \"CartPoleContinuous-v1\"\n",
    "    seed: int = 4\n",
    "    #: Which Gaussian policy to use (key of `ACTORS`)\n",
    "    actor: str = \"constant\"\n",
    "\n",
    "    #: Number of rollouts (updates)\n",
    "    max_updates: int = Profile.pick(2_000, fast_test=20)\n",
    "    #: Number of parallel training environments\n",
    "    n_envs: int = 8\n",
    "    #: Rollout length (per environment)\n",
    "    n_steps: int = 16\n",
    "\n",
    "    #: Discount factor and GAE lambda\n",
    "    gamma: float = 0.95\n",
    "    gae_lam: float = 0.8\n",
    "    critic_coef: float = 1.0\n",
    "    actor_coef: float = 0.1\n",
    "    entropy_coef: float = 1e-3\n",
    "    max_grad_norm: float = 0.5\n",
    "\n",
    "    actor_hidden: tuple[int, ...] = (25, 25)\n",
    "    critic_hidden: tuple[int, ...] = (24, 36)\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=100)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b62696e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "As in the basic version, each iteration collects one rollout and takes a\n",
    "single gradient step; the difference is the GAE advantage and the continuous\n",
    "Gaussian policy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c78c30e",
   "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 = ACTORS[cfg.actor](env.observation_dim, cfg.actor_hidden, env.action_dim)\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.actor}-{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",
    "        with torch.no_grad():\n",
    "            values_ng = critic(rollout.obs)\n",
    "            next_values = critic(rollout.next_obs)\n",
    "            advantage = compute_gae(\n",
    "                cfg.gamma, cfg.gae_lam, rollout, values_ng, next_values\n",
    "            )\n",
    "            returns = advantage + values_ng\n",
    "\n",
    "        # critic regresses V(s_t) towards the lambda-returns\n",
    "        values = critic(rollout.obs)\n",
    "        critic_loss = ((returns - values) ** 2).mean()\n",
    "\n",
    "        # actor: policy gradient weighted by the (detached) advantage\n",
    "        dist = policy.dist(rollout.obs)\n",
    "        log_probs = dist.log_prob(rollout.action.value)\n",
    "        actor_loss = (log_probs * advantage).mean()\n",
    "        entropy = dist.entropy().mean()\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": "9e20c0e8",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e0457ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f03c82d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = A2CConfig(actor=\"constant\")\n",
    "a2c = run_a2c(cfg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7f60ea21",
   "metadata": {},
   "outputs": [],
   "source": [
    "a2c.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c55efe7",
   "metadata": {},
   "source": [
    "## Exercise: compare the three policies\n",
    "\n",
    "Run A2C with the `tunable` and `state-dependent` actors and compare their\n",
    "learning curves against the constant-variance one."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Gaussian policies and Generalized Advantage Estimation",
   "practical_name": "A2C, continuous actions"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
