{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6be27f19",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we study **imitation learning**: learning to behave like an\n",
    "expert from a set of demonstration trajectories, *without* access to the\n",
    "environment's reward.\n",
    "\n",
    "We compare two approaches on `LunarLander` (discrete actions):\n",
    "\n",
    "1. **Behavioral cloning (BC)** — a supervised baseline: train the policy to\n",
    "   predict the expert's action in each demonstrated state;\n",
    "2. **GAIL** ([Generative Adversarial Imitation\n",
    "   Learning](https://arxiv.org/abs/1606.03476)) — train a **discriminator**\n",
    "   to tell expert transitions from the policy's, and use it as a reward to\n",
    "   train the policy with PPO. Policy and discriminator improve adversarially."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15dff4fc",
   "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": "bc394777",
   "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": "ca48c108",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import pickle\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 pathlib import Path\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": "code",
   "execution_count": null,
   "id": "d2e8ceec",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ebee457",
   "metadata": {},
   "source": [
    "# The expert demonstrations\n",
    "\n",
    "We load a single expert trajectory (from a well-trained PPO agent) on\n",
    "`LunarLander`: a set of $(s, a)$ pairs. This is *all* the supervision we get\n",
    "— no rewards."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4534ddef",
   "metadata": {},
   "outputs": [],
   "source": [
    "expert_path = Path(\"data\") / \"LunarLander-v2.expert.pkl\"\n",
    "with open(expert_path, \"rb\") as handle:\n",
    "    expert_data = pickle.load(handle)\n",
    "\n",
    "expert_states = expert_data[\"states\"].float()  # [N, obs_dim]\n",
    "expert_actions = expert_data[\"actions\"].long()  # [N]\n",
    "print(f\"{len(expert_actions)} expert transitions, obs dim {expert_states.shape[1]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2cb9388",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# The policy\n",
    "\n",
    "A standard discrete stochastic policy (as in PPO/A2C)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78fe792c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class DiscretePolicy(Actor[StochasticAction]):\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": "markdown",
   "id": "f5bae4cc",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Behavioral cloning\n",
    "\n",
    "The simplest baseline: treat imitation as supervised classification. Train\n",
    "the policy to maximize the log-probability of the expert action in each\n",
    "expert state (equivalently, minimize the cross-entropy)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1940a36",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def behavioral_cloning(policy, env_name, cfg) -> Evaluator:\n",
    "    optimizer = torch.optim.Adam(policy.parameters(), lr=cfg.lr)\n",
    "    evaluator = Evaluator(VecEnv(env_name, cfg.n_eval_envs, seed=1), every=0)\n",
    "\n",
    "    for step in tqdm(range(cfg.bc_steps)):\n",
    "        # One behavioral-cloning gradient step\n",
    "\n",
    "        logits = policy.model(expert_states)\n",
    "        loss = ...  # cross-entropy between logits and expert_actions\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "        if step % cfg.bc_eval_interval == 0:\n",
    "            evaluator.history.append(\n",
    "                _eval_result(step, evaluator.run(policy), evaluator)\n",
    "            )\n",
    "    return evaluator\n",
    "\n",
    "\n",
    "def _eval_result(step, rewards, evaluator):\n",
    "    from rl_mind.evaluation import EvalResult\n",
    "\n",
    "    is_best = float(rewards.mean()) > evaluator.best_reward\n",
    "    if is_best:\n",
    "        evaluator.best_reward = float(rewards.mean())\n",
    "    return EvalResult(step=step, rewards=rewards, is_best=is_best)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7db2c786",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# GAIL\n",
    "\n",
    "## The discriminator\n",
    "\n",
    "The discriminator $D(s, a)$ outputs a logit: high for transitions that look\n",
    "like the expert's, low for the policy's. It takes the observation and the\n",
    "**one-hot** action."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54037be7",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class Discriminator(nn.Module):\n",
    "    def __init__(self, obs_dim: int, n_actions: int, hidden: tuple[int, ...]):\n",
    "        super().__init__()\n",
    "        self.n_actions = n_actions\n",
    "        self.model = build_mlp([obs_dim + n_actions, *hidden, 1])\n",
    "\n",
    "    def forward(self, obs: Tensor, action: Tensor, noise: float = 0.0) -> Tensor:\n",
    "        if noise > 0:\n",
    "            obs = obs + torch.randn_like(obs) * noise\n",
    "        one_hot = F.one_hot(action, num_classes=self.n_actions).float()\n",
    "        return self.model(torch.cat([obs, one_hot], dim=-1)).squeeze(-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b7c2c1a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## GAE and PPO data (as in the PPO notebook)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc276085",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def compute_gae(gamma, lam, rollout, values, next_values, reward):\n",
    "    advantages = torch.zeros_like(reward)\n",
    "    gae = torch.zeros_like(reward[0])\n",
    "    for t in reversed(range(reward.shape[0])):\n",
    "        delta = (\n",
    "            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\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class PPOBatch(TensorStruct):\n",
    "    obs: Tensor\n",
    "    action: Tensor\n",
    "    old_log_prob: Tensor\n",
    "    advantage: Tensor\n",
    "    returns: Tensor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50e465a7",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c07e6b16",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class GAILConfig:\n",
    "    env_name: str = \"LunarLander-v3\"\n",
    "    seed: int = 1\n",
    "\n",
    "    #: BC baseline\n",
    "    bc_steps: int = Profile.pick(2_000, fast_test=20)\n",
    "    bc_eval_interval: int = Profile.pick(200, fast_test=10)\n",
    "\n",
    "    #: GAIL / PPO\n",
    "    max_updates: int = Profile.pick(3_000, fast_test=5)\n",
    "    n_envs: int = 8\n",
    "    n_steps: int = 20\n",
    "\n",
    "    gamma: float = 0.9\n",
    "    gae_lam: float = 0.9\n",
    "    epsilon: float = 0.2\n",
    "    entropy_coef: float = 1e-3\n",
    "    #: Discriminator / PPO inner epochs\n",
    "    opt_d_epochs: int = 10\n",
    "    opt_epochs: int = 10\n",
    "    batch_size: int = 256\n",
    "    #: GAIL reward is clamped to this range\n",
    "    reward_min: float = -10.0\n",
    "    reward_max: float = 0.0\n",
    "    #: Observation noise added when training the discriminator (regularization)\n",
    "    disc_noise: float = 1e-2\n",
    "\n",
    "    hidden: tuple[int, ...] = (64, 64)\n",
    "    lr: float = 1e-3\n",
    "\n",
    "    eval_interval: int = Profile.pick(5_000, fast_test=100)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e80ae3c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The GAIL training loop\n",
    "\n",
    "Each iteration:\n",
    "\n",
    "1. collect a rollout with the current policy;\n",
    "2. **train the discriminator** to classify expert vs policy transitions\n",
    "   (binary cross-entropy: expert → 1, policy → 0);\n",
    "3. **define the reward** $r(s, a) = \\log\\sigma(D(s, a))$ — high when the\n",
    "   discriminator is fooled — and use it (not the env reward) to train the\n",
    "   policy with PPO."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8da7253",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_gail(cfg: GAILConfig) -> 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.hidden, env.n_actions)\n",
    "    critic = build_mlp([env.observation_dim, *cfg.hidden, 1])\n",
    "    discriminator = Discriminator(env.observation_dim, env.n_actions, cfg.hidden)\n",
    "\n",
    "    policy_optimizer = torch.optim.Adam(policy.parameters(), lr=cfg.lr)\n",
    "    critic_optimizer = torch.optim.Adam(critic.parameters(), lr=cfg.lr)\n",
    "    disc_optimizer = torch.optim.Adam(discriminator.parameters(), lr=cfg.lr)\n",
    "    bce = nn.BCEWithLogitsLoss()\n",
    "\n",
    "    collector = RolloutCollector(env, policy)\n",
    "    run_dir = run_directory(f\"gail-{cfg.env_name}-S{cfg.seed}\")\n",
    "    writer = SummaryWriter(run_dir)\n",
    "    # Evaluation uses the TRUE environment reward (does imitation actually work?)\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",
    "        flat = rollout.flatten()\n",
    "\n",
    "        # --- 1) Discriminator training\n",
    "        # Train the discriminator (expert -> 1, policy -> 0)\n",
    "\n",
    "        for _ in range(cfg.opt_d_epochs):\n",
    "            d_expert = discriminator(expert_states, expert_actions, noise=cfg.disc_noise)\n",
    "            d_policy = discriminator(flat.obs, flat.action.value, noise=cfg.disc_noise)\n",
    "            disc_loss = bce(d_expert, ones) + bce(d_policy, zeros)\n",
    "            ...  # gradient step\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # --- 2) GAIL reward for the rollout transitions\n",
    "        # Compute the imitation reward from the discriminator\n",
    "\n",
    "        with torch.no_grad():\n",
    "            reward = ...  # log-sigmoid of D(s, a), clamped to [reward_min, reward_max]\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # --- 3) PPO update using the GAIL reward\n",
    "        with torch.no_grad():\n",
    "            values = critic(rollout.obs).squeeze(-1)\n",
    "            next_values = critic(rollout.next_obs).squeeze(-1)\n",
    "            advantage = compute_gae(\n",
    "                cfg.gamma, cfg.gae_lam, rollout, values, next_values, reward\n",
    "            )\n",
    "\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",
    "        for _ in range(cfg.opt_epochs):\n",
    "            for mb in minibatches(data, cfg.batch_size):\n",
    "                dist = policy.dist(mb.obs)\n",
    "                ratio = (dist.log_prob(mb.action) - mb.old_log_prob).exp()\n",
    "                adv = (mb.advantage - mb.advantage.mean()) / (mb.advantage.std() + 1e-8)\n",
    "                policy_loss = -torch.minimum(\n",
    "                    ratio * adv,\n",
    "                    ratio.clamp(1 - cfg.epsilon, 1 + cfg.epsilon) * adv,\n",
    "                ).mean()\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).squeeze(-1), mb.returns)\n",
    "                critic_optimizer.zero_grad()\n",
    "                critic_loss.backward()\n",
    "                critic_optimizer.step()\n",
    "\n",
    "        writer.add_scalar(\"disc/loss\", disc_loss.item(), collector.steps)\n",
    "        writer.add_scalar(\"disc/reward\", reward.mean().item(), collector.steps)\n",
    "        if result := evaluator.run_if_needed(collector.steps, policy):\n",
    "            pbar.set_description(f\"true reward eval={result.mean:7.1f}\")\n",
    "\n",
    "    return evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "404c09be",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ded255c",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f51f3981",
   "metadata": {},
   "source": [
    "## Behavioral cloning baseline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49f103ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = GAILConfig()\n",
    "bc_policy = DiscretePolicy(8, cfg.hidden, 4)\n",
    "bc = behavioral_cloning(bc_policy, cfg.env_name, cfg)\n",
    "print(\"BC best true reward:\", round(bc.best_reward, 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "600265e3",
   "metadata": {},
   "source": [
    "## GAIL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d06f85e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "gail = run_gail(cfg)\n",
    "print(\"GAIL best true reward:\", round(gail.best_reward, 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b20c1319",
   "metadata": {},
   "outputs": [],
   "source": [
    "gail.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16cbd354",
   "metadata": {},
   "source": [
    "## Comparison\n",
    "\n",
    "We plot the *true* environment reward (never used for training) achieved by\n",
    "the two imitators. BC tends to plateau (it cannot recover from states outside\n",
    "the demonstrations — *distribution shift*), while GAIL, by interacting with\n",
    "the environment, is usually more robust."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c391578b",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(\n",
    "    [r.step for r in bc.history],\n",
    "    [r.mean for r in bc.history],\n",
    "    label=\"behavioral cloning\",\n",
    ")\n",
    "plt.plot([r.step for r in gail.history], [r.mean for r in gail.history], label=\"GAIL\")\n",
    "plt.xlabel(\"training step\")\n",
    "plt.ylabel(\"true cumulated reward\")\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e2e4b12",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "- The discriminator can *overfit* the single expert trajectory and stop\n",
    "  providing a useful gradient. Observe `disc/loss` in tensorboard and try\n",
    "  adding more observation noise (`disc_noise`) or fewer discriminator epochs.\n",
    "- GAIL recovers a reward, not just a policy. Plot the learned reward\n",
    "  $\\log\\sigma(D(s, a))$ over states and compare it with the true reward."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Learning from demonstrations, without the environment's reward",
   "practical_name": "Imitation learning: BC and GAIL"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
