neuralninja110 commited on
Commit
309d86c
Β·
verified Β·
1 Parent(s): 10e4b13

Upload BioForge_GRPO.ipynb with huggingface_hub

Browse files
Files changed (1) hide show
  1. BioForge_GRPO.ipynb +667 -0
BioForge_GRPO.ipynb ADDED
@@ -0,0 +1,667 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "5f823ef8",
6
+ "metadata": {},
7
+ "source": [
8
+ "# 🧬 BioForge β€” GRPO Training on HuggingFace Spaces\n",
9
+ "\n",
10
+ "Fine-tunes **Qwen2.5-3B-Instruct** with Group Relative Policy Optimisation (GRPO) \n",
11
+ "against the BioForge drug-discovery + genomics RL environment.\n",
12
+ "\n",
13
+ "## How to run on HuggingFace Spaces\n",
14
+ "1. Create a new **Jupyter Notebook Space** at https://huggingface.co/new-space\n",
15
+ " - SDK: **Jupyter**\n",
16
+ " - Hardware: **T4 Small** (~$0.60/hr with credits) or **A10G** for faster training\n",
17
+ "2. In Space **Settings β†’ Secrets**, add:\n",
18
+ " - `HF_TOKEN` β†’ your HuggingFace write token\n",
19
+ " - `HF_USERNAME` β†’ your HuggingFace username (e.g. `johnsmith`)\n",
20
+ "3. Upload this notebook to the Space\n",
21
+ "4. Open it and **Run All Cells**\n",
22
+ "\n",
23
+ "Training will:\n",
24
+ "- Run **500 GRPO steps on T4** (~1-2 hrs) or **1000 steps on A10G** (~40 min)\n",
25
+ "- Push the trained LoRA adapter to `{HF_USERNAME}/bioforge-grpo-qwen2.5-3b`\n",
26
+ "- Print a before / after reward comparison on all 5 BioForge tasks\n",
27
+ "\n",
28
+ "**Expected reward improvement:** 0.3 β†’ 0.7+ mean reward vs. zero-shot baseline"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "execution_count": null,
34
+ "id": "5419b66f",
35
+ "metadata": {},
36
+ "outputs": [],
37
+ "source": [
38
+ "# ── 1. Install dependencies ───────────────────────────────────────────────\n",
39
+ "import subprocess, sys\n",
40
+ "\n",
41
+ "def pip(*args):\n",
42
+ " subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', *args])\n",
43
+ "\n",
44
+ "# Unsloth β€” fast 4-bit LoRA + GRPO\n",
45
+ "pip('unsloth[huggingface]>=2024.12')\n",
46
+ "# TRL with GRPO support\n",
47
+ "pip('trl>=0.14.0', 'peft>=0.12.0', 'accelerate>=0.34.0')\n",
48
+ "# HuggingFace ecosystem\n",
49
+ "pip('datasets>=2.20.0', 'huggingface_hub>=0.24.0', 'transformers>=4.44.0')\n",
50
+ "# BioForge environment dependencies\n",
51
+ "pip('fastapi>=0.111', 'uvicorn[standard]>=0.29', 'httpx>=0.27', 'pydantic>=2.7')\n",
52
+ "pip('biopython>=1.84', 'scikit-learn>=1.5', 'scipy>=1.13', 'requests>=2.32')\n",
53
+ "\n",
54
+ "print('βœ… Dependencies installed')"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "execution_count": null,
60
+ "id": "697271e2",
61
+ "metadata": {},
62
+ "outputs": [],
63
+ "source": [
64
+ "# ── 2. Configuration β€” credentials + GPU auto-detection ──────────────────\n",
65
+ "import os, torch\n",
66
+ "\n",
67
+ "# Credentials β€” set as Space Secrets, or paste here for local runs\n",
68
+ "HF_TOKEN = os.environ.get('HF_TOKEN', '') # HuggingFace write token\n",
69
+ "HF_USERNAME = os.environ.get('HF_USERNAME', '') # your HuggingFace username\n",
70
+ "\n",
71
+ "assert HF_TOKEN, '⚠️ Set HF_TOKEN in Space Settings β†’ Secrets'\n",
72
+ "assert HF_USERNAME, '⚠️ Set HF_USERNAME in Space Settings β†’ Secrets (e.g. \"johnsmith\")'\n",
73
+ "\n",
74
+ "# Authenticate with HF Hub\n",
75
+ "from huggingface_hub import login\n",
76
+ "login(token=HF_TOKEN, add_to_git_credential=False)\n",
77
+ "\n",
78
+ "# ── GPU detection ─────────────────────────────────────────────────────────\n",
79
+ "if torch.cuda.is_available():\n",
80
+ " gpu = torch.cuda.get_device_name(0)\n",
81
+ " vram_gb = torch.cuda.get_device_properties(0).total_memory / 1e9\n",
82
+ " print(f'βœ… GPU: {gpu} ({vram_gb:.1f} GB VRAM)')\n",
83
+ "else:\n",
84
+ " gpu, vram_gb = 'CPU', 0\n",
85
+ " print('⚠️ No GPU detected β€” training will be very slow')\n",
86
+ "\n",
87
+ "IS_T4 = 'T4' in gpu\n",
88
+ "IS_A10G = 'A10G' in gpu or 'A100' in gpu\n",
89
+ "IS_FAST = IS_A10G\n",
90
+ "\n",
91
+ "# ── Training hyperparams (auto-scaled by GPU) ─────────────────────────────\n",
92
+ "MODEL_NAME = 'unsloth/Qwen2.5-3B-Instruct' # fits T4 16GB with 4-bit, no gating\n",
93
+ "HUB_REPO = f'{HF_USERNAME}/bioforge-grpo-qwen2.5-3b'\n",
94
+ "MAX_SEQ_LEN = 2048 if IS_FAST else 1536\n",
95
+ "MAX_COMP_LEN = 512\n",
96
+ "NUM_GENERATIONS = 8 if IS_FAST else 4 # GRPO group size per prompt\n",
97
+ "BATCH_SIZE = 2 if IS_FAST else 1\n",
98
+ "GRAD_ACC = 4\n",
99
+ "MAX_STEPS = 1000 if IS_FAST else 500 # smoke-test: set to 50\n",
100
+ "LEARNING_RATE = 5e-6\n",
101
+ "N_PROMPTS = 600 if IS_FAST else 300 # rollout dataset size\n",
102
+ "\n",
103
+ "print(f'\\nConfig:')\n",
104
+ "print(f' model = {MODEL_NAME}')\n",
105
+ "print(f' max_steps = {MAX_STEPS}')\n",
106
+ "print(f' num_generations= {NUM_GENERATIONS}')\n",
107
+ "print(f' batch = {BATCH_SIZE} Γ— grad_acc {GRAD_ACC}')\n",
108
+ "print(f' hub output = https://huggingface.co/{HUB_REPO}')"
109
+ ]
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "execution_count": null,
114
+ "id": "bc441bb8",
115
+ "metadata": {},
116
+ "outputs": [],
117
+ "source": [
118
+ "# ── 3. Clone BioForge repo ────────────────────────────────────────────────\n",
119
+ "import subprocess, os, sys\n",
120
+ "\n",
121
+ "BIOFORGE_DIR = '/home/user/bioforge'\n",
122
+ "\n",
123
+ "if not os.path.isdir(BIOFORGE_DIR):\n",
124
+ " SPACE_URL = f'https://huggingface.co/spaces/{HF_USERNAME}/bioforge'\n",
125
+ " r = subprocess.run(['git', 'clone', SPACE_URL, BIOFORGE_DIR],\n",
126
+ " capture_output=True, text=True)\n",
127
+ " if r.returncode != 0:\n",
128
+ " # Fallback: look for the repo in common HF Spaces locations\n",
129
+ " for candidate in ['/app', '/home/user/app', os.getcwd()]:\n",
130
+ " if os.path.isdir(os.path.join(candidate, 'bioforge')):\n",
131
+ " BIOFORGE_DIR = candidate\n",
132
+ " break\n",
133
+ " print(f'⚠️ git clone failed. Using: {BIOFORGE_DIR}\\n {r.stderr.strip()[:120]}')\n",
134
+ " else:\n",
135
+ " print(f'βœ… Cloned to {BIOFORGE_DIR}')\n",
136
+ "else:\n",
137
+ " print(f'βœ… Repo already at {BIOFORGE_DIR}')\n",
138
+ "\n",
139
+ "# Resolve REPO_ROOT as the dir that contains the `bioforge/` package folder\n",
140
+ "REPO_ROOT = BIOFORGE_DIR if os.path.isdir(os.path.join(BIOFORGE_DIR, 'bioforge')) \\\n",
141
+ " else os.path.dirname(BIOFORGE_DIR)\n",
142
+ "\n",
143
+ "if REPO_ROOT not in sys.path:\n",
144
+ " sys.path.insert(0, REPO_ROOT)\n",
145
+ "\n",
146
+ "# Verify import\n",
147
+ "try:\n",
148
+ " import bioforge\n",
149
+ " print(f'βœ… bioforge package importable from {REPO_ROOT}')\n",
150
+ "except ImportError as e:\n",
151
+ " print(f'❌ Cannot import bioforge: {e}')\n",
152
+ " raise"
153
+ ]
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": null,
158
+ "id": "d50f839f",
159
+ "metadata": {},
160
+ "outputs": [],
161
+ "source": [
162
+ "# ── 4. BioForge environment β€” local server or deployed Space ──────────────\n",
163
+ "# If you have deployed the BioForge environment to HF Spaces (Step 2 of\n",
164
+ "# deploy_training_space.ps1), set ENV_URL to the Space URL instead.\n",
165
+ "# Otherwise we start a local server on port 7860.\n",
166
+ "\n",
167
+ "import subprocess, time, os, sys\n",
168
+ "import httpx\n",
169
+ "\n",
170
+ "# Override via env var or set directly:\n",
171
+ "# export BIOFORGE_ENV_URL=\"https://neuralninja110-bioforge.hf.space\"\n",
172
+ "ENV_URL = os.environ.get('BIOFORGE_ENV_URL', 'http://127.0.0.1:7860')\n",
173
+ "USE_LOCAL = ENV_URL.startswith('http://127') or ENV_URL.startswith('http://localhost')\n",
174
+ "\n",
175
+ "server_proc = None\n",
176
+ "\n",
177
+ "if USE_LOCAL:\n",
178
+ " ENV_PORT = int(ENV_URL.rsplit(':', 1)[-1])\n",
179
+ " env = os.environ.copy()\n",
180
+ " env['PYTHONPATH'] = REPO_ROOT + os.pathsep + env.get('PYTHONPATH', '')\n",
181
+ "\n",
182
+ " server_proc = subprocess.Popen(\n",
183
+ " [sys.executable, '-m', 'uvicorn',\n",
184
+ " 'bioforge.server.app:app',\n",
185
+ " '--host', '127.0.0.1', '--port', str(ENV_PORT),\n",
186
+ " '--log-level', 'warning'],\n",
187
+ " cwd=REPO_ROOT,\n",
188
+ " env=env,\n",
189
+ " stdout=subprocess.PIPE,\n",
190
+ " stderr=subprocess.PIPE,\n",
191
+ " )\n",
192
+ " print('Starting local BioForge server...', end='')\n",
193
+ " for _ in range(25):\n",
194
+ " time.sleep(1.5)\n",
195
+ " try:\n",
196
+ " r = httpx.post(f'{ENV_URL}/reset',\n",
197
+ " json={'task_id': 'variant_triage', 'difficulty': 'easy', 'payload': {}},\n",
198
+ " timeout=5)\n",
199
+ " if r.status_code == 200:\n",
200
+ " print(f' OK (HTTP {r.status_code})')\n",
201
+ " break\n",
202
+ " except Exception:\n",
203
+ " print('.', end='', flush=True)\n",
204
+ " else:\n",
205
+ " stderr = server_proc.stderr.read(2000).decode(errors='replace')\n",
206
+ " print(f'\\nServer stderr:\\n{stderr}')\n",
207
+ " raise RuntimeError('BioForge server failed to start')\n",
208
+ "else:\n",
209
+ " # Verify the remote Space is reachable\n",
210
+ " print(f'Using deployed BioForge Space: {ENV_URL}')\n",
211
+ " r = httpx.post(f'{ENV_URL}/reset',\n",
212
+ " json={'task_id': 'variant_triage', 'difficulty': 'easy', 'payload': {}},\n",
213
+ " timeout=30)\n",
214
+ " print(f' Health check: HTTP {r.status_code}')\n",
215
+ " if r.status_code != 200:\n",
216
+ " raise RuntimeError(f'Remote BioForge Space not ready: {r.text[:200]}')\n",
217
+ "\n",
218
+ "print(f'ENV_URL = {ENV_URL}')"
219
+ ]
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "execution_count": null,
224
+ "id": "33250bf0",
225
+ "metadata": {},
226
+ "outputs": [],
227
+ "source": [
228
+ "# ── 5. Load Qwen2.5-3B-Instruct (4-bit, Unsloth) ─────────────────────────\n",
229
+ "from unsloth import FastLanguageModel, PatchFastRL\n",
230
+ "PatchFastRL('GRPO', FastLanguageModel)\n",
231
+ "\n",
232
+ "model, tokenizer = FastLanguageModel.from_pretrained(\n",
233
+ " model_name=MODEL_NAME,\n",
234
+ " max_seq_length=MAX_SEQ_LEN,\n",
235
+ " load_in_4bit=True,\n",
236
+ " fast_inference=True, # Unsloth fast generation\n",
237
+ " gpu_memory_utilization=0.6, # leave headroom for GRPO rollouts\n",
238
+ " token=HF_TOKEN,\n",
239
+ ")\n",
240
+ "\n",
241
+ "model = FastLanguageModel.get_peft_model(\n",
242
+ " model,\n",
243
+ " r=16,\n",
244
+ " target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj',\n",
245
+ " 'gate_proj', 'up_proj', 'down_proj'],\n",
246
+ " lora_alpha=16,\n",
247
+ " lora_dropout=0,\n",
248
+ " bias='none',\n",
249
+ " use_gradient_checkpointing='unsloth',\n",
250
+ " random_state=42,\n",
251
+ ")\n",
252
+ "\n",
253
+ "print(f'βœ… Model loaded: {MODEL_NAME}')\n",
254
+ "print(f' Trainable params: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}')\n",
255
+ "if torch.cuda.is_available():\n",
256
+ " used = torch.cuda.memory_allocated() / 1e9\n",
257
+ " total = torch.cuda.get_device_properties(0).total_memory / 1e9\n",
258
+ " print(f' VRAM used: {used:.1f} GB / {total:.1f} GB')"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "execution_count": null,
264
+ "id": "85263d25",
265
+ "metadata": {},
266
+ "outputs": [],
267
+ "source": [
268
+ "# ── 6. Build GRPO rollout prompt dataset ─────────────────────────────────\n",
269
+ "import random, json, sys, os\n",
270
+ "import httpx\n",
271
+ "from datasets import Dataset\n",
272
+ "\n",
273
+ "# Import prompt helpers from inference module (graceful fallback)\n",
274
+ "try:\n",
275
+ " from bioforge.inference import SYSTEM_PROMPTS, build_user_prompt\n",
276
+ " _HAS_HELPERS = True\n",
277
+ "except ImportError:\n",
278
+ " _HAS_HELPERS = False\n",
279
+ "\n",
280
+ "TASK_LIST = [\n",
281
+ " ('variant_triage', 'easy'),\n",
282
+ " ('pharmacogenomics', 'easy'),\n",
283
+ " ('drug_synergy', 'medium'),\n",
284
+ " ('genetic_counseling', 'medium'),\n",
285
+ " ('neoantigen_vaccine', 'hard'),\n",
286
+ "]\n",
287
+ "\n",
288
+ "_SYS_FALLBACK = (\n",
289
+ " 'You are BioForge, an expert biomedical AI agent. '\n",
290
+ " 'Analyse the provided data and respond ONLY with a single valid JSON object '\n",
291
+ " 'wrapped in ```json ... ``` fences. No prose outside the fences.'\n",
292
+ ")\n",
293
+ "\n",
294
+ "def get_system_prompt(task_id):\n",
295
+ " return SYSTEM_PROMPTS.get(task_id, _SYS_FALLBACK) if _HAS_HELPERS else _SYS_FALLBACK\n",
296
+ "\n",
297
+ "def get_user_prompt(task_id, obs):\n",
298
+ " if _HAS_HELPERS:\n",
299
+ " try:\n",
300
+ " return build_user_prompt(task_id, obs)\n",
301
+ " except Exception:\n",
302
+ " pass\n",
303
+ " return f'Task: {task_id}\\n\\nObservation:\\n{json.dumps(obs, indent=2)[:1200]}\\n\\nRespond with a valid JSON action.'\n",
304
+ "\n",
305
+ "rng = random.Random(42)\n",
306
+ "records, errors = [], 0\n",
307
+ "\n",
308
+ "print(f'Building {N_PROMPTS} prompts for GRPO rollout dataset...', end='')\n",
309
+ "for i in range(N_PROMPTS):\n",
310
+ " task_id, difficulty = rng.choice(TASK_LIST)\n",
311
+ " try:\n",
312
+ " resp = httpx.post(f'{ENV_URL}/reset',\n",
313
+ " json={'task_id': task_id, 'difficulty': difficulty, 'payload': {}},\n",
314
+ " timeout=15)\n",
315
+ " obs = resp.json().get('observation', {})\n",
316
+ " except Exception:\n",
317
+ " obs, errors = {}, errors + 1\n",
318
+ "\n",
319
+ " prompt = tokenizer.apply_chat_template(\n",
320
+ " [\n",
321
+ " {'role': 'system', 'content': get_system_prompt(task_id)},\n",
322
+ " {'role': 'user', 'content': get_user_prompt(task_id, obs)},\n",
323
+ " ],\n",
324
+ " tokenize=False,\n",
325
+ " add_generation_prompt=True,\n",
326
+ " )\n",
327
+ " records.append({'prompt': prompt, 'task_id': task_id, 'difficulty': difficulty})\n",
328
+ " if (i + 1) % 50 == 0:\n",
329
+ " print(f' {i+1}', end='', flush=True)\n",
330
+ "\n",
331
+ "print(f'\\nβœ… Dataset: {len(records)} prompts ({errors} reset errors)')\n",
332
+ "grpo_dataset = Dataset.from_list(records)"
333
+ ]
334
+ },
335
+ {
336
+ "cell_type": "code",
337
+ "execution_count": null,
338
+ "id": "46645d83",
339
+ "metadata": {},
340
+ "outputs": [],
341
+ "source": [
342
+ "# ── 7. Reward function ────────────────────────────────────────────────────\n",
343
+ "import json, re\n",
344
+ "import httpx\n",
345
+ "from typing import List\n",
346
+ "\n",
347
+ "_http = httpx.Client(timeout=20.0)\n",
348
+ "\n",
349
+ "\n",
350
+ "def extract_json(text: str):\n",
351
+ " \"\"\"Parse JSON from model output β€” handles ```json fences or bare objects.\"\"\"\n",
352
+ " fence = re.search(r'```(?:json)?\\s*(\\{.*?\\})\\s*```', text, re.DOTALL)\n",
353
+ " if fence:\n",
354
+ " candidate = fence.group(1)\n",
355
+ " else:\n",
356
+ " brace = re.search(r'\\{.*\\}', text, re.DOTALL)\n",
357
+ " if not brace:\n",
358
+ " return None\n",
359
+ " candidate = brace.group(0)\n",
360
+ " try:\n",
361
+ " return json.loads(candidate)\n",
362
+ " except json.JSONDecodeError:\n",
363
+ " return None\n",
364
+ "\n",
365
+ "\n",
366
+ "def bioforge_reward(completions: List[str], prompts: List[str], **kw) -> List[float]:\n",
367
+ " \"\"\"\n",
368
+ " GRPO reward function. Called after each generation batch.\n",
369
+ " Returns a reward in [-0.1, 1.0] per completion.\n",
370
+ " \"\"\"\n",
371
+ " task_ids = kw.get('task_id', ['variant_triage'] * len(completions))\n",
372
+ " diffs = kw.get('difficulty', ['easy'] * len(completions))\n",
373
+ " rewards = []\n",
374
+ "\n",
375
+ " for comp, tid, diff in zip(completions, task_ids, diffs):\n",
376
+ " parsed = extract_json(comp)\n",
377
+ " if parsed is None:\n",
378
+ " rewards.append(-0.1) # penalty for not producing valid JSON\n",
379
+ " continue\n",
380
+ " try:\n",
381
+ " r = _http.post(\n",
382
+ " f'{ENV_URL}/step',\n",
383
+ " json={'task_id': tid, 'difficulty': diff, 'payload': parsed},\n",
384
+ " )\n",
385
+ " d = r.json()\n",
386
+ " obs = d.get('observation', d)\n",
387
+ " rewards.append(float(obs.get('reward', 0.0)))\n",
388
+ " except Exception:\n",
389
+ " rewards.append(0.0)\n",
390
+ "\n",
391
+ " return rewards\n",
392
+ "\n",
393
+ "\n",
394
+ "# Smoke-test reward function\n",
395
+ "_test = ['```json\\n{\"variant_id\":\"c.123A>T\",\"proposed_classification\":\"Pathogenic\",'\n",
396
+ " '\"acmg_criteria_invoked\":[\"PS1\"],\"evidence_citations\":[],'\n",
397
+ " '\"reasoning_chain\":\"test\"}\\n```']\n",
398
+ "_r = bioforge_reward(_test, [''], task_id=['variant_triage'], difficulty=['easy'])\n",
399
+ "print(f'βœ… Reward function OK (smoke-test reward = {_r[0]:.3f})')"
400
+ ]
401
+ },
402
+ {
403
+ "cell_type": "code",
404
+ "execution_count": null,
405
+ "id": "6d89aed0",
406
+ "metadata": {},
407
+ "outputs": [],
408
+ "source": [
409
+ "# ── 8. GRPO Training ──────────────────────────────────────────────────────\n",
410
+ "import os, torch\n",
411
+ "from trl import GRPOConfig, GRPOTrainer\n",
412
+ "\n",
413
+ "OUT_DIR = '/home/user/outputs/bioforge-grpo'\n",
414
+ "os.makedirs(OUT_DIR, exist_ok=True)\n",
415
+ "\n",
416
+ "grpo_cfg = GRPOConfig(\n",
417
+ " output_dir=OUT_DIR,\n",
418
+ "\n",
419
+ " # Training schedule\n",
420
+ " max_steps=MAX_STEPS,\n",
421
+ " per_device_train_batch_size=BATCH_SIZE,\n",
422
+ " gradient_accumulation_steps=GRAD_ACC,\n",
423
+ " learning_rate=LEARNING_RATE,\n",
424
+ " lr_scheduler_type='cosine',\n",
425
+ " warmup_ratio=0.05,\n",
426
+ "\n",
427
+ " # GRPO-specific\n",
428
+ " num_generations=NUM_GENERATIONS, # rollouts per prompt\n",
429
+ " max_completion_length=MAX_COMP_LEN,\n",
430
+ " temperature=0.9,\n",
431
+ " top_p=0.95,\n",
432
+ " beta=0.001, # KL penalty weight\n",
433
+ "\n",
434
+ " # Logging & saving\n",
435
+ " logging_steps=5,\n",
436
+ " save_steps=100,\n",
437
+ " save_total_limit=2,\n",
438
+ " report_to='wandb' if os.environ.get('WANDB_API_KEY') else 'none',\n",
439
+ " run_name='bioforge-grpo-qwen2.5-3b',\n",
440
+ "\n",
441
+ " # Mixed precision\n",
442
+ " bf16=torch.cuda.is_bf16_supported(),\n",
443
+ " fp16=not torch.cuda.is_bf16_supported(),\n",
444
+ "\n",
445
+ " # Misc\n",
446
+ " seed=42,\n",
447
+ " dataloader_num_workers=0, # avoids multiprocessing issues in Spaces\n",
448
+ ")\n",
449
+ "\n",
450
+ "grpo_trainer = GRPOTrainer(\n",
451
+ " model=model,\n",
452
+ " processing_class=tokenizer,\n",
453
+ " config=grpo_cfg,\n",
454
+ " train_dataset=grpo_dataset,\n",
455
+ " reward_funcs=bioforge_reward,\n",
456
+ ")\n",
457
+ "\n",
458
+ "print(f'πŸš€ Starting GRPO training β€” {MAX_STEPS} steps, {NUM_GENERATIONS}Γ— rollouts/prompt')\n",
459
+ "print(f' Effective batch = {BATCH_SIZE}Γ—{GRAD_ACC}Γ—{NUM_GENERATIONS} = {BATCH_SIZE*GRAD_ACC*NUM_GENERATIONS} rollouts/update')\n",
460
+ "\n",
461
+ "train_result = grpo_trainer.train()\n",
462
+ "\n",
463
+ "print('\\nβœ… GRPO training complete')\n",
464
+ "print(f' Steps completed : {train_result.global_step}')\n",
465
+ "print(f' Final loss : {train_result.training_loss:.4f}')"
466
+ ]
467
+ },
468
+ {
469
+ "cell_type": "code",
470
+ "execution_count": null,
471
+ "id": "873c7168",
472
+ "metadata": {},
473
+ "outputs": [],
474
+ "source": [
475
+ "# ── 9. Save merged model + push LoRA adapter to HuggingFace Hub ──────────\n",
476
+ "import os\n",
477
+ "from huggingface_hub import HfApi\n",
478
+ "\n",
479
+ "MERGED_DIR = '/home/user/outputs/bioforge-grpo-merged'\n",
480
+ "os.makedirs(MERGED_DIR, exist_ok=True)\n",
481
+ "\n",
482
+ "print('Merging LoRA weights into base model (16-bit)...')\n",
483
+ "model.save_pretrained_merged(MERGED_DIR, tokenizer, save_method='merged_16bit')\n",
484
+ "print(f'βœ… Merged model saved to {MERGED_DIR}')\n",
485
+ "\n",
486
+ "# Push LoRA adapter (much faster than full 16-bit push)\n",
487
+ "print(f'\\nPushing LoRA adapter to hub: {HUB_REPO}...')\n",
488
+ "model.push_to_hub_merged(\n",
489
+ " HUB_REPO,\n",
490
+ " tokenizer,\n",
491
+ " save_method='lora',\n",
492
+ " token=HF_TOKEN,\n",
493
+ " commit_message='BioForge GRPO fine-tuned Qwen2.5-3B-Instruct',\n",
494
+ ")\n",
495
+ "print(f'βœ… LoRA adapter pushed to https://huggingface.co/{HUB_REPO}')\n",
496
+ "\n",
497
+ "# Write model card\n",
498
+ "api = HfApi(token=HF_TOKEN)\n",
499
+ "card = f'''---\n",
500
+ "base_model: Qwen/Qwen2.5-3B-Instruct\n",
501
+ "tags:\n",
502
+ " - rl\n",
503
+ " - grpo\n",
504
+ " - biomedical\n",
505
+ " - drug-discovery\n",
506
+ " - genomics\n",
507
+ " - openenv\n",
508
+ "license: apache-2.0\n",
509
+ "---\n",
510
+ "\n",
511
+ "# BioForge GRPO β€” Qwen2.5-3B-Instruct\n",
512
+ "\n",
513
+ "Fine-tuned with **GRPO** against the [BioForge](https://huggingface.co/spaces/{HF_USERNAME}/bioforge)\n",
514
+ "drug-discovery & genomics RL environment.\n",
515
+ "\n",
516
+ "Tasks: `variant_triage` | `pharmacogenomics` | `drug_synergy` | `genetic_counseling` | `neoantigen_vaccine`\n",
517
+ "\n",
518
+ "Training: {MAX_STEPS} GRPO steps, {NUM_GENERATIONS}x rollouts per prompt.\n",
519
+ "Base model: `Qwen/Qwen2.5-3B-Instruct` fine-tuned with Unsloth 4-bit LoRA.\n",
520
+ "'''\n",
521
+ "api.upload_file(\n",
522
+ " path_or_fileobj=card.encode(),\n",
523
+ " path_in_repo='README.md',\n",
524
+ " repo_id=HUB_REPO,\n",
525
+ " repo_type='model',\n",
526
+ " token=HF_TOKEN,\n",
527
+ ")\n",
528
+ "print('βœ… Model card uploaded')"
529
+ ]
530
+ },
531
+ {
532
+ "cell_type": "code",
533
+ "execution_count": null,
534
+ "id": "0c941c0a",
535
+ "metadata": {},
536
+ "outputs": [],
537
+ "source": [
538
+ "# ── 10. Before / After reward evaluation ─────────────────────────────────\n",
539
+ "import json, re, torch\n",
540
+ "import httpx\n",
541
+ "from unsloth import FastLanguageModel\n",
542
+ "\n",
543
+ "EVAL_TASKS = [\n",
544
+ " ('variant_triage', 'easy'),\n",
545
+ " ('pharmacogenomics', 'easy'),\n",
546
+ " ('drug_synergy', 'medium'),\n",
547
+ " ('genetic_counseling', 'medium'),\n",
548
+ " ('neoantigen_vaccine', 'hard'),\n",
549
+ "]\n",
550
+ "\n",
551
+ "def eval_single_task(task_id, difficulty, _model, _tok):\n",
552
+ " FastLanguageModel.for_inference(_model)\n",
553
+ "\n",
554
+ " resp = httpx.post(f'{ENV_URL}/reset',\n",
555
+ " json={'task_id': task_id, 'difficulty': difficulty, 'payload': {}},\n",
556
+ " timeout=15)\n",
557
+ " obs = resp.json().get('observation', {})\n",
558
+ "\n",
559
+ " prompt = _tok.apply_chat_template(\n",
560
+ " [\n",
561
+ " {'role': 'system', 'content': get_system_prompt(task_id)},\n",
562
+ " {'role': 'user', 'content': get_user_prompt(task_id, obs)},\n",
563
+ " ],\n",
564
+ " tokenize=False, add_generation_prompt=True,\n",
565
+ " )\n",
566
+ "\n",
567
+ " inputs = _tok(prompt, return_tensors='pt').to(_model.device)\n",
568
+ " with torch.no_grad():\n",
569
+ " out = _model.generate(**inputs, max_new_tokens=400, temperature=0.3, do_sample=True)\n",
570
+ " completion = _tok.decode(out[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)\n",
571
+ "\n",
572
+ " parsed = extract_json(completion)\n",
573
+ " if parsed is None:\n",
574
+ " return 0.0, completion[:200], 'No JSON produced'\n",
575
+ "\n",
576
+ " step = httpx.post(f'{ENV_URL}/step',\n",
577
+ " json={'task_id': task_id, 'difficulty': difficulty, 'payload': parsed},\n",
578
+ " timeout=15)\n",
579
+ " step_obs = step.json().get('observation', {})\n",
580
+ " return float(step_obs.get('reward', 0.0)), completion[:200], step_obs.get('feedback', '')\n",
581
+ "\n",
582
+ "\n",
583
+ "print('=' * 65)\n",
584
+ "print('AFTER GRPO TRAINING β€” EVALUATION')\n",
585
+ "print('=' * 65)\n",
586
+ "\n",
587
+ "rewards_after = {}\n",
588
+ "for task_id, difficulty in EVAL_TASKS:\n",
589
+ " r, _, feedback = eval_single_task(task_id, difficulty, model, tokenizer)\n",
590
+ " rewards_after[task_id] = r\n",
591
+ " icon = 'βœ…' if r >= 0.7 else ('⚑' if r >= 0.3 else '❌')\n",
592
+ " print(f'{icon} {task_id:<26} difficulty={difficulty:<8} reward={r:.3f}')\n",
593
+ " if feedback:\n",
594
+ " print(f' {str(feedback)[:110]}')\n",
595
+ "\n",
596
+ "mean_r = sum(rewards_after.values()) / len(rewards_after)\n",
597
+ "print('-' * 65)\n",
598
+ "print(f'Mean reward after GRPO: {mean_r:.3f} (zero-shot baseline ~0.3)')\n",
599
+ "print('=' * 65)\n",
600
+ "print(f'\\nβœ… Trained model: https://huggingface.co/{HUB_REPO}')"
601
+ ]
602
+ },
603
+ {
604
+ "cell_type": "code",
605
+ "execution_count": null,
606
+ "id": "f594a6d6",
607
+ "metadata": {},
608
+ "outputs": [],
609
+ "source": [
610
+ "# ── 11. Cleanup ───────────────────────────────────────────────────────────\n",
611
+ "import gc, torch\n",
612
+ "\n",
613
+ "# Stop BioForge env server\n",
614
+ "try:\n",
615
+ " server_proc.terminate()\n",
616
+ " server_proc.wait(timeout=5)\n",
617
+ " print('βœ… BioForge server stopped')\n",
618
+ "except Exception as e:\n",
619
+ " print(f'Server cleanup: {e}')\n",
620
+ "\n",
621
+ "# Free GPU memory\n",
622
+ "del model\n",
623
+ "gc.collect()\n",
624
+ "if torch.cuda.is_available():\n",
625
+ " torch.cuda.empty_cache()\n",
626
+ " remaining = torch.cuda.memory_allocated() / 1e9\n",
627
+ " print(f'VRAM freed ({remaining:.2f} GB remaining)')\n",
628
+ "\n",
629
+ "print('\\nπŸŽ‰ Training complete!')\n",
630
+ "print(f'πŸ“¦ Model: https://huggingface.co/{HUB_REPO}')"
631
+ ]
632
+ },
633
+ {
634
+ "cell_type": "markdown",
635
+ "id": "4ae1306c",
636
+ "metadata": {},
637
+ "source": [
638
+ "## Training Metrics (W&B)\n",
639
+ "\n",
640
+ "Set `WANDB_API_KEY` in Space Secrets to enable W&B tracking. \n",
641
+ "Key metrics logged during GRPO training:\n",
642
+ "\n",
643
+ "| Metric | Description |\n",
644
+ "|--------|-------------|\n",
645
+ "| `train/reward_mean` | Average reward across all tasks (target: > 0.7) |\n",
646
+ "| `train/reward_std` | Reward standard deviation (should decrease as model improves) |\n",
647
+ "| `train/loss` | GRPO policy loss |\n",
648
+ "| `train/kl` | KL divergence from reference model (bounded by `beta=0.001`) |\n",
649
+ "\n",
650
+ "## What to expect\n",
651
+ "\n",
652
+ "- **Steps 0–100**: Model learns JSON formatting β†’ reward rises from ~0.1 to ~0.4\n",
653
+ "- **Steps 100–300**: Model learns task-specific schemas β†’ reward 0.4–0.65\n",
654
+ "- **Steps 300–500**: Fine-grained biological reasoning improves β†’ reward 0.65–0.80+\n",
655
+ "\n",
656
+ "If reward stagnates below 0.3 after 100 steps, increase `temperature` to 1.0 or reduce `beta`."
657
+ ]
658
+ }
659
+ ],
660
+ "metadata": {
661
+ "language_info": {
662
+ "name": "python"
663
+ }
664
+ },
665
+ "nbformat": 4,
666
+ "nbformat_minor": 5
667
+ }