{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "46428029",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we code **Truncated Quantile Critics (TQC)**, described in\n",
    "[this paper](https://arxiv.org/abs/2005.04269). TQC extends SAC (`08`) in one\n",
    "way: instead of predicting a single Q-value, each critic predicts a\n",
    "**distribution** of returns as a set of *quantiles*; the target then **drops\n",
    "the top quantiles** (the optimistic tail) to control the overestimation bias\n",
    "more finely than the min-of-two-critics trick of TD3/SAC.\n",
    "\n",
    "Everything else — the squashed Gaussian actor, the entropy tuning, the replay\n",
    "buffer — is unchanged from SAC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3457a054",
   "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": "52e9d848",
   "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": "5e5c2ea2",
   "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 rl_mind.envs\n",
    "from dataclasses import dataclass, replace\n",
    "from torch import Tensor\n",
    "from torch.distributions import Independent, Normal, TanhTransform, TransformedDistribution\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, soft_update\n",
    "from rl_mind.env import VecEnv\n",
    "from rl_mind.data import ReplayBuffer, Transitions\n",
    "from rl_mind.collectors import TransitionCollector\n",
    "from rl_mind.evaluation import Evaluator\n",
    "from rl_mind.notebook import run_directory, setup_tensorboard, silence_known_warnings\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08664901",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53c2864a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# The Squashed Gaussian actor\n",
    "\n",
    "Identical to SAC: a Gaussian squashed through a $\\tanh$, sampled with the\n",
    "reparametrization trick."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9e1bfc6",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class SquashedGaussianActor(Actor[StochasticAction]):\n",
    "    def __init__(\n",
    "        self,\n",
    "        obs_dim: int,\n",
    "        hidden: tuple[int, ...],\n",
    "        action_dim: int,\n",
    "        min_std: float = 1e-4,\n",
    "    ):\n",
    "        super().__init__()\n",
    "        self.backbone = build_mlp([obs_dim, *hidden], output_activation=nn.ReLU())\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",
    "        self.min_std = min_std\n",
    "        self.tanh = TanhTransform(cache_size=1)\n",
    "\n",
    "    def dist(self, obs: Tensor) -> TransformedDistribution:\n",
    "        features = self.backbone(obs)\n",
    "        std = self.softplus(self.std_layer(features)) + self.min_std\n",
    "        normal = Independent(Normal(self.mean_layer(features), std), 1)\n",
    "        return TransformedDistribution(normal, [self.tanh])\n",
    "\n",
    "    def forward(self, obs: Tensor) -> StochasticAction:\n",
    "        dist = self.dist(obs)\n",
    "        action = dist.rsample()\n",
    "        log_prob = dist.log_prob(action)\n",
    "        self.tanh._cached_x_y = [None, None]\n",
    "        return StochasticAction(value=action, log_prob=log_prob)\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        features = self.backbone(obs)\n",
    "        return torch.tanh(self.mean_layer(features))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0101e23",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# The quantile critic\n",
    "\n",
    "The critic is a set of `n_nets` networks, each outputting `n_quantiles`\n",
    "values — an approximation of the *distribution* of the return $Q(s, a)$ by\n",
    "its quantiles. `forward` stacks them into a `[B, n_nets, n_quantiles]`\n",
    "tensor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "004d9de6",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class TruncatedQuantileCritic(nn.Module):\n",
    "    def __init__(\n",
    "        self,\n",
    "        obs_dim: int,\n",
    "        hidden: tuple[int, ...],\n",
    "        action_dim: int,\n",
    "        n_nets: int,\n",
    "        n_quantiles: int,\n",
    "    ):\n",
    "        super().__init__()\n",
    "        self.nets = nn.ModuleList(\n",
    "            build_mlp([obs_dim + action_dim, *hidden, n_quantiles])\n",
    "            for _ in range(n_nets)\n",
    "        )\n",
    "\n",
    "    def forward(self, obs: Tensor, action: Tensor) -> Tensor:\n",
    "        obs_act = torch.cat([obs, action], dim=1)\n",
    "        return torch.stack([net(obs_act) for net in self.nets], dim=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c155d97d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# The quantile Huber loss\n",
    "\n",
    "The critic regresses its quantiles towards the target quantiles using the\n",
    "quantile Huber loss (from\n",
    "[QR-DQN](https://arxiv.org/abs/1710.10044)): a Huber loss weighted\n",
    "asymmetrically so that the $i$-th predicted quantile converges to the\n",
    "corresponding quantile of the target distribution. This part is provided."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2af86d6d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def quantile_huber_loss(quantiles: Tensor, target: Tensor) -> Tensor:\n",
    "    \"\"\"Quantile Huber loss between predicted quantiles and target samples\n",
    "\n",
    "    :param quantiles: The predicted quantiles, shape `[B, n_nets, n_quantiles]`\n",
    "    :param target: The target samples, shape `[B, n_targets]`\n",
    "    \"\"\"\n",
    "    # pairwise differences: [B, n_nets, n_quantiles, n_targets]\n",
    "    pairwise = target[:, None, None, :] - quantiles[:, :, :, None]\n",
    "    abs_pairwise = pairwise.abs()\n",
    "    huber = torch.where(abs_pairwise > 1, abs_pairwise - 0.5, 0.5 * pairwise**2)\n",
    "\n",
    "    n_quantiles = quantiles.shape[2]\n",
    "    tau = (torch.arange(n_quantiles).float() + 0.5) / n_quantiles\n",
    "    weight = torch.abs(tau[None, None, :, None] - (pairwise < 0).float())\n",
    "    return (weight * huber).mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16e4dd2f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# The critic loss\n",
    "\n",
    "The target pools the quantiles predicted by **all** the target nets at the\n",
    "next state (for an action sampled from the current actor), sorts them, and\n",
    "**drops the `top_quantiles_to_drop` per net** — the truncation that removes\n",
    "the optimistic tail. As in SAC, the (entropy-augmented) target is\n",
    "\n",
    "$$ y = r + \\gamma\\,(1-\\text{terminated})\\,\\big(z - \\alpha \\log\\pi(a'|s')\\big) $$\n",
    "\n",
    "for each kept quantile $z$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5807c8b4",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_critic_loss(\n",
    "    gamma: float,\n",
    "    alpha: float,\n",
    "    top_quantiles_to_drop: int,\n",
    "    batch: Transitions[StochasticAction],\n",
    "    actor: SquashedGaussianActor,\n",
    "    critic: TruncatedQuantileCritic,\n",
    "    target_critic: TruncatedQuantileCritic,\n",
    ") -> Tensor:\n",
    "    \"\"\"Compute the TQC critic loss\"\"\"\n",
    "    quantiles = critic(batch.obs, batch.action.value)  # [B, n_nets, n_quantiles]\n",
    "    n_nets = quantiles.shape[1]\n",
    "\n",
    "    # Compute the truncated, entropy-augmented target quantiles\n",
    "\n",
    "    with torch.no_grad():\n",
    "        next_action = actor(batch.next_obs)          # current actor at s'\n",
    "        next_quantiles = target_critic(...)          # [B, n_nets, n_quantiles]\n",
    "        # pool all nets, sort, drop the top `top_quantiles_to_drop * n_nets`\n",
    "        sorted_q, _ = next_quantiles.reshape(quantiles.shape[0], -1).sort(dim=1)\n",
    "        n_keep = sorted_q.shape[1] - top_quantiles_to_drop * n_nets\n",
    "        truncated = sorted_q[:, :n_keep]\n",
    "        target = ...                                 # [B, n_keep]\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    return quantile_huber_loss(quantiles, target)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce1a477e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# The actor loss\n",
    "\n",
    "The actor maximizes the (entropy-augmented) **mean** of its quantiles — the\n",
    "distributional analogue of SAC's actor loss."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78e35168",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_actor_loss(\n",
    "    alpha: float,\n",
    "    obs: Tensor,\n",
    "    actor: SquashedGaussianActor,\n",
    "    critic: TruncatedQuantileCritic,\n",
    ") -> tuple[Tensor, Tensor]:\n",
    "    \"\"\"Compute the TQC actor loss and return the sampled log-probabilities\"\"\"\n",
    "    # Compute the actor loss\n",
    "\n",
    "    action = actor(obs)\n",
    "    mean_q = critic(obs, action.value).mean(dim=(1, 2))   # mean over nets and quantiles\n",
    "    actor_loss = ...\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "    return actor_loss, action.log_prob"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a09468a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a5572ca",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class TQCConfig:\n",
    "    env_name: str = \"CartPoleContinuous-v1\"\n",
    "    seed: int = 1\n",
    "\n",
    "    max_steps: int = Profile.pick(30_000, fast_test=1_200)\n",
    "    n_envs: int = 8\n",
    "    steps_per_round: int = 32\n",
    "    updates_per_round: int = 32\n",
    "    learning_starts: int = Profile.pick(10_000, fast_test=300)\n",
    "\n",
    "    buffer_size: int = 1_000_000\n",
    "    batch_size: int = 256\n",
    "\n",
    "    gamma: float = 0.98\n",
    "    tau: float = 0.05\n",
    "    max_grad_norm: float = 0.5\n",
    "\n",
    "    entropy_mode: str = \"auto\"\n",
    "    init_entropy_coef: float = 0.2\n",
    "\n",
    "    #: distributional critic: number of nets, quantiles, and how many top\n",
    "    #: quantiles to drop per net (the truncation)\n",
    "    n_nets: int = 2\n",
    "    n_quantiles: int = 25\n",
    "    top_quantiles_to_drop: int = 2\n",
    "\n",
    "    actor_hidden: tuple[int, ...] = (256, 256)\n",
    "    critic_hidden: tuple[int, ...] = (256, 256)\n",
    "    lr: float = 3e-4\n",
    "\n",
    "    eval_interval: int = Profile.pick(2_000, fast_test=400)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cb70c6b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "Identical in structure to SAC — only the critic and its loss changed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4faf22bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_tqc(cfg: TQCConfig) -> Evaluator:\n",
    "    torch.manual_seed(cfg.seed)\n",
    "    env = VecEnv(cfg.env_name, cfg.n_envs, seed=cfg.seed)\n",
    "\n",
    "    actor = SquashedGaussianActor(env.observation_dim, cfg.actor_hidden, env.action_dim)\n",
    "    critic = TruncatedQuantileCritic(\n",
    "        env.observation_dim,\n",
    "        cfg.critic_hidden,\n",
    "        env.action_dim,\n",
    "        cfg.n_nets,\n",
    "        cfg.n_quantiles,\n",
    "    )\n",
    "    target_critic = copy.deepcopy(critic)\n",
    "\n",
    "    actor_optimizer = torch.optim.Adam(actor.parameters(), lr=cfg.lr)\n",
    "    critic_optimizer = torch.optim.Adam(critic.parameters(), lr=cfg.lr)\n",
    "\n",
    "    auto_entropy = cfg.entropy_mode == \"auto\"\n",
    "    log_alpha = torch.log(torch.ones(1) * cfg.init_entropy_coef).requires_grad_(\n",
    "        auto_entropy\n",
    "    )\n",
    "    alpha_optimizer = torch.optim.Adam([log_alpha], lr=cfg.lr) if auto_entropy else None\n",
    "    target_entropy = -float(env.action_dim)\n",
    "\n",
    "    collector = TransitionCollector(env, actor)\n",
    "    buffer = ReplayBuffer(cfg.buffer_size)\n",
    "    run_dir = run_directory(f\"tqc-{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(total=cfg.max_steps)\n",
    "    while collector.steps < cfg.max_steps:\n",
    "        buffer.add(collector.collect(cfg.steps_per_round))\n",
    "        pbar.update(collector.steps - pbar.n)\n",
    "        if len(buffer) < cfg.learning_starts:\n",
    "            continue\n",
    "\n",
    "        for _ in range(cfg.updates_per_round):\n",
    "            batch = buffer.sample(cfg.batch_size)\n",
    "            alpha = log_alpha.exp().item()\n",
    "\n",
    "            critic_loss = compute_critic_loss(\n",
    "                cfg.gamma,\n",
    "                alpha,\n",
    "                cfg.top_quantiles_to_drop,\n",
    "                batch,\n",
    "                actor,\n",
    "                critic,\n",
    "                target_critic,\n",
    "            )\n",
    "            critic_optimizer.zero_grad()\n",
    "            critic_loss.backward()\n",
    "            critic_optimizer.step()\n",
    "\n",
    "            actor_loss, log_prob = compute_actor_loss(alpha, batch.obs, actor, critic)\n",
    "            actor_optimizer.zero_grad()\n",
    "            actor_loss.backward()\n",
    "            actor_optimizer.step()\n",
    "\n",
    "            if auto_entropy:\n",
    "                alpha_loss = -(log_alpha * (log_prob + target_entropy).detach()).mean()\n",
    "                alpha_optimizer.zero_grad()\n",
    "                alpha_loss.backward()\n",
    "                alpha_optimizer.step()\n",
    "\n",
    "            soft_update(critic, target_critic, cfg.tau)\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(\"entropy_coef\", alpha, collector.steps)\n",
    "        if result := evaluator.run_if_needed(collector.steps, actor):\n",
    "            pbar.set_description(\n",
    "                f\"eval={result.mean:7.1f} best={evaluator.best_reward:7.1f}\"\n",
    "            )\n",
    "\n",
    "    pbar.close()\n",
    "    return evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b0f502a",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eed6f410",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be3e5fd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = TQCConfig()\n",
    "tqc = run_tqc(cfg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22a30188",
   "metadata": {},
   "outputs": [],
   "source": [
    "tqc.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2cd04293",
   "metadata": {},
   "source": [
    "## Learning curve"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8ac6598",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot([r.step for r in tqc.history], [r.mean for r in tqc.history])\n",
    "plt.xlabel(\"steps\")\n",
    "plt.ylabel(\"cumulated reward\")\n",
    "plt.title(f\"TQC on {cfg.env_name}\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e3ad0f8",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "Vary `top_quantiles_to_drop`: with 0 dropped quantiles TQC is optimistic\n",
    "(overestimates), while dropping too many makes it overly pessimistic and\n",
    "slow. Find the sweet spot for `CartPoleContinuous-v1`."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Distributional critics for SAC: quantiles, with the optimistic tail dropped",
   "practical_name": "Truncated Quantile Critics"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
