{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7aff9136",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "`MountainCarContinuous-v0` is a classic environment where standard policy\n",
    "gradient / TD3 struggles: the reward is sparse (you only score by reaching\n",
    "the flag) and the gradient is *deceptive* (initially, moving costs energy, so\n",
    "the agent learns to do nothing). We first see TD3 **fail**, then help it with\n",
    "two forms of external guidance:\n",
    "\n",
    "1. **Tutor instructions** — a wrapper that occasionally overrides the agent's\n",
    "   action with a hint (push in the momentum direction), a form of reward-free\n",
    "   guidance / reward shaping;\n",
    "2. **Behavioral cloning** — bootstrap the policy by imitating a hand-coded\n",
    "   expert."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc1ba34c",
   "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": "dd04dff6",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import copy\n",
    "import random\n",
    "import gymnasium as gym\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from dataclasses import dataclass, field, 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 Action, Actor\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": "2f82125d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10045bb2",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# TD3 (provided)\n",
    "\n",
    "The learner is the TD3 algorithm from `04-ddpg-td3`. It is parametrized by a\n",
    "list of gymnasium `wrappers` so we can plug in the tutor below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3b0f9c06",
   "metadata": {},
   "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))\n",
    "\n",
    "\n",
    "class GaussianNoise(Actor[Action]):\n",
    "    def __init__(self, actor: Actor[Action], sigma: float):\n",
    "        super().__init__()\n",
    "        self.actor = actor\n",
    "        self.sigma = sigma\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        action = self.actor(obs).value\n",
    "        return Action(value=action + self.sigma * torch.randn_like(action))\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        return self.actor.act(obs)\n",
    "\n",
    "\n",
    "class ContinuousQNetwork(nn.Module):\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": "code",
   "execution_count": null,
   "id": "3f095d2c",
   "metadata": {},
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class TD3Config:\n",
    "    env_name: str = \"MountainCarContinuous-v0\"\n",
    "    #: gymnasium wrappers applied to the TRAINING sub-environments (the tutor)\n",
    "    wrappers: tuple = ()\n",
    "    tutor_rate: float = 0.25\n",
    "    seed: int = 1\n",
    "\n",
    "    max_steps: int = Profile.pick(100_000, fast_test=1_500)\n",
    "    n_envs: int = 1\n",
    "    steps_per_round: int = 100\n",
    "    updates_per_round: int = 100\n",
    "    learning_starts: int = Profile.pick(1_000, fast_test=200)\n",
    "\n",
    "    buffer_size: int = 1_000_000\n",
    "    batch_size: int = 256\n",
    "\n",
    "    gamma: float = 0.99\n",
    "    tau: float = 0.005\n",
    "    action_noise: float = 0.3\n",
    "    policy_delay: int = 2\n",
    "    target_noise: float = 0.2\n",
    "    target_noise_clip: float = 0.5\n",
    "\n",
    "    actor_hidden: tuple[int, ...] = (256, 256)\n",
    "    critic_hidden: tuple[int, ...] = (256, 256)\n",
    "    lr: float = 1e-3\n",
    "\n",
    "    eval_interval: int = Profile.pick(5_000, fast_test=500)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9ec568e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_td3(cfg: TD3Config, actor: ContinuousDeterministicActor | None = None) -> tuple:\n",
    "    \"\"\"Train TD3; the evaluation env is always the *unwrapped* environment (we\n",
    "    measure true performance, not the tutor-assisted one). An initial `actor`\n",
    "    can be passed (e.g. after behavioral cloning).\"\"\"\n",
    "    torch.manual_seed(cfg.seed)\n",
    "    env = VecEnv(cfg.env_name, cfg.n_envs, seed=cfg.seed, wrappers=cfg.wrappers)\n",
    "\n",
    "    if actor is None:\n",
    "        actor = ContinuousDeterministicActor(\n",
    "            env.observation_dim, cfg.actor_hidden, env.action_dim\n",
    "        )\n",
    "    target_actor = copy.deepcopy(actor)\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, target_2 = copy.deepcopy(critic_1), 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",
    "    collector = TransitionCollector(env, GaussianNoise(actor, cfg.action_noise))\n",
    "    buffer = ReplayBuffer(cfg.buffer_size)\n",
    "    run_dir = run_directory(f\"td3-{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",
    "    updates = 0\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",
    "            with torch.no_grad():\n",
    "                noise = (torch.randn_like(batch.action.value) * cfg.target_noise).clamp(\n",
    "                    -cfg.target_noise_clip, cfg.target_noise_clip\n",
    "                )\n",
    "                next_actions = (target_actor(batch.next_obs).value + noise).clamp(-1, 1)\n",
    "                q_next = torch.min(\n",
    "                    target_1(batch.next_obs, next_actions),\n",
    "                    target_2(batch.next_obs, next_actions),\n",
    "                )\n",
    "                target = batch.reward + cfg.gamma * q_next * (~batch.terminated).float()\n",
    "\n",
    "            critic_loss = F.mse_loss(\n",
    "                critic_1(batch.obs, batch.action.value), target\n",
    "            ) + F.mse_loss(critic_2(batch.obs, batch.action.value), target)\n",
    "            critic_optimizer.zero_grad()\n",
    "            critic_loss.backward()\n",
    "            critic_optimizer.step()\n",
    "\n",
    "            updates += 1\n",
    "            if updates % cfg.policy_delay == 0:\n",
    "                actor_loss = -critic_1(batch.obs, actor(batch.obs).value).mean()\n",
    "                actor_optimizer.zero_grad()\n",
    "                actor_loss.backward()\n",
    "                actor_optimizer.step()\n",
    "                soft_update(actor, target_actor, cfg.tau)\n",
    "                soft_update(critic_1, target_1, cfg.tau)\n",
    "                soft_update(critic_2, target_2, cfg.tau)\n",
    "\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 actor, evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d31ef101",
   "metadata": {},
   "source": [
    "# 1. Plain TD3 (the baseline that struggles)\n",
    "\n",
    "`MountainCarContinuous` has an action in $[-1, 1]$ (the force) and a 2-D\n",
    "state (position, velocity). With only exploration noise, TD3 rarely reaches\n",
    "the flag and often converges to \"do nothing\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7047ee9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27ca1875",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = TD3Config()\n",
    "_, td3_plain = run_td3(cfg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1039b32",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# 2. Tutor instructions (reward-free guidance)\n",
    "\n",
    "`TutorInstructionWrapper` occasionally **overrides** the agent's action with\n",
    "a hint that pushes the car in the direction of its velocity (build up\n",
    "momentum). It tutors only a fraction `tutor_rate` of the episodes, so the\n",
    "agent still has to learn to act on its own.\n",
    "\n",
    "**Exercise**: fill in the two conditions of `tutor_instruction_signal` so\n",
    "that the car is pushed the right way (recall: `obs = [position, velocity]`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2f230f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "class TutorInstructionWrapper(gym.Wrapper):\n",
    "    def __init__(self, env, tutor_rate: float):\n",
    "        super().__init__(env)\n",
    "        self.tutor_rate = tutor_rate\n",
    "        self.nb_instructions = 0\n",
    "\n",
    "    def reset(self, **kwargs):\n",
    "        self.current_obs, info = self.env.reset(**kwargs)\n",
    "        self.tutor = random.random() <= self.tutor_rate\n",
    "        return self.current_obs, info\n",
    "\n",
    "    def tutor_instruction_signal(self, action):\n",
    "        if not self.tutor:\n",
    "            return action\n",
    "        position, velocity = self.current_obs\n",
    "        # Push in the direction that builds momentum\n",
    "\n",
    "        # push right when moving right in the left/middle region...\n",
    "        if ...:\n",
    "            self.nb_instructions += 1\n",
    "            return [1.0]\n",
    "        # ... push left when moving left near the bottom\n",
    "        elif ...:\n",
    "            self.nb_instructions += 1\n",
    "            return [-1.0]\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "        return action\n",
    "\n",
    "    def step(self, action):\n",
    "        action = self.tutor_instruction_signal(action)\n",
    "        obs, reward, terminated, truncated, info = self.env.step(action)\n",
    "        self.current_obs = obs\n",
    "        return obs, reward, terminated, truncated, info"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1cc1c9b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "tutor_cfg = replace(\n",
    "    cfg, wrappers=(lambda e: TutorInstructionWrapper(e, cfg.tutor_rate),)\n",
    ")\n",
    "_, td3_tutor = run_td3(tutor_cfg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a997233c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# 3. Behavioral cloning\n",
    "\n",
    "We bootstrap the policy by imitating a hand-coded **expert** that solves\n",
    "MountainCar with a simple momentum strategy: push left for the first ~50\n",
    "steps, then push right. We collect its trajectories and regress the actor's\n",
    "action towards the expert's."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb96b82a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def expert_action(step: int, num_envs: int, noise: bool = True) -> Tensor:\n",
    "    \"\"\"The scripted MountainCar expert: push left then right\"\"\"\n",
    "    base = -1.0 if step < 50 else 1.0\n",
    "    action = torch.full((num_envs, 1), base)\n",
    "    if noise:\n",
    "        action += (0.5 - torch.rand(num_envs, 1)) / 20\n",
    "    return action\n",
    "\n",
    "\n",
    "def collect_expert_data(\n",
    "    env_name: str, num_envs: int, n_steps: int\n",
    ") -> tuple[Tensor, Tensor]:\n",
    "    \"\"\"Run the scripted expert and collect (obs, action) pairs\"\"\"\n",
    "    env = VecEnv(env_name, num_envs, seed=0)\n",
    "    obs = env.reset()\n",
    "    obs_list, action_list = [], []\n",
    "    for step in range(n_steps):\n",
    "        action = expert_action(step, num_envs)\n",
    "        obs_list.append(obs)\n",
    "        action_list.append(action)\n",
    "        obs = env.step(action).obs\n",
    "    return torch.cat(obs_list), torch.cat(action_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52bd7b15",
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_cloning_loss(action: Tensor, expert_action: Tensor) -> Tensor:\n",
    "    \"\"\"Behavioral cloning loss: match the expert's actions\"\"\"\n",
    "    # Regress the actor's action towards the expert's\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e237df92",
   "metadata": {},
   "outputs": [],
   "source": [
    "def behavioral_cloning(\n",
    "    cfg: TD3Config, bc_steps: int = 500\n",
    ") -> ContinuousDeterministicActor:\n",
    "    env = VecEnv(cfg.env_name, 1, seed=0)\n",
    "    actor = ContinuousDeterministicActor(\n",
    "        env.observation_dim, cfg.actor_hidden, env.action_dim\n",
    "    )\n",
    "    optimizer = torch.optim.Adam(actor.parameters(), lr=cfg.lr)\n",
    "\n",
    "    obs, expert_a = collect_expert_data(cfg.env_name, cfg.n_envs or 1, 200)\n",
    "    for _ in tqdm(range(bc_steps)):\n",
    "        loss = compute_cloning_loss(actor(obs).value, expert_a)\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "    return actor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "860f1a3f",
   "metadata": {},
   "source": [
    "We clone the expert, then fine-tune the cloned policy with TD3."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0dc79c8d",
   "metadata": {},
   "outputs": [],
   "source": [
    "bc_steps = Profile.pick(500, fast_test=5)\n",
    "cloned_actor = behavioral_cloning(cfg, bc_steps=bc_steps)\n",
    "_, td3_cloned = run_td3(replace(cfg, seed=2), actor=cloned_actor)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3451bef",
   "metadata": {},
   "source": [
    "# Comparison\n",
    "\n",
    "The true (unwrapped) evaluation reward of the three approaches. Plain TD3\n",
    "typically stays near 0 (never solves), while the tutor and behavioral-cloning\n",
    "variants reach the flag."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd50c59d",
   "metadata": {},
   "outputs": [],
   "source": [
    "for name, ev in {\n",
    "    \"plain TD3\": td3_plain,\n",
    "    \"tutor\": td3_tutor,\n",
    "    \"cloning\": td3_cloned,\n",
    "}.items():\n",
    "    plt.plot([r.step for r in ev.history], [r.mean for r in ev.history], label=name)\n",
    "plt.xlabel(\"steps\")\n",
    "plt.ylabel(\"true cumulated reward\")\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40f0d44b",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "- Vary `tutor_rate`: too low gives no help, too high and the agent never\n",
    "  learns to act without the tutor.\n",
    "- The tutor never touches the *reward* — it only changes the actions taken\n",
    "  (and hence which transitions are stored). Discuss why this is enough to\n",
    "  escape the deceptive-gradient trap."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "MountainCar: tutor instructions and behavioural cloning where TD3 fails alone",
   "practical_name": "Guiding TD3 on a deceptive reward"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
