{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a83a218b",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we code the **KL-penalty** version of PPO. Instead of\n",
    "*clipping* the probability ratio (the version in `07-2`), it keeps the new\n",
    "policy close to the old one by subtracting a KL-divergence penalty from the\n",
    "objective.\n",
    "\n",
    "See the [PPO paper](https://arxiv.org/pdf/1707.06347.pdf) and [these\n",
    "slides](http://pages.isir.upmc.fr/~sigaud/teach/ps/10_ppo.pdf)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "491089e0",
   "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": "f5d6a674",
   "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": "8bc1be4a",
   "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",
    "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, 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": "341622fa",
   "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",
    "`minibatches`, `Evaluator`, and the `Actor` base class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3e634987",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35934eb6",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# PPO with a KL penalty\n",
    "\n",
    "The overall structure is identical to PPO-clip (`07-2`): collect a rollout,\n",
    "compute GAE advantages once, then run several epochs of minibatch updates.\n",
    "The only difference is the policy loss, which maximizes\n",
    "\n",
    "$$\n",
    "\\max_{\\theta}\\ \\hat{\\mathbb{E}}_t\\left[ r_t(\\theta)\\,\\hat{A}_t - \\beta\\,\n",
    "\\operatorname{KL}\\!\\big[\\pi_{\\theta_{\\text{old}}}(\\cdot|s_t)\\,\\|\\,\n",
    "\\pi_\\theta(\\cdot|s_t)\\big] \\right]\n",
    "$$\n",
    "\n",
    "where $\\hat{A}_t$ is the advantage and\n",
    "\n",
    "$$r_t(\\theta) = \\frac{\\pi_\\theta\\left(a_t \\mid\n",
    "s_t\\right)}{\\pi_{\\theta_{\\text{old}}}\\left(a_t \\mid s_t\\right)}$$\n",
    "\n",
    "is the probability ratio between the current policy and the policy that\n",
    "collected the data: a penalty on the KL divergence replaces the clipping.\n",
    "\n",
    "The ratio itself only needs the log-probabilities stored when the actions\n",
    "were sampled, but the KL term needs the **full** old distribution at each\n",
    "state, so we also keep a frozen copy of the policy that collected the\n",
    "rollout (`old_policy`).\n",
    "\n",
    "## Definition of the agents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29cb2321",
   "metadata": {},
   "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": "code",
   "execution_count": null,
   "id": "f62148b5",
   "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": "c4b3e846",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## GAE and the training data\n",
    "\n",
    "Unchanged from PPO-clip."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8ef7b02",
   "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": "2ef9fa03",
   "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": "c7f68e2c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48a846bc",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class PPOConfig:\n",
    "    env_name: str = \"CartPole-v1\"\n",
    "    seed: int = 12\n",
    "\n",
    "    max_updates: int = 100\n",
    "    n_envs: int = 8\n",
    "    n_steps: int = 32\n",
    "\n",
    "    gamma: float = 0.98\n",
    "    gae_lam: float = 0.8\n",
    "\n",
    "    #: KL penalty coefficient (beta)\n",
    "    beta: float = 5.0\n",
    "    opt_epochs: int = 10\n",
    "    batch_size: int = 256\n",
    "    normalize_advantage: bool = False\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(4_000, fast_test=1_000)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4760733f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "Write the KL-penalty policy loss: the probability ratio $r_t(\\theta)$, then\n",
    "the penalized objective. Useful:\n",
    "\n",
    "- the ratio is computed from the *difference of log-probabilities*\n",
    "  (`dist.log_prob(mb.action)` against the stored `mb.old_log_prob`), which\n",
    "  avoids two exponentials and is numerically better behaved;\n",
    "- [`torch.distributions.kl_divergence(p, q)`](https://pytorch.org/docs/stable/distributions.html#torch.distributions.kl.kl_divergence)\n",
    "  computes $\\operatorname{KL}[p\\,\\|\\,q]$ per state — pass the **old**\n",
    "  policy's distribution as $p$ and the current one as $q$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1e1c7cfc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_ppo_penalty(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 = DiscretePolicy(env.observation_dim, cfg.actor_hidden, env.n_actions)\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-kl-{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",
    "        # Frozen copy of the policy that collected the rollout (for the KL term)\n",
    "        old_policy = copy.deepcopy(policy)\n",
    "\n",
    "        for epoch in range(cfg.opt_epochs):\n",
    "            for mb in minibatches(data, cfg.batch_size):\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",
    "                # Compute the KL-penalty policy loss\n",
    "\n",
    "                dist = policy.dist(mb.obs)\n",
    "                # The probability ratio, from the stored log-probabilities\n",
    "                ratio = ...\n",
    "                # KL between the old and the current policy at each state\n",
    "                with torch.no_grad(): old_dist = old_policy.dist(mb.obs)\n",
    "                kl = ...\n",
    "                # maximize  ratio * advantage - beta * kl  (so minimize its negation)\n",
    "                policy_loss = ...\n",
    "                assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "                loss = policy_loss - cfg.entropy_coef * dist.entropy().mean()\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": "aa5123c8",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96e8b0bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b0c06dfd",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = PPOConfig()\n",
    "ppo = run_ppo_penalty(cfg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "232812b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "ppo.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "653bac07",
   "metadata": {},
   "source": [
    "## Learning curve"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2472d031",
   "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(\"PPO (KL penalty) on CartPole-v1\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56ad068c",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "Compare the KL-penalty version with PPO-clip (`07-2`). Try a few values of\n",
    "`beta`: too small barely constrains the update (like vanilla policy gradient,\n",
    "unstable), too large freezes the policy."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Staying close to the old policy by penalising the KL divergence",
   "practical_name": "PPO with a KL penalty"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
