{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "270923ad",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we run PPO-clip on a **continuous** action space, using a\n",
    "Gaussian policy. It is the continuous counterpart of `07-2`; the algorithm is\n",
    "unchanged — only the policy differs.\n",
    "\n",
    "See the [PPO paper](https://arxiv.org/pdf/1707.06347.pdf), [these\n",
    "slides](http://pages.isir.upmc.fr/~sigaud/teach/ps/10_ppo.pdf) and [The 37\n",
    "implementation details of\n",
    "PPO](https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2486201",
   "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": "48452d52",
   "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.* torch tqdm\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57896e98",
   "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",
    "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, TensorStruct\n",
    "from rl_mind.nn import build_mlp\n",
    "from rl_mind.env import VecEnv\n",
    "from rl_mind.data import Rollout, minibatches\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": "de61a27e",
   "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`, `minibatches`, `Evaluator`, and the\n",
    "`Actor` base class. Importing `rl_mind.envs` registers `CartPoleContinuous-v1`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "255b022a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d13194a3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Continuous Gaussian policies\n",
    "\n",
    "For continuous actions the policy outputs a Gaussian $\\mathcal{N}(\\mu,\n",
    "\\Sigma)$ over actions. We reuse the three variants introduced in the A2C\n",
    "notebook (`06-2`): constant, tunable and state-dependent variance. The\n",
    "`GaussianPolicy` base samples in `forward` and returns the mean in `act`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b77f631b",
   "metadata": {},
   "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": "code",
   "execution_count": null,
   "id": "c5883a6d",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ConstantVarianceActor(GaussianPolicy):\n",
    "    def __init__(\n",
    "        self, obs_dim: int, hidden: tuple[int, ...], action_dim: int, std: float = 1.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": "code",
   "execution_count": null,
   "id": "da50ce84",
   "metadata": {},
   "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.zeros(action_dim))\n",
    "        self.softplus = nn.Softplus()\n",
    "\n",
    "    def dist(self, obs: Tensor) -> Distribution:\n",
    "        return Independent(Normal(self.model(obs), self.softplus(self.std_param)), 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3ac8dae",
   "metadata": {},
   "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",
    "        self.mean_layer = nn.Linear(hidden[-1], action_dim)\n",
    "        self.std_layer = nn.Linear(hidden[-1], action_dim)\n",
    "        self.softplus = nn.Softplus()\n",
    "\n",
    "    def dist(self, obs: Tensor) -> Distribution:\n",
    "        features = self.backbone(obs)\n",
    "        std = self.softplus(self.std_layer(features))\n",
    "        return Independent(Normal(self.mean_layer(features), std), 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "351d17d1",
   "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": "3e1fc24e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## GAE and the training data\n",
    "\n",
    "Identical to PPO-clip (`07-2`); the only difference below is that the stored\n",
    "actions are continuous vectors (`[N, action_dim]`) instead of discrete\n",
    "indices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80c13915",
   "metadata": {},
   "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": "code",
   "execution_count": null,
   "id": "4c683e00",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class PPOBatch(TensorStruct):\n",
    "    \"\"\"The data PPO trains on (all shapes `[N, ...]`)\"\"\"\n",
    "\n",
    "    obs: Tensor\n",
    "    action: Tensor\n",
    "    old_log_prob: Tensor\n",
    "    advantage: Tensor\n",
    "    returns: Tensor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b14272de",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a556e20b",
   "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 PPOConfig:\n",
    "    env_name: str = \"CartPoleContinuous-v1\"\n",
    "    seed: int = 12\n",
    "    actor: str = \"state-dependent\"\n",
    "\n",
    "    max_updates: int = Profile.pick(300, fast_test=5)\n",
    "    n_envs: int = 8\n",
    "    n_steps: int = 32\n",
    "\n",
    "    gamma: float = 0.98\n",
    "    gae_lam: float = 0.8\n",
    "\n",
    "    epsilon: float = 0.2\n",
    "    opt_epochs: int = 10\n",
    "    batch_size: int = 256\n",
    "    normalize_advantage: bool = True\n",
    "    entropy_coef: float = 0.0\n",
    "\n",
    "    actor_hidden: tuple[int, ...] = (64, 64)\n",
    "    critic_hidden: tuple[int, ...] = (64, 64)\n",
    "    lr: float = 1e-3\n",
    "\n",
    "    eval_interval: int = Profile.pick(8_000, fast_test=1_000)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc4ebd91",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "The clipped-surrogate policy loss is exactly the one from `07-2` — the\n",
    "continuous Gaussian policy provides `dist(obs)`, `.log_prob` and `.entropy`\n",
    "just like the discrete one, so nothing else changes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0df7f34",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_ppo_clip(cfg: PPOConfig) -> 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",
    "    policy_optimizer = torch.optim.Adam(policy.parameters(), lr=cfg.lr)\n",
    "    critic_optimizer = torch.optim.Adam(critic.parameters(), lr=cfg.lr)\n",
    "\n",
    "    collector = RolloutCollector(env, policy)\n",
    "    run_dir = run_directory(f\"ppo-clip-{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 = critic(rollout.obs)\n",
    "            next_values = critic(rollout.next_obs)\n",
    "            advantage = compute_gae(\n",
    "                cfg.gamma, cfg.gae_lam, rollout, values, next_values\n",
    "            )\n",
    "\n",
    "        flat = rollout.flatten()\n",
    "        data = PPOBatch(\n",
    "            obs=flat.obs,\n",
    "            action=flat.action.value,\n",
    "            old_log_prob=flat.action.log_prob,\n",
    "            advantage=advantage.flatten(),\n",
    "            returns=(advantage + values).flatten(),\n",
    "        )\n",
    "\n",
    "        for epoch in range(cfg.opt_epochs):\n",
    "            for mb in minibatches(data, cfg.batch_size):\n",
    "                dist = policy.dist(mb.obs)\n",
    "                ratio = (dist.log_prob(mb.action) - mb.old_log_prob).exp()\n",
    "\n",
    "                advantage_mb = mb.advantage\n",
    "                if cfg.normalize_advantage:\n",
    "                    advantage_mb = (advantage_mb - advantage_mb.mean()) / (\n",
    "                        advantage_mb.std() + 1e-8\n",
    "                    )\n",
    "\n",
    "                policy_loss = -torch.minimum(\n",
    "                    ratio * advantage_mb,\n",
    "                    torch.clamp(ratio, 1 - cfg.epsilon, 1 + cfg.epsilon) * advantage_mb,\n",
    "                ).mean()\n",
    "                loss = policy_loss - cfg.entropy_coef * dist.entropy().mean()\n",
    "\n",
    "                policy_optimizer.zero_grad()\n",
    "                loss.backward()\n",
    "                policy_optimizer.step()\n",
    "\n",
    "                critic_loss = F.mse_loss(critic(mb.obs), mb.returns)\n",
    "                critic_optimizer.zero_grad()\n",
    "                critic_loss.backward()\n",
    "                critic_optimizer.step()\n",
    "\n",
    "        writer.add_scalar(\"loss/policy\", policy_loss.item(), collector.steps)\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",
    "    return evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ab99062",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "725318dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aaa4e2bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = PPOConfig()\n",
    "ppo = run_ppo_clip(cfg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c74b8f56",
   "metadata": {},
   "outputs": [],
   "source": [
    "ppo.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f6c057e5",
   "metadata": {},
   "source": [
    "## Learning curve"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e30831a",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot([r.step for r in ppo.history], [r.mean for r in ppo.history])\n",
    "plt.xlabel(\"steps\")\n",
    "plt.ylabel(\"cumulated reward\")\n",
    "plt.title(f\"PPO-clip ({cfg.actor}) on {cfg.env_name}\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7faffe71",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "- Compare the three Gaussian policies (`constant`, `tunable`,\n",
    "  `state-dependent`) by changing `PPOConfig.actor`.\n",
    "- Try a harder continuous environment, e.g. `LunarLanderContinuous-v3` or a\n",
    "  MuJoCo task."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "The same algorithm with a Gaussian policy",
   "practical_name": "PPO, clipped, continuous actions"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
