{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "403a84c7",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we code the Soft Actor-Critic (SAC) algorithm. SAC is an\n",
    "*off-policy*, maximum-entropy actor-critic method for continuous actions,\n",
    "described in [this paper](http://proceedings.mlr.press/v80/haarnoja18b/haarnoja18b.pdf)\n",
    "and [this one](https://arxiv.org/pdf/1812.05905.pdf).\n",
    "\n",
    "SAC is explained in [this video](https://www.youtube.com/watch?v=U20F-MvThjM)\n",
    "and [these slides](http://pages.isir.upmc.fr/~sigaud/teach/ps/12_sac.pdf).\n",
    "\n",
    "It builds on TD3 (twin critics, target networks) and adds an **entropy\n",
    "bonus**: the agent maximizes reward *and* the entropy of its policy, which\n",
    "improves exploration. If the entropy coefficient $\\alpha$ is set to 0, SAC\n",
    "reduces exactly to TD3."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68606a97",
   "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": "91983bbb",
   "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",
    "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": "markdown",
   "id": "1a8fb093",
   "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`, `Transitions` / `ReplayBuffer` / `TransitionCollector`, `Evaluator`,\n",
    "`soft_update`, and the `Actor` base class. Importing `rl_mind.envs` registers\n",
    "`CartPoleContinuous-v1`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d536b26",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40d245ef",
   "metadata": {},
   "source": [
    "# SAC\n",
    "\n",
    "## The Squashed Gaussian actor\n",
    "\n",
    "SAC uses a **squashed Gaussian** policy: a Gaussian $\\mathcal{N}(\\mu(s),\n",
    "\\sigma(s))$ passed through a $\\tanh$ so that actions stay in $[-1, 1]$.\n",
    "Since the $\\tanh$ is a deterministic, differentiable function, the policy\n",
    "keeps the property of the Gaussian that matters most here: it can be sampled\n",
    "with the reparametrization trick (`rsample`), described below.\n",
    "\n",
    "`TransformedDistribution` handles the change-of-variables correction to the\n",
    "log-probability automatically. `act` (evaluation) returns the squashed mean.\n",
    "\n",
    "**Where the log-probabilities come from.** Every loss below needs\n",
    "$\\log \\pi(a|s)$ for the action it just sampled. Calling `actor(obs)` returns\n",
    "a `StochasticAction`, which carries **both**:\n",
    "\n",
    "- `.value`, the sampled action $a$ (`[B, action_dim]`);\n",
    "- `.log_prob`, the log-probability $\\log \\pi(a|s)$ **of that very sample**\n",
    "  (`[B]`).\n",
    "\n",
    "The log-probability travels *with* the action rather than being recomputed\n",
    "later, and this is not just a convenience: the action comes from a\n",
    "reparametrized sample (`rsample`), so the gradient of the actor loss flows\n",
    "through it. Recomputing $\\log \\pi(a|s)$ from a stored action would build a\n",
    "different graph — and would pay for a second forward pass. This is why you\n",
    "will read `action.log_prob` and `next_action.log_prob` below instead of\n",
    "calling some `log_prob(obs, action)` method."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83a2fd29",
   "metadata": {},
   "source": [
    "### The reparametrization trick\n",
    "\n",
    "The actor wants to maximize $\\mathbb{E}_{a \\sim \\pi_\\theta(\\cdot|s)}\\big[\n",
    "Q(s, a)\\big]$ (leaving the entropy aside). The problem: $\\theta$ is in the\n",
    "distribution we sample from, and drawing $a$ at random has no gradient.\n",
    "\n",
    "The trick is to move the randomness out of $\\theta$: draw a noise\n",
    "$\\varepsilon \\sim \\mathcal{N}(0, I)$, which does not depend on $\\theta$, and\n",
    "compute the action as a differentiable function of it:\n",
    "\n",
    "$$ a = \\tanh\\big(\\mu_\\theta(s) + \\sigma_\\theta(s)\\, \\varepsilon\\big) $$\n",
    "\n",
    "The action is now an ordinary output of the network (with some noise added\n",
    "to the input), so backpropagation goes from $Q(s, a)$ to $a$, then to\n",
    "$\\mu_\\theta$ and $\\sigma_\\theta$: the critic tells the actor *in which\n",
    "direction to move its actions*, exactly as in DDPG/TD3, but for a stochastic\n",
    "policy. This requires $Q$ to be differentiable in $a$, which it is (a neural\n",
    "network).\n",
    "\n",
    "Without the trick, we would need the score-function estimator of REINFORCE,\n",
    "$\\mathbb{E}\\big[Q(s, a)\\, \\nabla_\\theta \\log \\pi_\\theta(a|s)\\big]$, which\n",
    "only uses the *value* of $Q$ and has a much higher variance.\n",
    "\n",
    "**The log-probability of the squashed action.** The entropy term needs\n",
    "$\\log \\pi_\\theta(a|s)$. Writing $u = \\mu_\\theta(s) + \\sigma_\\theta(s)\\,\n",
    "\\varepsilon$ for the Gaussian sample and $a = \\tanh(u)$, the change of\n",
    "variable formula gives (one term per action dimension $j$, since\n",
    "$\\tanh'(u) = 1 - \\tanh^2(u)$):\n",
    "\n",
    "$$ \\log \\pi_\\theta(a|s) = \\log \\mathcal{N}\\big(u;\\, \\mu_\\theta(s),\n",
    "\\sigma_\\theta(s)\\big) - \\sum_j \\log\\big(1 - \\tanh^2(u_j)\\big) $$\n",
    "\n",
    "In PyTorch, `dist.rsample()` samples this way (the gradient flows back to\n",
    "the parameters), while `dist.sample()` does not; and a\n",
    "`TransformedDistribution` with a `TanhTransform` applies the change of\n",
    "variable in `log_prob` for us. Let us check both:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c109fdb",
   "metadata": {},
   "outputs": [],
   "source": [
    "_mean = torch.zeros(3, requires_grad=True)\n",
    "_std = torch.ones(3)\n",
    "_gaussian = Independent(Normal(_mean, _std), 1)\n",
    "_squashed = TransformedDistribution(_gaussian, [TanhTransform(cache_size=1)])\n",
    "\n",
    "print(\"sample() :\", _squashed.sample().requires_grad)  # no gradient\n",
    "_a = _squashed.rsample()\n",
    "print(\"rsample():\", _a.requires_grad)  # gradient w.r.t. the mean\n",
    "\n",
    "# The change of variable, by hand (u is the Gaussian sample behind a)\n",
    "_u = torch.atanh(_a)\n",
    "_by_hand = _gaussian.log_prob(_u) - torch.log(1 - torch.tanh(_u) ** 2).sum(-1)\n",
    "print(\"log_prob, PyTorch:\", _squashed.log_prob(_a).item())\n",
    "print(\"log_prob, by hand:\", _by_hand.item())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6207f190",
   "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",
    "        # cache_size=1 avoids numerical issues in the log-prob correction\n",
    "        self.tanh = TanhTransform(cache_size=1)\n",
    "\n",
    "    def dist(self, obs: Tensor) -> TransformedDistribution:\n",
    "        # Build the squashed Gaussian distribution\n",
    "\n",
    "        features = self.backbone(obs)\n",
    "        # mean from `self.mean_layer`; std from `self.std_layer`, made positive\n",
    "        # with `self.softplus`, plus `self.min_std` (keeps it away from 0)\n",
    "        mean = ...\n",
    "        std = ...\n",
    "        # `Normal(mean, std)` is a batch of independent 1D Gaussians:\n",
    "        # `Independent(..., 1)` makes it one Gaussian over the action vector,\n",
    "        # so that `log_prob` sums over the action dimensions (shape [B])\n",
    "        normal = ...\n",
    "        return TransformedDistribution(normal, [self.tanh])\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def forward(self, obs: Tensor) -> StochasticAction:\n",
    "        # Sample an action and compute its log-probability\n",
    "\n",
    "        dist = self.dist(obs)\n",
    "        # reparametrized sample (`dist.rsample()`, not `dist.sample()`, so\n",
    "        # that the gradient flows through the action)\n",
    "        action = ...\n",
    "        # log-probability of that very sample (`dist.log_prob`)\n",
    "        log_prob = ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "        # Allows the actor to be deep-copied (clears the transform cache)\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": "eafe1aff",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The critics $Q(s, a)$\n",
    "\n",
    "As in TD3, SAC uses two critics (and their target networks) and takes the\n",
    "minimum of the two to fight the overestimation bias."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5df2a118",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class ContinuousQNetwork(nn.Module):\n",
    "    \"\"\"The Q-network $Q(s, a)$ for continuous actions\"\"\"\n",
    "\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...], action_dim: int):\n",
    "        super().__init__()\n",
    "        self.model = build_mlp([obs_dim + action_dim, *hidden, 1])\n",
    "\n",
    "    def forward(self, obs: Tensor, action: Tensor) -> Tensor:\n",
    "        return self.model(torch.cat([obs, action], dim=1)).squeeze(-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48d858ce",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The losses\n",
    "\n",
    "### Critic loss\n",
    "\n",
    "The target adds an entropy term to the min of the two target critics,\n",
    "evaluated at an action sampled from the **current** actor at the next state:\n",
    "\n",
    "$$ y = r + \\gamma\\,(1-\\text{terminated})\\Big(\\min_{i=1,2} Q'_{\\phi_i}(s',\n",
    "a') - \\alpha \\log \\pi(a'|s')\\Big), \\quad a' \\sim \\pi(\\cdot|s') $$\n",
    "\n",
    "and both critics regress towards it. With $\\alpha = 0$ this is exactly the\n",
    "TD3 critic target."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4cb14031",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_critic_loss(\n",
    "    gamma: float,\n",
    "    alpha: float,\n",
    "    batch: Transitions[StochasticAction],\n",
    "    actor: SquashedGaussianActor,\n",
    "    critics: tuple[ContinuousQNetwork, ContinuousQNetwork],\n",
    "    target_critics: tuple[ContinuousQNetwork, ContinuousQNetwork],\n",
    ") -> Tensor:\n",
    "    \"\"\"Compute the SAC critic loss (sum of the two critics' MSE)\"\"\"\n",
    "    q1, q2 = critics\n",
    "    tq1, tq2 = target_critics\n",
    "\n",
    "    # Compute the critic loss\n",
    "\n",
    "    # action sampled from the CURRENT actor at the next state (no grad)\n",
    "    with torch.no_grad():\n",
    "        next_action = actor(batch.next_obs)\n",
    "        q_next = ...  # min of the two target critics at (next_obs, next_action.value)\n",
    "        v_next = q_next - alpha * next_action.log_prob\n",
    "        target = ...\n",
    "    # the two critics regress towards the shared target\n",
    "    return ...\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4d78ebe",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Actor loss\n",
    "\n",
    "The actor maximizes the (entropy-augmented) Q-value of its own actions,\n",
    "$\\mathbb{E}_{a \\sim \\pi(\\cdot|s)}\\big[\\min_{i} Q_{\\phi_i}(s, a) - \\alpha \\log\n",
    "\\pi(a|s)\\big]$, i.e. it **minimizes** the opposite:\n",
    "\n",
    "$$ \\mathcal{L}_\\pi = \\mathbb{E}_{a \\sim \\pi(\\cdot|s)}\\big[ \\alpha \\log\n",
    "\\pi(a|s) - \\min_{i=1,2} Q_{\\phi_i}(s, a) \\big] $$\n",
    "\n",
    "The action is sampled from the current actor with the reparametrization trick\n",
    "(so the gradient flows through it). With $\\alpha = 0$ this is the TD3 actor\n",
    "loss."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56f1971d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_actor_loss(\n",
    "    alpha: float,\n",
    "    obs: Tensor,\n",
    "    actor: SquashedGaussianActor,\n",
    "    critics: tuple[ContinuousQNetwork, ContinuousQNetwork],\n",
    ") -> tuple[Tensor, Tensor]:\n",
    "    \"\"\"Compute the SAC actor loss; also return the sampled log-probabilities\n",
    "    (needed to tune the entropy coefficient)\"\"\"\n",
    "    q1, q2 = critics\n",
    "    # Compute the actor loss\n",
    "\n",
    "    action = actor(obs)                       # reparametrized sample\n",
    "    q = ...  # min of the two critics at (obs, action.value)\n",
    "    actor_loss = ...\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "    return actor_loss, action.log_prob"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4c3d7e7",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b6cc3d9",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class SACConfig:\n",
    "    env_name: str = \"CartPoleContinuous-v1\"\n",
    "    seed: int = 1\n",
    "\n",
    "    #: Total number of environment steps\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.99\n",
    "    tau: float = 0.05\n",
    "    max_grad_norm: float = 0.5\n",
    "\n",
    "    #: Entropy coefficient: \"auto\" tunes it, a float keeps it fixed\n",
    "    entropy_mode: str = \"auto\"\n",
    "    init_entropy_coef: float = 0.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": "57fc9f5c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The entropy coefficient\n",
    "\n",
    "SAC can **tune** the entropy coefficient $\\alpha$ automatically towards a\n",
    "target entropy $\\mathcal{H}_0 = -\\dim(\\mathcal{A})$. Following SB3, we\n",
    "optimize $\\log \\alpha$ (which keeps $\\alpha$ positive):\n",
    "\n",
    "$$ \\mathcal{L}_\\alpha = -\\log\\alpha \\cdot \\big(\\log\\pi(a|s) +\n",
    "\\mathcal{H}_0\\big) $$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9705d895",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_sac(cfg: SACConfig) -> 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_1 = ContinuousQNetwork(\n",
    "        env.observation_dim, cfg.critic_hidden, env.action_dim\n",
    "    )\n",
    "    critic_2 = ContinuousQNetwork(\n",
    "        env.observation_dim, cfg.critic_hidden, env.action_dim\n",
    "    )\n",
    "    target_1 = copy.deepcopy(critic_1)\n",
    "    target_2 = copy.deepcopy(critic_2)\n",
    "\n",
    "    actor_optimizer = torch.optim.Adam(actor.parameters(), lr=cfg.lr)\n",
    "    critic_optimizer = torch.optim.Adam(\n",
    "        [*critic_1.parameters(), *critic_2.parameters()], lr=cfg.lr\n",
    "    )\n",
    "\n",
    "    # Entropy coefficient (tuned or fixed)\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\"sac-{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 update\n",
    "            critic_loss = compute_critic_loss(\n",
    "                cfg.gamma,\n",
    "                alpha,\n",
    "                batch,\n",
    "                actor,\n",
    "                (critic_1, critic_2),\n",
    "                (target_1, target_2),\n",
    "            )\n",
    "            # Gradient step on the critics\n",
    "\n",
    "            # zero_grad() on the optimizer, backward() on the loss, then step()\n",
    "            ...\n",
    "            assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "            # Actor update\n",
    "            actor_loss, log_prob = compute_actor_loss(\n",
    "                alpha, batch.obs, actor, (critic_1, critic_2)\n",
    "            )\n",
    "            # Gradient step on the actor\n",
    "\n",
    "            # same three calls, with the actor's loss and optimizer\n",
    "            ...\n",
    "            assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "            # Entropy coefficient update\n",
    "            if auto_entropy:\n",
    "                # Entropy coefficient loss, then a gradient step on log_alpha\n",
    "\n",
    "                # L_alpha (see above), averaged over the batch; `.detach()` the\n",
    "                # term in log_prob, which must not carry gradients to the actor\n",
    "                alpha_loss = ...\n",
    "                # gradient step with `alpha_optimizer`\n",
    "                ...\n",
    "                assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "            # Soft update of the two target critics\n",
    "\n",
    "            # `soft_update(source, target, tau)` moves `target` towards\n",
    "            # `source` (by a fraction `cfg.tau`), once per critic\n",
    "            ...\n",
    "            assert False, 'Not implemented yet'\n",
    "\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": "42b913d6",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61d0e5c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "209caef1",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = SACConfig()\n",
    "sac = run_sac(cfg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f244739f",
   "metadata": {},
   "outputs": [],
   "source": [
    "sac.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "250dceb5",
   "metadata": {},
   "source": [
    "## Learning curve"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc37eb6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot([r.step for r in sac.history], [r.mean for r in sac.history])\n",
    "plt.xlabel(\"steps\")\n",
    "plt.ylabel(\"cumulated reward\")\n",
    "plt.title(f\"SAC on {cfg.env_name}\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b478a549",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "- Set `entropy_mode` to a fixed float (e.g. `0.0`) and check that SAC then\n",
    "  behaves like TD3.\n",
    "- Run SAC on the harder `Pendulum-v1` environment; you may need to retune the\n",
    "  hyper-parameters (see the\n",
    "  [rl-baselines3-zoo](https://github.com/DLR-RM/rl-baselines3-zoo))."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Maximum-entropy off-policy learning: TD3 plus an entropy bonus",
   "practical_name": "Soft Actor-Critic"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
