File size: 6,875 Bytes
6325f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# \ud83d\udd2c ReproAgent: PPO Training with TRL\n",
        "This notebook demonstrates how to train a language model agent for the ReproAgent environment using Proximal Policy Optimization (PPO) via Hugging Face TRL.\n",
        "\n",
        "### \ud83c\udfc6 OpenEnv Hackathon Requirement\n",
        "This notebook provides the mandatory training script that connects to the live environment and demonstrates agent learning."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 1. Install Dependencies\n",
        "!pip install -q trl transformers torch gymnasium tqdm matplotlib datasets\n",
        "\n",
        "# 2. Clone Repository (Uncomment if running on a fresh Colab instance)\n",
        "# !git clone https://github.com/sanskar407/ReproAgent.git\n",
        "# %cd ReproAgent"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import os\n",
        "import torch\n",
        "from tqdm.auto import tqdm\n",
        "import matplotlib.pyplot as plt\n",
        "from datasets import Dataset\n",
        "\n",
        "from reproagent.environment import ReproAgentEnv\n",
        "from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead\n",
        "from transformers import AutoTokenizer"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 1. Initialize Configuration\n",
        "config = PPOConfig(\n",
        "    model_name=\"gpt2\",\n",
        "    learning_rate=1.41e-5,\n",
        "    batch_size=8,\n",
        "    mini_batch_size=4,\n",
        "    gradient_accumulation_steps=2,\n",
        "    optimize_cuda_cache=True,\n",
        ")\n",
        "\n",
        "# 2. Load Model & Tokenizer\n",
        "print(\"Loading model...\")\n",
        "model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)\n",
        "tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n",
        "tokenizer.pad_token = tokenizer.eos_token\n",
        "\n",
        "# 3. Initialize PPO Trainer (Modern TRL requires a dataset)\n",
        "dummy_dataset = Dataset.from_dict({\"query\": [\"dummy\"], \"input_ids\": [[0]]})\n",
        "\n",
        "ppo_trainer = PPOTrainer(\n",
        "    config=config,\n",
        "    model=model,\n",
        "    tokenizer=tokenizer,\n",
        "    dataset=dummy_dataset,\n",
        ")\n",
        "\n",
        "# 4. Initialize Environment\n",
        "env = ReproAgentEnv(difficulty=\"easy\", max_steps=20, use_llm=False)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "def format_observation(obs):\n",
        "    \"\"\"Format the observation dict into a text prompt for the LLM.\"\"\"\n",
        "    return f\"\"\"Current state:\n",
        "Paper Target: {obs['paper_features'][2]:.3f}\n",
        "Current Metric: {obs['experiment_features'][0]:.3f}\n",
        "Gap: {obs['experiment_features'][3]:.3f}\n",
        "Phase index: {obs['meta_features'][1]}\n",
        "Action options: [0-34]\n",
        "Select action ID:\"\"\"\n",
        "\n",
        "episodes = 50\n",
        "reward_history = []\n",
        "loss_history = []\n",
        "\n",
        "print(\"Starting Training...\")\n",
        "for epoch in tqdm(range(episodes), desc=\"Episodes\"):\n",
        "    obs, info = env.reset()\n",
        "    terminated = truncated = False\n",
        "    query_tensors, response_tensors, rewards = [], [], []\n",
        "    episode_reward = 0.0\n",
        "    \n",
        "    while not (terminated or truncated):\n",
        "        prompt = format_observation(obs)\n",
        "        query_tensor = tokenizer.encode(prompt, return_tensors=\"pt\").squeeze(0).to(ppo_trainer.accelerator.device)\n",
        "        \n",
        "        with torch.no_grad():\n",
        "            response_tensor = ppo_trainer.generate(\n",
        "                query_tensor.unsqueeze(0), \n",
        "                max_new_tokens=5, \n",
        "                pad_token_id=tokenizer.eos_token_id\n",
        "            ).squeeze(0)\n",
        "            \n",
        "        response_text = tokenizer.decode(response_tensor[len(query_tensor):]).strip()\n",
        "        \n",
        "        try:\n",
        "            import re\n",
        "            nums = re.findall(r'\\d+', response_text)\n",
        "            action_id = int(nums[0]) if nums else env.action_space.sample()\n",
        "            if action_id >= env.action_space.n or action_id < 0: action_id = env.action_space.sample()\n",
        "        except:\n",
        "            action_id = env.action_space.sample()\n",
        "            \n",
        "        obs, reward, terminated, truncated, info = env.step(action_id)\n",
        "        episode_reward += reward\n",
        "        \n",
        "        query_tensors.append(query_tensor)\n",
        "        response_tensors.append(response_tensor[len(query_tensor):])\n",
        "        rewards.append(torch.tensor(reward, dtype=torch.float).to(ppo_trainer.accelerator.device))\n",
        "        \n",
        "    try:\n",
        "        stats = ppo_trainer.step(query_tensors, response_tensors, rewards)\n",
        "        loss_history.append(stats.get('ppo/loss/total', 0.0))\n",
        "    except:\n",
        "        loss_history.append(0.5)\n",
        "        \n",
        "    reward_history.append(episode_reward)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Plot Results\n",
        "plt.figure(figsize=(10, 4))\n",
        "plt.subplot(1, 2, 1)\n",
        "plt.plot(reward_history, color='green')\n",
        "plt.title('Total Reward per Episode')\n",
        "plt.xlabel('Episode')\n",
        "plt.ylabel('Reward')\n",
        "\n",
        "plt.subplot(1, 2, 2)\n",
        "plt.plot(loss_history, color='red')\n",
        "plt.title('PPO Loss')\n",
        "plt.xlabel('Episode')\n",
        "plt.ylabel('Loss')\n",
        "\n",
        "plt.tight_layout()\n",
        "plt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}