{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "653abd50",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we code the **Cross-Entropy Method (CEM)**. Unlike the\n",
    "gradient-based algorithms of the other notebooks, CEM is a *black-box*\n",
    "optimizer: it treats the whole policy as a vector of parameters and searches\n",
    "for a good one by evolution — no gradients, no critic, no replay buffer.\n",
    "\n",
    "It maintains a Gaussian distribution over parameter vectors, samples a\n",
    "**population** of candidates, evaluates each by running episodes, keeps the\n",
    "best (**elites**) and re-fits the Gaussian to them."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f14cf113",
   "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": "cd1f804f",
   "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 numpy rl-mind==0.4.* torch\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7c1ae23",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import copy\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from dataclasses import dataclass, replace\n",
    "from torch import Tensor\n",
    "from torch.distributions import MultivariateNormal\n",
    "from rl_mind.profiles import Profile\n",
    "from rl_mind.core import Action, Actor\n",
    "from rl_mind.nn import build_mlp\n",
    "from rl_mind.env import VecEnv\n",
    "from rl_mind.evaluation import EvalResult, Evaluator\n",
    "from rl_mind.notebook import run_directory, silence_known_warnings\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "acf17025",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c10ba87",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# The policy\n",
    "\n",
    "A plain deterministic actor (a `tanh` MLP). CEM never differentiates it — it\n",
    "only reads and writes its parameters as a flat vector."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b9511a8",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class ContinuousDeterministicActor(Actor[Action]):\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...], action_dim: int):\n",
    "        super().__init__()\n",
    "        self.model = build_mlp(\n",
    "            [obs_dim, *hidden, action_dim], output_activation=nn.Tanh()\n",
    "        )\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        return Action(value=self.model(obs))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00ef623b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# The search distribution\n",
    "\n",
    "`CovMatrix` holds the covariance of the Gaussian over parameter vectors,\n",
    "with an additive **noise** term (decayed over time) that keeps the search\n",
    "from collapsing too early. `generate_weights` samples a population from\n",
    "$\\mathcal{N}(\\text{centroid}, \\Sigma)$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e016f68",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class CovMatrix:\n",
    "    def __init__(self, centroid: Tensor, sigma: float, noise_multiplier: float):\n",
    "        policy_dim = centroid.shape[0]\n",
    "        self.noise = torch.diag(torch.ones(policy_dim) * sigma)\n",
    "        self.cov = torch.diag(torch.ones(policy_dim) * torch.var(centroid)) + self.noise\n",
    "        self.noise_multiplier = noise_multiplier\n",
    "\n",
    "    def update_noise(self) -> None:\n",
    "        self.noise = self.noise * self.noise_multiplier\n",
    "\n",
    "    def generate_weights(self, centroid: Tensor, pop_size: int) -> list[Tensor]:\n",
    "        \"\"\"Sample `pop_size` parameter vectors around `centroid`\n",
    "\n",
    "        Use a\n",
    "        [`MultivariateNormal`](https://pytorch.org/docs/stable/distributions.html#multivariatenormal)\n",
    "        with mean `centroid` and covariance `self.cov`.\n",
    "        \"\"\"\n",
    "        # Sample the population\n",
    "\n",
    "        dist = ...\n",
    "        return ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def update(self, elites: Tensor) -> None:\n",
    "        \"\"\"Re-fit the covariance to the elite parameter vectors (+ noise)\"\"\"\n",
    "        self.cov = torch.cov(elites.T) + self.noise"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a99a9fb",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters\n",
    "\n",
    "Notice how short this is compared with the RL algorithms: no optimizer, no\n",
    "learning rate, no replay buffer, no discount factor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fd0fcb3d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class CEMConfig:\n",
    "    env_name: str = \"MountainCarContinuous-v0\"\n",
    "    seed: int = 1\n",
    "\n",
    "    #: Number of generations\n",
    "    max_epochs: int = Profile.pick(150, fast_test=2)\n",
    "    #: Population size and number of elites kept each generation\n",
    "    pop_size: int = Profile.pick(10, fast_test=4)\n",
    "    elites_nb: int = Profile.pick(5, fast_test=2)\n",
    "    #: Number of episodes used to score each candidate\n",
    "    n_eval_envs: int = 10\n",
    "\n",
    "    #: Initial exploration noise and its decay\n",
    "    sigma: float = 0.1\n",
    "    noise_multiplier: float = 0.99\n",
    "\n",
    "    actor_hidden: tuple[int, ...] = (10,)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09cebd6c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main loop\n",
    "\n",
    "Each generation: decay the noise, sample a population, evaluate every\n",
    "candidate (load its parameters into the actor and run episodes), keep the\n",
    "elites, and re-fit the Gaussian to them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d640960e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_cem(cfg: CEMConfig) -> Evaluator:\n",
    "    torch.manual_seed(cfg.seed)\n",
    "    env = VecEnv(cfg.env_name, cfg.n_eval_envs, seed=cfg.seed)\n",
    "    actor = ContinuousDeterministicActor(\n",
    "        env.observation_dim, cfg.actor_hidden, env.action_dim\n",
    "    )\n",
    "\n",
    "    # The policy parameters as a single flat vector (the \"centroid\")\n",
    "    centroid = nn.utils.parameters_to_vector(actor.parameters())\n",
    "    cov = CovMatrix(centroid, cfg.sigma, cfg.noise_multiplier)\n",
    "\n",
    "    run_dir = run_directory(f\"cem-{cfg.env_name}-S{cfg.seed}\")\n",
    "    evaluator = Evaluator(env, every=0, run_dir=run_dir)\n",
    "\n",
    "    def score(params: Tensor) -> Tensor:\n",
    "        \"\"\"Load `params` into the actor and return the per-episode rewards\"\"\"\n",
    "        nn.utils.vector_to_parameters(params, actor.parameters())\n",
    "        return evaluator.run(actor)\n",
    "\n",
    "    for epoch in range(cfg.max_epochs):\n",
    "        cov.update_noise()\n",
    "        weights = cov.generate_weights(centroid, cfg.pop_size)\n",
    "\n",
    "        scores = []\n",
    "        for params in weights:\n",
    "            rewards = score(params)\n",
    "            scores.append(float(rewards.mean()))\n",
    "            # Keep the best candidate seen so far (for the video)\n",
    "            if float(rewards.mean()) > evaluator.best_reward:\n",
    "                evaluator.best_reward = float(rewards.mean())\n",
    "                evaluator.best_actor = copy.deepcopy(actor)\n",
    "\n",
    "        # Keep the elites and update the search distribution\n",
    "\n",
    "        # indices of the `elites_nb` best candidates\n",
    "        elite_idx = ...\n",
    "        elites = ...            # a [elites_nb, param_dim] tensor\n",
    "        # the new centroid is the mean of the elites; refit the covariance\n",
    "        centroid = ...\n",
    "        cov.update(elites)\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        evaluator.history.append(\n",
    "            EvalResult(step=epoch, rewards=torch.tensor(scores), is_best=False)\n",
    "        )\n",
    "\n",
    "    return evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5812b964",
   "metadata": {},
   "source": [
    "## CEM on MountainCarContinuous\n",
    "\n",
    "`MountainCarContinuous-v0` rewards reaching the flag (and penalizes energy),\n",
    "which makes it a classic sparse-ish task where black-box search shines."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ee94372",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = CEMConfig()\n",
    "cem = run_cem(cfg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec5995ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "cem.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a1ab2a9",
   "metadata": {},
   "source": [
    "## Learning curve\n",
    "\n",
    "The mean and best population score per generation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3499ca2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "epochs = [r.step for r in cem.history]\n",
    "means = [r.mean for r in cem.history]\n",
    "best = [float(r.rewards.max()) for r in cem.history]\n",
    "plt.plot(epochs, means, label=\"population mean\")\n",
    "plt.plot(epochs, best, label=\"population best\")\n",
    "plt.xlabel(\"generation\")\n",
    "plt.ylabel(\"cumulated reward\")\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "A black-box optimizer: a population of policies, no gradient and no critic",
   "practical_name": "Cross-Entropy Method"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
