Addyk24 commited on
Commit
e911fbe
·
verified ·
1 Parent(s): 35e5549

Upload grpo_training.ipynb

Browse files
Files changed (1) hide show
  1. grpo_training.ipynb +1090 -0
grpo_training.ipynb ADDED
@@ -0,0 +1,1090 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "1df5ac03",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "!pip install -q \\\n",
11
+ "datasets==4.8.4 \\\n",
12
+ "groq==1.2.0 \\\n",
13
+ "openenv-core==0.2.3 \\\n",
14
+ "sentence-transformers==5.4.1 \\\n",
15
+ "torch==2.11.0 \\\n",
16
+ "transformers==5.6.2 \\\n",
17
+ "trl==1.2.0\n",
18
+ "\n",
19
+ "print(\"Dependencies installed successfully!\")"
20
+ ]
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "execution_count": null,
25
+ "id": "26b26888",
26
+ "metadata": {},
27
+ "outputs": [],
28
+ "source": [
29
+ "from __future__ import annotations\n",
30
+ "\n",
31
+ "import argparse\n",
32
+ "import json\n",
33
+ "import random\n",
34
+ "import os\n",
35
+ "import re\n",
36
+ "import time\n",
37
+ "from pathlib import Path\n",
38
+ "from typing import Optional\n",
39
+ "\n",
40
+ "try:\n",
41
+ " from dotenv import load_dotenv\n",
42
+ " load_dotenv()\n",
43
+ "except ImportError:\n",
44
+ " # Keep script runnable even if python-dotenv is not installed.\n",
45
+ " pass\n",
46
+ "\n",
47
+ "\n",
48
+ "try:\n",
49
+ " import matplotlib\n",
50
+ " matplotlib.use(\"Agg\") # non-interactive backend for servers\n",
51
+ " import matplotlib.pyplot as plt\n",
52
+ " HAS_PLT = True\n",
53
+ "except ImportError:\n",
54
+ " HAS_PLT = False\n",
55
+ "\n",
56
+ "HAS_UNSLOTH = False\n",
57
+ "FastLanguageModel = None\n",
58
+ "\n",
59
+ "\n",
60
+ "try:\n",
61
+ " from trl import GRPOConfig, GRPOTrainer\n",
62
+ " HAS_TRL = True\n",
63
+ " print(\"TRL loaded OK\")\n",
64
+ "except Exception as e:\n",
65
+ " print(f\"TRL FAILED: {e}\")\n",
66
+ " HAS_TRL = False\n",
67
+ "\n",
68
+ "try:\n",
69
+ " from datasets import Dataset\n",
70
+ " HAS_DATASETS = True\n",
71
+ "except ImportError:\n",
72
+ " HAS_DATASETS = False\n",
73
+ "\n",
74
+ "try:\n",
75
+ " from transformers import AutoModelForCausalLM, AutoTokenizer\n",
76
+ " HAS_TRANSFORMERS = True\n",
77
+ "except ImportError:\n",
78
+ " HAS_TRANSFORMERS = False\n",
79
+ "\n",
80
+ "# Local imports\n",
81
+ "from envs.environment import WorkSpaceEnvironment\n",
82
+ "from models.schemas import WorkSpaceAction"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "execution_count": null,
88
+ "id": "12225440",
89
+ "metadata": {},
90
+ "outputs": [],
91
+ "source": [
92
+ "TOPICS_FILE = Path(\"ai_pm_prompts.json\")\n",
93
+ "OUTPUT_DIR = Path(\"artifacts/grpo_state_based\")"
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "execution_count": null,
99
+ "id": "8b3d0fd0",
100
+ "metadata": {},
101
+ "outputs": [],
102
+ "source": [
103
+ "HIDDEN_CONSTRAINTS = {\n",
104
+ " \"Finance\": \"Budget must not exceed $50k.\",\n",
105
+ " \"Security\": \"Must include biometric 2FA.\",\n",
106
+ " \"UX\": \"Checkout must be a single click.\",\n",
107
+ "}\n",
108
+ "\n",
109
+ "# ── Action templates the model should learn to produce\n",
110
+ "ORACLE_ACTIONS = {\n",
111
+ " \"ask_finance\": json.dumps({\n",
112
+ " \"action_type\": \"message_expert\", \"target\": \"Finance\",\n",
113
+ " \"content\": \"What is the hard budget ceiling the PRD must respect for launch?\"\n",
114
+ " }),\n",
115
+ " \"ask_security\": json.dumps({\n",
116
+ " \"action_type\": \"message_expert\", \"target\": \"Security\",\n",
117
+ " \"content\": \"What authentication controls must the PRD include? Is biometric 2FA required?\"\n",
118
+ " }),\n",
119
+ " \"ask_ux\": json.dumps({\n",
120
+ " \"action_type\": \"message_expert\", \"target\": \"UX\",\n",
121
+ " \"content\": \"What checkout experience is required? Should we target a single-click flow?\"\n",
122
+ " }),\n",
123
+ " \"propose_draft\": json.dumps({\n",
124
+ " \"action_type\": \"propose_draft\", \"target\": \"All\",\n",
125
+ " \"content\": (\n",
126
+ " \"PRD Draft:\\n\"\n",
127
+ " \"1. Budget: Launch scope capped at $50k.\\n\"\n",
128
+ " \"2. Security: Biometric 2FA required for login and sensitive actions.\\n\"\n",
129
+ " \"3. UX: Single-click checkout flow.\"\n",
130
+ " ),\n",
131
+ " }),\n",
132
+ " \"submit_final\": json.dumps({\n",
133
+ " \"action_type\": \"submit_final\", \"target\": None,\n",
134
+ " \"content\": (\n",
135
+ " \"Final PRD:\\n\"\n",
136
+ " \"1. Budget cap: All launch costs must stay at or below $50k.\\n\"\n",
137
+ " \"2. Security: The app must enforce biometric 2FA for all authentication.\\n\"\n",
138
+ " \"3. UX: Checkout must be implemented as a true single-click experience.\"\n",
139
+ " ),\n",
140
+ " }),\n",
141
+ "}"
142
+ ]
143
+ },
144
+ {
145
+ "cell_type": "markdown",
146
+ "id": "760766ee",
147
+ "metadata": {},
148
+ "source": [
149
+ "### Load Topic"
150
+ ]
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "execution_count": null,
155
+ "id": "65205766",
156
+ "metadata": {},
157
+ "outputs": [],
158
+ "source": [
159
+ "def load_topics(limit: int = 50) -> list[str]:\n",
160
+ " if TOPICS_FILE.exists():\n",
161
+ " with TOPICS_FILE.open() as f:\n",
162
+ " return json.load(f)[:limit]\n",
163
+ " return [\n",
164
+ " \"Draft a Mobile App PRD for a FinTech startup targeting emerging markets.\",\n",
165
+ " \"Build an AI-driven healthcare platform for enterprise customers.\",\n",
166
+ " \"Create a SaaS analytics tool for regulatory-heavy industries.\",\n",
167
+ " \"Design a gaming platform for Gen Z users with real-time features.\",\n",
168
+ " \"Develop a cross-platform product for low-bandwidth regions.\",\n",
169
+ " ]\n"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "markdown",
174
+ "id": "7e76846b",
175
+ "metadata": {},
176
+ "source": [
177
+ "### Parse Action (Handle fenced responses like ```json ... ```)"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "execution_count": null,
183
+ "id": "6b91f1f9",
184
+ "metadata": {},
185
+ "outputs": [],
186
+ "source": [
187
+ "def parse_action(text: str) -> Optional[WorkSpaceAction]:\n",
188
+ " \"\"\"Parse a JSON action from model output. Returns None on failure.\"\"\"\n",
189
+ " text = text.strip()\n",
190
+ " if text.startswith(\"```\"):\n",
191
+ " text = re.sub(r\"^```(?:json)?\\s*\", \"\", text)\n",
192
+ " text = re.sub(r\"\\s*```$\", \"\", text)\n",
193
+ "\n",
194
+ " text = text.strip()\n",
195
+ " try:\n",
196
+ " # Fast path: entire completion is valid JSON.\n",
197
+ " return WorkSpaceAction(**json.loads(text))\n",
198
+ " except Exception:\n",
199
+ " pass\n",
200
+ "\n",
201
+ " # Fallback: find the first JSON object that includes action_type.\n",
202
+ " try:\n",
203
+ " idx = text.find(\"{\")\n",
204
+ " while idx != -1:\n",
205
+ " depth = 0\n",
206
+ " for end in range(idx, len(text)):\n",
207
+ " if text[end] == \"{\":\n",
208
+ " depth += 1\n",
209
+ " elif text[end] == \"}\":\n",
210
+ " depth -= 1\n",
211
+ " if depth == 0:\n",
212
+ " candidate = text[idx:end + 1]\n",
213
+ " if '\"action_type\"' in candidate:\n",
214
+ " return WorkSpaceAction(**json.loads(candidate))\n",
215
+ " break\n",
216
+ " idx = text.find(\"{\", idx + 1)\n",
217
+ " return None\n",
218
+ " except Exception:\n",
219
+ " return None"
220
+ ]
221
+ },
222
+ {
223
+ "cell_type": "markdown",
224
+ "id": "8c6b5cba",
225
+ "metadata": {},
226
+ "source": [
227
+ "### CONTRAINTS"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "execution_count": null,
233
+ "id": "4d01ee84",
234
+ "metadata": {},
235
+ "outputs": [],
236
+ "source": [
237
+ "def lexical_overlap(a: str, b: str) -> float:\n",
238
+ " \"\"\"Simple token overlap score in [0,1] for dense content shaping.\"\"\"\n",
239
+ " toks_a = set(re.findall(r\"[a-z0-9]+\", (a or \"\").lower()))\n",
240
+ " toks_b = set(re.findall(r\"[a-z0-9]+\", (b or \"\").lower()))\n",
241
+ " if not toks_a or not toks_b:\n",
242
+ " return 0.0\n",
243
+ " inter = len(toks_a & toks_b)\n",
244
+ " denom = max(1, min(len(toks_a), len(toks_b)))\n",
245
+ " return inter / denom\n",
246
+ "\n",
247
+ "\n",
248
+ "def format_discovered(env: WorkSpaceEnvironment) -> str:\n",
249
+ " lines = []\n",
250
+ " for name, expert in env.state().experts.items():\n",
251
+ " status = \"✓ DISCOVERED\" if expert.constraint_discovered_by_agent else \"? unknown\"\n",
252
+ " lines.append(f\" {name}: {status}\")\n",
253
+ " return \"\\n\".join(lines)\n"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "markdown",
258
+ "id": "3473c0ef",
259
+ "metadata": {},
260
+ "source": [
261
+ "### AGENT PROMPT"
262
+ ]
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "execution_count": null,
267
+ "id": "76497a28",
268
+ "metadata": {},
269
+ "outputs": [],
270
+ "source": [
271
+ "AGENT_SYSTEM_PROMPT = \"\"\"You are an expert AI Project Manager in a multi-stakeholder negotiation.\n",
272
+ "\n",
273
+ "TASK: Produce a final PRD that satisfies ALL three experts — Finance, Security, and UX.\n",
274
+ "Each expert holds a hidden constraint you must discover through targeted questions.\n",
275
+ "\n",
276
+ "STRATEGY:\n",
277
+ " 1. Message each expert INDIVIDUALLY (not \"All\") to discover their constraint.\n",
278
+ " 2. Once all constraints are known, propose a draft.\n",
279
+ " 3. Refine if needed, then submit_final before turn 15.\n",
280
+ "\n",
281
+ "ANTI-PATTERNS (will be penalized):\n",
282
+ " - Broadcasting to \"All\" when gathering requirements → -0.3 penalty\n",
283
+ " - Repeating a question already answered → -0.4 penalty\n",
284
+ " - Submitting without discovering constraints → low harmonic mean score\n",
285
+ "\n",
286
+ "CURRENT DISCOVERED CONSTRAINTS:\n",
287
+ "{discovered}\n",
288
+ "\n",
289
+ "You are a strict API. Respond with ONLY raw, valid JSON. \n",
290
+ "DO NOT wrap the JSON in markdown formatting (no ```json). \n",
291
+ "DO NOT output any conversational text.\n",
292
+ "End your response immediately after the closing }}.\n",
293
+ "{{\"action_type\": \"message_expert\" | \"propose_draft\" | \"submit_final\",\n",
294
+ " \"target\": \"Finance\" | \"Security\" | \"UX\" | \"All\" | null,\n",
295
+ " \"content\": \"your message\"}}\"\"\"\n"
296
+ ]
297
+ },
298
+ {
299
+ "cell_type": "markdown",
300
+ "id": "58fa5c08",
301
+ "metadata": {},
302
+ "source": [
303
+ "### STATE PROMPT FOR DATASET GENERATION\n",
304
+ "\n",
305
+ "- Use Qwen-compatible ChatML formatting to improve stop behavior.\n",
306
+ "- Qwen instruct models are much more likely to terminate with <|im_end|>\n",
307
+ "- when prompted in this native format."
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "execution_count": null,
313
+ "id": "4e24ca2e",
314
+ "metadata": {},
315
+ "outputs": [],
316
+ "source": [
317
+ "def build_state_prompt(\n",
318
+ " topic: str,\n",
319
+ " turn: int,\n",
320
+ " feedback_so_far: str,\n",
321
+ " discovered: str,\n",
322
+ " conversation_history: str = \"\",\n",
323
+ ") -> str:\n",
324
+ " \"\"\"\n",
325
+ " Build a prompt representing a specific game state.\n",
326
+ " This is what gets fed to GRPOTrainer as the 'prompt' field.\n",
327
+ " \"\"\"\n",
328
+ " system = AGENT_SYSTEM_PROMPT.format(discovered=discovered)\n",
329
+ "\n",
330
+ " user_content = (\n",
331
+ " f\"NEGOTIATION TASK: {topic}\\n\\n\"\n",
332
+ " f\"TURN: {turn}/15\\n\\n\"\n",
333
+ " )\n",
334
+ "\n",
335
+ " if conversation_history:\n",
336
+ " user_content += f\"CONVERSATION SO FAR:\\n{conversation_history}\\n\\n\"\n",
337
+ "\n",
338
+ " user_content += f\"LATEST FEEDBACK:\\n{feedback_so_far}\\n\\nWhat is your next action?\"\n",
339
+ "\n",
340
+ "\n",
341
+ " return (\n",
342
+ " f\"<|im_start|>system\\n{system}<|im_end|>\\n\"\n",
343
+ " f\"<|im_start|>user\\n{user_content}<|im_end|>\\n\"\n",
344
+ " f\"<|im_start|>assistant\\n\"\n",
345
+ " )"
346
+ ]
347
+ },
348
+ {
349
+ "cell_type": "markdown",
350
+ "id": "7f8cf7ea",
351
+ "metadata": {},
352
+ "source": [
353
+ "### State Dataset Builder"
354
+ ]
355
+ },
356
+ {
357
+ "cell_type": "code",
358
+ "execution_count": null,
359
+ "id": "60877e63",
360
+ "metadata": {},
361
+ "outputs": [],
362
+ "source": [
363
+ "def build_state_dataset(topics: list[str], states_per_topic: int = 5) -> list[dict]:\n",
364
+ " \"\"\"\n",
365
+ " Build a dataset of negotiation states using the EASY mode environment.\n",
366
+ " Each record represents one (state → optimal_action) training example.\n",
367
+ "\n",
368
+ " We run oracle trajectories through the environment to get realistic\n",
369
+ " expert feedback, then snapshot the state at each turn.\n",
370
+ "\n",
371
+ " This is the key fix: instead of hoping the model learns from full episodes,\n",
372
+ " we give it explicit training signal at every decision point.\n",
373
+ " \"\"\"\n",
374
+ " env = WorkSpaceEnvironment(mode=\"medium\")\n",
375
+ " records = []\n",
376
+ "\n",
377
+ " # Oracle action sequence for easy mode\n",
378
+ " oracle_sequence = [\n",
379
+ " (\"ask_finance\", WorkSpaceAction(\n",
380
+ " action_type=\"message_expert\", target=\"Finance\",\n",
381
+ " content=\"What budget ceiling must the PRD respect?\"\n",
382
+ " )),\n",
383
+ " (\"ask_security\", WorkSpaceAction(\n",
384
+ " action_type=\"message_expert\", target=\"Security\",\n",
385
+ " content=\"What authentication requirements must be included?\"\n",
386
+ " )),\n",
387
+ " (\"ask_ux\", WorkSpaceAction(\n",
388
+ " action_type=\"message_expert\", target=\"UX\",\n",
389
+ " content=\"What checkout flow is required?\"\n",
390
+ " )),\n",
391
+ " (\"propose_draft\", WorkSpaceAction(\n",
392
+ " action_type=\"propose_draft\", target=\"All\",\n",
393
+ " content=\"PRD: Budget at or below $50k. Biometric 2FA required. Single-click checkout.\"\n",
394
+ " )),\n",
395
+ " (\"submit_final\", WorkSpaceAction(\n",
396
+ " action_type=\"submit_final\", target=None,\n",
397
+ " content=\"Final PRD: Budget capped at $50k. Biometric 2FA for auth. Single-click checkout.\"\n",
398
+ " )),\n",
399
+ " ]\n",
400
+ "\n",
401
+ "\n",
402
+ " for topic in topics:\n",
403
+ " obs = env.reset(topic)\n",
404
+ " conversation_history = \"\"\n",
405
+ " discovered = \" Finance: ? unknown\\n Security: ? unknown\\n UX: ? unknown\"\n",
406
+ "\n",
407
+ " for step_idx, (action_key, oracle_action) in enumerate(oracle_sequence):\n",
408
+ " if obs.done:\n",
409
+ " break\n",
410
+ "\n",
411
+ " # Snapshot the state BEFORE taking the action\n",
412
+ " prompt = build_state_prompt(\n",
413
+ " topic=topic,\n",
414
+ " turn=obs.current_turn,\n",
415
+ " feedback_so_far=obs.feedback,\n",
416
+ " discovered=discovered,\n",
417
+ " conversation_history=conversation_history,\n",
418
+ " )\n",
419
+ "\n",
420
+ " records.append({\n",
421
+ " \"prompt\": prompt,\n",
422
+ " \"topic\": topic,\n",
423
+ " \"turn\": obs.current_turn,\n",
424
+ " \"oracle_action\": ORACLE_ACTIONS[action_key],\n",
425
+ " # These metadata fields help with debugging and post-analysis\n",
426
+ " \"step_idx\": step_idx,\n",
427
+ " \"discovered_before\": discovered,\n",
428
+ " })\n",
429
+ "\n",
430
+ " # Step forward with oracle action to get next state\n",
431
+ " obs = env.step(oracle_action)\n",
432
+ " conversation_history += (\n",
433
+ " f\"Turn {step_idx}: {oracle_action.action_type} → {oracle_action.target}\\n\"\n",
434
+ " f\"Feedback: {obs.feedback[:120]}...\\n\"\n",
435
+ " )\n",
436
+ " discovered = format_discovered(env)\n",
437
+ "\n",
438
+ " if step_idx >= states_per_topic - 1:\n",
439
+ " break\n",
440
+ "\n",
441
+ " # Add negative-pattern states (what NOT to do)\n",
442
+ " records.extend(build_negative_states(topics[:5]))\n",
443
+ " # Upweight late-stage \"submit_final\" states so policy learns to finish.\n",
444
+ " late_stage = build_late_stage_states(topics)\n",
445
+ " records.extend(late_stage)\n",
446
+ " records.extend(late_stage)\n",
447
+ " records.extend(late_stage)\n",
448
+ " random.shuffle(records)\n",
449
+ "\n",
450
+ " print(f\"Built {len(records)} training states from {len(topics)} topics\")\n",
451
+ " return records"
452
+ ]
453
+ },
454
+ {
455
+ "cell_type": "markdown",
456
+ "id": "8db26d85",
457
+ "metadata": {},
458
+ "source": [
459
+ "### Late Stage State and Negative Pattern State (what NOT to do)\n",
460
+ "\n",
461
+ "- Upweight late-stage \"submit_final\" states so policy learns to finish."
462
+ ]
463
+ },
464
+ {
465
+ "cell_type": "code",
466
+ "execution_count": null,
467
+ "id": "a75ccb32",
468
+ "metadata": {},
469
+ "outputs": [],
470
+ "source": [
471
+ "def build_late_stage_states(topics: list[str]) -> list[dict]:\n",
472
+ " \"\"\"\n",
473
+ " FIX 3: Inject guaranteed late-stage states.\n",
474
+ " Forces the model to learn how to synthesize and submit the final PRD.\n",
475
+ " \"\"\"\n",
476
+ " late_records = []\n",
477
+ " for topic in topics:\n",
478
+ " prompt = build_state_prompt(\n",
479
+ " topic=topic,\n",
480
+ " turn=4,\n",
481
+ " feedback_so_far=\"UX: The checkout must be a single click.\",\n",
482
+ " discovered=\" Finance: ✓ DISCOVERED\\n Security: ✓ DISCOVERED\\n UX: ✓ DISCOVERED\",\n",
483
+ " conversation_history=(\n",
484
+ " \"Turn 0: message_expert → Finance\\nFeedback: The budget cap is $50k.\\n\"\n",
485
+ " \"Turn 1: message_expert → Security\\nFeedback: Biometric 2FA is strictly required.\\n\"\n",
486
+ " \"Turn 2: message_expert → UX\\nFeedback: Checkout must be a single click.\\n\"\n",
487
+ " )\n",
488
+ " )\n",
489
+ " late_records.append({\n",
490
+ " \"prompt\": prompt,\n",
491
+ " \"topic\": topic,\n",
492
+ " \"turn\": 4,\n",
493
+ " \"oracle_action\": ORACLE_ACTIONS[\"submit_final\"],\n",
494
+ " \"step_idx\": 4,\n",
495
+ " \"discovered_before\": \" Finance: ✓ DISCOVERED\\n Security: ✓ DISCOVERED\\n UX: ✓ DISCOVERED\",\n",
496
+ " })\n",
497
+ " return late_records\n",
498
+ "\n",
499
+ "# negative sates that tells what not to do\n",
500
+ "\n",
501
+ "def build_negative_states(topics: list[str]) -> list[dict]:\n",
502
+ " \"\"\"\n",
503
+ " States where the agent is in a bad situation (repeated question, wrong phase).\n",
504
+ " These teach the model to recover, not just follow the oracle.\n",
505
+ " \"\"\"\n",
506
+ " negative_records = []\n",
507
+ "\n",
508
+ " for topic in topics:\n",
509
+ " # State: Finance already answered, agent is about to repeat\n",
510
+ " prompt = build_state_prompt(\n",
511
+ " topic=topic,\n",
512
+ " turn=2,\n",
513
+ " feedback_so_far=(\n",
514
+ " \"Finance: As I mentioned, we have a strict $50k budget cap. \"\n",
515
+ " \"This is the same answer I gave before.\"\n",
516
+ " ),\n",
517
+ " discovered=\" Finance: ✓ DISCOVERED\\n Security: ? unknown\\n UX: ? unknown\",\n",
518
+ " conversation_history=(\n",
519
+ " \"Turn 0: message_expert → Finance\\n\"\n",
520
+ " \"Feedback: Finance: The budget cap is $50k. Don't go over it.\\n\"\n",
521
+ " \"Turn 1: message_expert → Finance\\n\"\n",
522
+ " \"Feedback: Finance: I already told you — $50k. Ask someone else.\\n\"\n",
523
+ " ),\n",
524
+ " )\n",
525
+ " negative_records.append({\n",
526
+ " \"prompt\": prompt,\n",
527
+ " \"topic\": topic,\n",
528
+ " \"turn\": 2,\n",
529
+ " \"oracle_action\": ORACLE_ACTIONS[\"ask_security\"], # Should pivot to Security\n",
530
+ " \"step_idx\": -1, # Negative example\n",
531
+ " \"discovered_before\": \"Finance: ✓ DISCOVERED\",\n",
532
+ " })\n",
533
+ "\n",
534
+ " return negative_records"
535
+ ]
536
+ },
537
+ {
538
+ "cell_type": "markdown",
539
+ "id": "4f25c978",
540
+ "metadata": {},
541
+ "source": [
542
+ "### Reward Function\n",
543
+ "- Formatting Penalty.\n",
544
+ "- Anti-Pattern Penalties.\n",
545
+ "- Massive penalty for broadcasting (Reward Hacking).\n",
546
+ "- Penalty for empty or trivially short drafts/finals (short expert questions are often valid and should not be over-penalized)\n",
547
+ "- Penalize very long outputs; they correlate with max-length clipping.\n",
548
+ "- Hard penalty for non-terminated JSON-like responses.\n",
549
+ "- Strongly discourage invalid action/target combinations\n",
550
+ "- HEURISTIC STATE GRADING\n",
551
+ "- Did it try to submit before gathering all constraints?\n",
552
+ "- ORACLE-GUIDED DENSE SHAPING (This gives non-binary signal and prevents reward plateaus)\n",
553
+ "- Late turns should avoid endless questioning/proposals\n",
554
+ "- Keeping the reward in stable range for GRPO"
555
+ ]
556
+ },
557
+ {
558
+ "cell_type": "code",
559
+ "execution_count": null,
560
+ "id": "b082cf4c",
561
+ "metadata": {},
562
+ "outputs": [],
563
+ "source": [
564
+ "def make_reward_fn():\n",
565
+ " \"\"\"\n",
566
+ " Evaluates the model's actions instantly and locally.\n",
567
+ " No live API calls. No reward hacking loopholes.\n",
568
+ " \"\"\"\n",
569
+ " def reward_fn(completions: list[str], prompts: list[str], **kwargs) -> list[float]:\n",
570
+ " rewards = []\n",
571
+ " oracle_actions = kwargs.get(\"oracle_action\", [None] * len(completions))\n",
572
+ " turns = kwargs.get(\"turn\", [None] * len(completions))\n",
573
+ "\n",
574
+ " for completion, prompt, oracle_raw, turn in zip(completions, prompts, oracle_actions, turns):\n",
575
+ " action = parse_action(completion)\n",
576
+ "\n",
577
+ " # 1. Formatting Penalty\n",
578
+ " if action is None:\n",
579
+ " rewards.append(-0.5)\n",
580
+ " continue\n",
581
+ "\n",
582
+ " reward = 0.0\n",
583
+ " completion_text = (completion or \"\").strip()\n",
584
+ "\n",
585
+ " # ── 2. YOUR ANTI-PATTERN PENALTIES ──\n",
586
+ " \n",
587
+ " # Massive penalty for broadcasting (Reward Hacking)\n",
588
+ " if action.target == \"All\":\n",
589
+ " reward -= 1.0 \n",
590
+ " \n",
591
+ " # Penalty for empty or trivially short drafts/finals\n",
592
+ " # (short expert questions are often valid and should not be over-penalized)\n",
593
+ " if action.action_type in {\"propose_draft\", \"submit_final\"} and len((action.content or \"\").split()) < 5:\n",
594
+ " reward -= 0.2\n",
595
+ "\n",
596
+ " # Penalize very long outputs; they correlate with max-length clipping.\n",
597
+ " if len((action.content or \"\").split()) > 80:\n",
598
+ " reward -= 0.2\n",
599
+ " if len(completion_text) > 320:\n",
600
+ " reward -= 0.15\n",
601
+ "\n",
602
+ " # Encourage strict JSON-only behavior: starts with { and ends with }.\n",
603
+ " is_strict_json = completion_text.startswith(\"{\") and completion_text.endswith(\"}\")\n",
604
+ " if is_strict_json:\n",
605
+ " reward += 0.1\n",
606
+ " else:\n",
607
+ " reward -= 0.3\n",
608
+ "\n",
609
+ " # Hard penalty for non-terminated JSON-like responses.\n",
610
+ " # This directly pushes generations away from max-token clipping.\n",
611
+ " if not completion_text.endswith(\"}\"):\n",
612
+ " reward -= 0.25\n",
613
+ "\n",
614
+ " # Small bonus for compact single-line JSON output.\n",
615
+ " if is_strict_json and \"\\n\" not in completion_text and len(completion_text) <= 240:\n",
616
+ " reward += 0.08\n",
617
+ "\n",
618
+ " # Strongly discourage invalid action/target combinations.\n",
619
+ " if action.action_type == \"submit_final\" and action.target is not None:\n",
620
+ " reward -= 0.6\n",
621
+ " if action.action_type in {\"message_expert\", \"propose_draft\"} and action.target is None:\n",
622
+ " reward -= 0.6\n",
623
+ "\n",
624
+ " # ── 3. HEURISTIC STATE GRADING (NO API CALLS!) ──\n",
625
+ " \n",
626
+ " if action.action_type == \"message_expert\" and action.target != \"All\":\n",
627
+ " # Did it ask a question it already knows the answer to?\n",
628
+ " if f\"{action.target}: ✓ DISCOVERED\" in prompt:\n",
629
+ " reward -= 0.5\n",
630
+ " else:\n",
631
+ " reward += 0.33 # Good job doing research!\n",
632
+ "\n",
633
+ " elif action.action_type in [\"propose_draft\", \"submit_final\"]:\n",
634
+ " # Did it try to submit before gathering all constraints?\n",
635
+ " if \"? unknown\" in prompt:\n",
636
+ " reward -= 1.0 # Heavy penalty for guessing\n",
637
+ " else:\n",
638
+ " # It did the research. Did it actually include the constraints?\n",
639
+ " text = action.content.lower()\n",
640
+ " has_finance = \"50\" in text\n",
641
+ " has_security = \"biometric\" in text\n",
642
+ " has_ux = \"click\" in text or \"tap\" in text\n",
643
+ " \n",
644
+ " if has_finance and has_security and has_ux:\n",
645
+ " reward += 1.5 \n",
646
+ " else:\n",
647
+ " reward -= 0.5\n",
648
+ "\n",
649
+ " # ── 4. ORACLE-GUIDED DENSE SHAPING ──\n",
650
+ " # This gives non-binary signal and prevents reward plateaus.\n",
651
+ " if oracle_raw:\n",
652
+ " oracle_action = parse_action(oracle_raw)\n",
653
+ " if oracle_action is not None:\n",
654
+ " if action.action_type == oracle_action.action_type:\n",
655
+ " reward += 0.45\n",
656
+ " else:\n",
657
+ " reward -= 0.25\n",
658
+ "\n",
659
+ " if action.target == oracle_action.target:\n",
660
+ " reward += 0.35\n",
661
+ " else:\n",
662
+ " reward -= 0.2\n",
663
+ "\n",
664
+ " overlap = lexical_overlap(action.content, oracle_action.content)\n",
665
+ " reward += 0.4 * overlap\n",
666
+ "\n",
667
+ " # Late turns should avoid endless questioning/proposals.\n",
668
+ " if isinstance(turn, int):\n",
669
+ " if turn >= 8 and action.action_type != \"submit_final\":\n",
670
+ " reward -= 0.35\n",
671
+ " if turn >= 10 and action.action_type != \"submit_final\":\n",
672
+ " reward -= 0.6\n",
673
+ " # Reward timely completion once constraints are all discovered.\n",
674
+ " if (\n",
675
+ " action.action_type == \"submit_final\"\n",
676
+ " and \"? unknown\" not in prompt\n",
677
+ " and turn <= 10\n",
678
+ " ):\n",
679
+ " reward += 0.6\n",
680
+ "\n",
681
+ " # Keep rewards in a stable range for GRPO.\n",
682
+ " reward = max(-2.0, min(2.0, reward))\n",
683
+ "\n",
684
+ " rewards.append(reward)\n",
685
+ "\n",
686
+ " return rewards\n",
687
+ " return reward_fn"
688
+ ]
689
+ },
690
+ {
691
+ "cell_type": "markdown",
692
+ "id": "276d1887",
693
+ "metadata": {},
694
+ "source": [
695
+ "### GRAPH PLOTS"
696
+ ]
697
+ },
698
+ {
699
+ "cell_type": "code",
700
+ "execution_count": null,
701
+ "id": "fa70239a",
702
+ "metadata": {},
703
+ "outputs": [],
704
+ "source": [
705
+ "def save_training_plots(log_history: list[dict], output_dir: Path):\n",
706
+ " if not HAS_PLT:\n",
707
+ " print(\" matplotlib not available — skipping plots\")\n",
708
+ " return\n",
709
+ "\n",
710
+ " output_dir.mkdir(parents=True, exist_ok=True)\n",
711
+ "\n",
712
+ " # Loss curve\n",
713
+ " loss_points = [\n",
714
+ " (e[\"step\"], e[\"loss\"])\n",
715
+ " for e in log_history\n",
716
+ " if \"loss\" in e and \"step\" in e\n",
717
+ " ]\n",
718
+ " if loss_points:\n",
719
+ " xs, ys = zip(*loss_points)\n",
720
+ " fig, ax = plt.subplots(figsize=(9, 4))\n",
721
+ " ax.plot(xs, ys, marker=\"o\", linewidth=1.5, color=\"#4C72B0\", markersize=4)\n",
722
+ " ax.set_xlabel(\"Training Step\", fontsize=12)\n",
723
+ " ax.set_ylabel(\"GRPO Loss\", fontsize=12)\n",
724
+ " ax.set_title(\n",
725
+ " \"Project Polymath — GRPO Training Loss\\n\"\n",
726
+ " \"(State-Based: each step = one negotiation decision)\",\n",
727
+ " fontsize=12\n",
728
+ " )\n",
729
+ " ax.grid(True, alpha=0.3)\n",
730
+ " plt.tight_layout()\n",
731
+ " plt.savefig(output_dir / \"loss_curve.png\", dpi=160)\n",
732
+ " plt.close()\n",
733
+ " print(f\" Saved: {output_dir}/loss_curve.png\")\n",
734
+ "\n",
735
+ " # Reward curve (from log history if available)\n",
736
+ " reward_points = [\n",
737
+ " (e[\"step\"], e.get(\"reward\", e.get(\"mean_reward\", None)))\n",
738
+ " for e in log_history\n",
739
+ " if \"step\" in e and (\"reward\" in e or \"mean_reward\" in e)\n",
740
+ " ]\n",
741
+ " reward_points = [(s, r) for s, r in reward_points if r is not None]\n",
742
+ "\n",
743
+ " if reward_points:\n",
744
+ " xs, ys = zip(*reward_points)\n",
745
+ " fig, ax = plt.subplots(figsize=(9, 4))\n",
746
+ " ax.plot(xs, ys, marker=\"s\", linewidth=1.5, color=\"#55A868\", markersize=4)\n",
747
+ " ax.set_xlabel(\"Training Step\", fontsize=12)\n",
748
+ " ax.set_ylabel(\"Mean Reward\", fontsize=12)\n",
749
+ " ax.set_title(\n",
750
+ " \"Project Polymath — Mean Reward During GRPO Training\\n\"\n",
751
+ " \"(Harmonic mean of Finance/Security/UX constraint satisfaction)\",\n",
752
+ " fontsize=12\n",
753
+ " )\n",
754
+ " ax.grid(True, alpha=0.3)\n",
755
+ " plt.tight_layout()\n",
756
+ " plt.savefig(output_dir / \"reward_curve.png\", dpi=160)\n",
757
+ " plt.close()\n",
758
+ " print(f\" Saved: {output_dir}/reward_curve.png\")"
759
+ ]
760
+ },
761
+ {
762
+ "cell_type": "markdown",
763
+ "id": "57034d95",
764
+ "metadata": {},
765
+ "source": [
766
+ "### Main functin"
767
+ ]
768
+ },
769
+ {
770
+ "cell_type": "code",
771
+ "execution_count": null,
772
+ "id": "01e33d44",
773
+ "metadata": {},
774
+ "outputs": [],
775
+ "source": [
776
+ "def main():\n",
777
+ " parser = argparse.ArgumentParser(description=\"State-Based GRPO — Project Polymath\")\n",
778
+ "\n",
779
+ " # Model\n",
780
+ " parser.add_argument(\"--model\", default=\"unsloth/Qwen2.5-3B-Instruct-bnb-4bit\",\n",
781
+ " help=\"Base model to train\")\n",
782
+ " parser.add_argument(\"--use-unsloth\", action=\"store_true\",\n",
783
+ " help=\"Use Unsloth for 2x faster training (recommended on GPU)\")\n",
784
+ "\n",
785
+ " # Dataset\n",
786
+ " parser.add_argument(\"--states\", type=int, default=40,\n",
787
+ " help=\"Number of negotiation states to train on\")\n",
788
+ " parser.add_argument(\"--states-per-topic\", type=int, default=5,\n",
789
+ " help=\"States to extract per topic (1-5)\")\n",
790
+ " parser.add_argument(\"--topics-limit\", type=int, default=20,\n",
791
+ " help=\"Max topics to use from ai_pm_prompts.json\")\n",
792
+ "\n",
793
+ " # GRPO hyperparams\n",
794
+ " parser.add_argument(\"--group-size\", type=int, default=8,\n",
795
+ " help=\"G: completions per prompt for GRPO advantage (default: 8)\")\n",
796
+ " parser.add_argument(\"--epochs\", type=float, default=3.0)\n",
797
+ " parser.add_argument(\"--lr\", type=float, default=5e-6,\n",
798
+ " help=\"Learning rate (lower = safer, 5e-6 recommended for GRPO)\")\n",
799
+ " parser.add_argument(\"--max-new-tokens\", type=int, default=40,\n",
800
+ " help=\"Max generated tokens per sampled completion (default: 40)\")\n",
801
+ " parser.add_argument(\"--temperature\", type=float, default=0.9,\n",
802
+ " help=\"Sampling temperature for GRPO rollouts\")\n",
803
+ " parser.add_argument(\"--top-p\", type=float, default=0.9,\n",
804
+ " help=\"Nucleus sampling p for GRPO rollouts\")\n",
805
+ " parser.add_argument(\"--batch-size\", type=int, default=1)\n",
806
+ " parser.add_argument(\"--grad-accum\", type=int, default=4)\n",
807
+ " parser.add_argument(\"--max-seq-length\", type=int, default=2048)\n",
808
+ "\n",
809
+ " # Output\n",
810
+ " parser.add_argument(\"--output-dir\", default=str(OUTPUT_DIR))\n",
811
+ " parser.add_argument(\"--dry-run\", action=\"store_true\",\n",
812
+ " help=\"Build dataset and verify reward fn, skip actual training\")\n",
813
+ "\n",
814
+ " args = parser.parse_args()\n",
815
+ "\n",
816
+ " # for dry run only\n",
817
+ " # if not HAS_TRL:\n",
818
+ " # raise RuntimeError(\"pip install trl>=0.8.0 transformers datasets\")\n",
819
+ "\n",
820
+ " output_dir = Path(args.output_dir)\n",
821
+ " output_dir.mkdir(parents=True, exist_ok=True)\n",
822
+ "\n",
823
+ " # Build dataset\n",
824
+ " print(\"\\n[1/4] Loading state dataset...\")\n",
825
+ " topics = load_topics(limit=args.topics_limit)\n",
826
+ " dataset_path = output_dir / \"state_dataset.jsonl\"\n",
827
+ "\n",
828
+ " # CACHING LOGIC for dataset\n",
829
+ " if dataset_path.exists():\n",
830
+ " print(f\" [CACHE HIT] Found existing dataset! Loading instantly from {dataset_path}...\")\n",
831
+ " records = []\n",
832
+ " with dataset_path.open(\"r\") as f:\n",
833
+ " for line in f:\n",
834
+ " if line.strip():\n",
835
+ " records.append(json.loads(line))\n",
836
+ " records = records[:args.states]\n",
837
+ " else:\n",
838
+ " print(\" [CACHE MISS] No dataset found. Generating from scratch (this may take a minute)...\")\n",
839
+ " records = build_state_dataset(topics, states_per_topic=args.states_per_topic)\n",
840
+ " records = records[:args.states]\n",
841
+ " \n",
842
+ " with dataset_path.open(\"w\") as f:\n",
843
+ " for r in records:\n",
844
+ " f.write(json.dumps(r, ensure_ascii=True) + \"\\n\")\n",
845
+ " print(f\" Saved {len(records)} states → {dataset_path}\")\n",
846
+ "\n",
847
+ " dataset = Dataset.from_list([{\n",
848
+ " \"prompt\": r[\"prompt\"],\n",
849
+ " \"topic\": r[\"topic\"],\n",
850
+ " \"turn\": r[\"turn\"],\n",
851
+ " \"oracle_action\": r[\"oracle_action\"],\n",
852
+ " \"step_idx\": r[\"step_idx\"],\n",
853
+ " } for r in records])\n",
854
+ "\n",
855
+ " # Verify reward function\n",
856
+ " print(\"\\n[2/4] Verifying reward function on 6 samples...\")\n",
857
+ " reward_fn = make_reward_fn()\n",
858
+ " # reward_fn = make_reward_fn(topics)\n",
859
+ " prompt_with_finance_discovered = build_state_prompt(\n",
860
+ " topic=topics[0],\n",
861
+ " turn=1,\n",
862
+ " feedback_so_far=\"Finance: Budget cap is $50k.\",\n",
863
+ " discovered=\" Finance: ✓ DISCOVERED\\n Security: ? unknown\\n UX: ? unknown\",\n",
864
+ " )\n",
865
+ "\n",
866
+ " test_completions = [\n",
867
+ " ORACLE_ACTIONS[\"ask_finance\"], # Should score ~0.33\n",
868
+ " ORACLE_ACTIONS[\"ask_security\"], # Should score ~0.33 \n",
869
+ " '{\"action_type\": \"message_expert\", \"target\": \"Finance\", \"content\": \"What is the budget?\"}', # Should score -0.5 (repeat)\n",
870
+ " '{\"action_type\": \"message_expert\", \"target\": \"All\", \"content\": \"What do you all need?\"}', # Should score -1.0\n",
871
+ " \"this is not JSON at all\", # Should score -0.5\n",
872
+ " ORACLE_ACTIONS[\"submit_final\"], # Should score +1.5 (all constraints in content)\n",
873
+ " ]\n",
874
+ "\n",
875
+ " test_rewards = reward_fn(\n",
876
+ " completions=test_completions,\n",
877
+ " prompts=[\n",
878
+ " \"\", # oracle ask_finance — unknown state\n",
879
+ " prompt_with_finance_discovered, # ask_security — good pivot\n",
880
+ " prompt_with_finance_discovered, # ask Finance again — repeat penalty\n",
881
+ " \"\", # broadcast — penalty\n",
882
+ " \"\", # bad JSON\n",
883
+ " build_state_prompt( # submit after all discovered\n",
884
+ " topic=topics[0], turn=4,\n",
885
+ " feedback_so_far=\"All experts responded.\",\n",
886
+ " discovered=\" Finance: ✓ DISCOVERED\\n Security: ✓ DISCOVERED\\n UX: ✓ DISCOVERED\",\n",
887
+ " ),\n",
888
+ " ],\n",
889
+ " )\n",
890
+ "\n",
891
+ " labels = [\n",
892
+ " \"Oracle ask_finance\",\n",
893
+ " \"Oracle ask_security\",\n",
894
+ " \"Repeat question to discovered expert\",\n",
895
+ " \"Broadcast to All\",\n",
896
+ " \"Malformed JSON\",\n",
897
+ " \"Submit final with all constraints\",\n",
898
+ " ]\n",
899
+ " for label, reward in zip(labels, test_rewards):\n",
900
+ " print(f\" • {label}: reward={reward:.3f}\")\n",
901
+ "\n",
902
+ " ask_finance_r, ask_security_r, repeat_r, broadcast_r, malformed_r, submit_r = test_rewards\n",
903
+ " checks = [\n",
904
+ " (\"oracle ask_finance is positive\", ask_finance_r > 0.0),\n",
905
+ " (\"oracle ask_security is positive\", ask_security_r > 0.0),\n",
906
+ " (\"repeat < oracle ask_finance\", repeat_r < ask_finance_r),\n",
907
+ " (\"broadcast <= repeat\", broadcast_r <= repeat_r),\n",
908
+ " (\"malformed JSON is negative\", malformed_r < 0.0),\n",
909
+ " (\"submit_final > oracle ask_finance\", submit_r > ask_finance_r),\n",
910
+ " ]\n",
911
+ " all_ok = True\n",
912
+ " for name, passed in checks:\n",
913
+ " status = \"✓\" if passed else \"✗\"\n",
914
+ " print(f\" {status} invariant: {name}\")\n",
915
+ " all_ok = all_ok and passed\n",
916
+ " if not all_ok:\n",
917
+ " raise RuntimeError(\"Reward verification invariants failed. Check reward shaping logic.\")\n",
918
+ "\n",
919
+ " if args.dry_run:\n",
920
+ " print(\"\\n[DRY RUN] Dataset and reward function verified. Skipping training.\")\n",
921
+ " print(\" Run without --dry-run on GPU to train.\")\n",
922
+ " return\n",
923
+ " \n",
924
+ " # FOR DRY RUN ONLY\n",
925
+ " if not HAS_TRL:\n",
926
+ " raise RuntimeError(\"TRL is required for actual training on the GPU.\")\n",
927
+ " # Load model\n",
928
+ " print(f\"\\n[3/4] Loading model: {args.model}\")\n",
929
+ "\n",
930
+ " if args.use_unsloth:\n",
931
+ " try:\n",
932
+ " from unsloth import FastLanguageModel\n",
933
+ " HAS_UNSLOTH = True\n",
934
+ " except Exception as e:\n",
935
+ " raise RuntimeError(f\"Unsloth failed to load: {e}\\nRun without --use-unsloth instead.\")\n",
936
+ " model, tokenizer = FastLanguageModel.from_pretrained(\n",
937
+ " model_name=args.model,\n",
938
+ " max_seq_length=args.max_seq_length,\n",
939
+ " load_in_4bit=True,\n",
940
+ " dtype=None,\n",
941
+ " )\n",
942
+ " model = FastLanguageModel.get_peft_model(\n",
943
+ " model,\n",
944
+ " r=16,\n",
945
+ " lora_alpha=32,\n",
946
+ " lora_dropout=0.0,\n",
947
+ " target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n",
948
+ " \"gate_proj\", \"up_proj\", \"down_proj\"],\n",
949
+ " use_gradient_checkpointing=\"unsloth\",\n",
950
+ " )\n",
951
+ "\n",
952
+ " if tokenizer.pad_token is None:\n",
953
+ " tokenizer.pad_token = tokenizer.eos_token\n",
954
+ " im_end_id = tokenizer.convert_tokens_to_ids(\"<|im_end|>\")\n",
955
+ " if isinstance(im_end_id, int) and im_end_id >= 0:\n",
956
+ " tokenizer.eos_token = \"<|im_end|>\"\n",
957
+ " model.config.pad_token_id = tokenizer.pad_token_id\n",
958
+ " if tokenizer.eos_token_id is not None:\n",
959
+ " model.config.eos_token_id = tokenizer.eos_token_id\n",
960
+ " model.generation_config.eos_token_id = tokenizer.eos_token_id\n",
961
+ " model.generation_config.pad_token_id = tokenizer.pad_token_id\n",
962
+ " print(\" Unsloth LoRA loaded (4-bit quantization)\")\n",
963
+ " else:\n",
964
+ " if not HAS_TRANSFORMERS:\n",
965
+ " raise RuntimeError(\"pip install transformers\")\n",
966
+ " tokenizer = AutoTokenizer.from_pretrained(args.model)\n",
967
+ " if tokenizer.pad_token is None:\n",
968
+ " tokenizer.pad_token = tokenizer.eos_token\n",
969
+ "\n",
970
+ " # Qwen chat models typically terminate on <|im_end|>.\n",
971
+ " im_end_id = tokenizer.convert_tokens_to_ids(\"<|im_end|>\")\n",
972
+ " if isinstance(im_end_id, int) and im_end_id >= 0:\n",
973
+ " tokenizer.eos_token = \"<|im_end|>\"\n",
974
+ "\n",
975
+ " model = AutoModelForCausalLM.from_pretrained(args.model)\n",
976
+ "\n",
977
+ " # Keepping model/generation config aligned with tokenizer.\n",
978
+ " model.config.pad_token_id = tokenizer.pad_token_id\n",
979
+ " if tokenizer.eos_token_id is not None:\n",
980
+ " model.config.eos_token_id = tokenizer.eos_token_id\n",
981
+ " model.generation_config.eos_token_id = tokenizer.eos_token_id\n",
982
+ " model.generation_config.pad_token_id = tokenizer.pad_token_id\n",
983
+ "\n",
984
+ " print(\" Standard transformers model loaded\")\n",
985
+ "\n",
986
+ " # GRPO Training\n",
987
+ " print(f\"\\n[4/4] Starting GRPO training...\")\n",
988
+ " print(f\" States: {len(records)} | Group size (G): {args.group_size}\")\n",
989
+ " print(f\" Epochs: {args.epochs} | LR: {args.lr}\")\n",
990
+ " print(f\" Total updates: ~{int(len(records) * args.epochs / args.batch_size)}\")\n",
991
+ "\n",
992
+ " # Build explicit stop-token list for GRPO sampling.\n",
993
+ " eos_ids = []\n",
994
+ " if tokenizer.eos_token_id is not None:\n",
995
+ " eos_ids.append(int(tokenizer.eos_token_id))\n",
996
+ " im_end_id = tokenizer.convert_tokens_to_ids(\"<|im_end|>\")\n",
997
+ " if isinstance(im_end_id, int) and im_end_id >= 0:\n",
998
+ " eos_ids.append(int(im_end_id))\n",
999
+ " close_brace_id = tokenizer.convert_tokens_to_ids(\"}\")\n",
1000
+ " if isinstance(close_brace_id, int) and close_brace_id >= 0:\n",
1001
+ " eos_ids.append(int(close_brace_id))\n",
1002
+ " # Preserve order, remove duplicates.\n",
1003
+ " eos_ids = list(dict.fromkeys(eos_ids))\n",
1004
+ "\n",
1005
+ " generation_kwargs = {\n",
1006
+ " \"eos_token_id\": eos_ids if len(eos_ids) > 1 else (eos_ids[0] if eos_ids else None),\n",
1007
+ " \"pad_token_id\": tokenizer.pad_token_id,\n",
1008
+ " }\n",
1009
+ " # Remove None values.\n",
1010
+ " generation_kwargs = {k: v for k, v in generation_kwargs.items() if v is not None}\n",
1011
+ "\n",
1012
+ " config = GRPOConfig(\n",
1013
+ " output_dir=str(output_dir),\n",
1014
+ "\n",
1015
+ " # GRPO-specific\n",
1016
+ " num_generations=args.group_size, # G: sample this many completions per prompt\n",
1017
+ " max_completion_length=args.max_new_tokens,\n",
1018
+ " temperature=args.temperature,\n",
1019
+ " top_p=args.top_p,\n",
1020
+ " top_k=40,\n",
1021
+ " repetition_penalty=1.05,\n",
1022
+ " generation_kwargs=generation_kwargs,\n",
1023
+ " mask_truncated_completions=True,\n",
1024
+ "\n",
1025
+ " # Standard training\n",
1026
+ " learning_rate=args.lr,\n",
1027
+ " num_train_epochs=args.epochs,\n",
1028
+ " per_device_train_batch_size=max(1, args.batch_size),\n",
1029
+ " gradient_accumulation_steps=args.grad_accum,\n",
1030
+ "\n",
1031
+ " # Logging\n",
1032
+ " logging_steps=1,\n",
1033
+ " save_strategy=\"epoch\",\n",
1034
+ " report_to=[],\n",
1035
+ " )\n",
1036
+ "\n",
1037
+ " trainer = GRPOTrainer(\n",
1038
+ " model=model,\n",
1039
+ " processing_class=tokenizer,\n",
1040
+ " args=config,\n",
1041
+ " reward_funcs=reward_fn, \n",
1042
+ " train_dataset=dataset,\n",
1043
+ " )\n",
1044
+ "\n",
1045
+ " trainer.train()\n",
1046
+ "\n",
1047
+ " # Saving everything\n",
1048
+ " trainer.save_model(str(output_dir / \"final_model\"))\n",
1049
+ " tokenizer.save_pretrained(str(output_dir / \"final_model\"))\n",
1050
+ " print(f\"\\n Model saved → {output_dir}/final_model\")\n",
1051
+ "\n",
1052
+ " # Saving metrics\n",
1053
+ " metrics_path = output_dir / \"grpo_metrics.json\"\n",
1054
+ " with metrics_path.open(\"w\") as f:\n",
1055
+ " json.dump(trainer.state.log_history, f, indent=2)\n",
1056
+ " print(f\" Metrics saved → {metrics_path}\")\n",
1057
+ "\n",
1058
+ " # Saving plots\n",
1059
+ " save_training_plots(trainer.state.log_history, output_dir)\n",
1060
+ "\n",
1061
+ " # Summary\n",
1062
+ " log = trainer.state.log_history\n",
1063
+ " losses = [e[\"loss\"] for e in log if \"loss\" in e]\n",
1064
+ " if losses:\n",
1065
+ " print(f\"\\n Initial loss: {losses[0]:.4f}\")\n",
1066
+ " print(f\" Final loss: {losses[-1]:.4f}\")\n",
1067
+ " print(f\" Improvement: {((losses[0] - losses[-1]) / losses[0] * 100):.1f}%\")\n",
1068
+ "\n",
1069
+ " print(f\"\\n{'='*60}\")\n",
1070
+ " print(f\" GRPO TRAINING COMPLETE\")\n",
1071
+ " print(f\" Model: {output_dir}/final_model\")\n",
1072
+ " print(f\" Plots: {output_dir}/loss_curve.png\")\n",
1073
+ " print(f\" {output_dir}/reward_curve.png\")\n",
1074
+ " print(f\" Metrics: {output_dir}/grpo_metrics.json\")\n",
1075
+ " print(f\"{'='*60}\")\n",
1076
+ "\n",
1077
+ "\n",
1078
+ "if __name__ == \"__main__\":\n",
1079
+ " main()"
1080
+ ]
1081
+ }
1082
+ ],
1083
+ "metadata": {
1084
+ "language_info": {
1085
+ "name": "python"
1086
+ }
1087
+ },
1088
+ "nbformat": 4,
1089
+ "nbformat_minor": 5
1090
+ }