Pratap-K commited on
Commit
5b9b298
·
1 Parent(s): 7445273

Update training

Browse files
README.md CHANGED
@@ -209,6 +209,28 @@ The self-improving upgrades are inspired by:
209
 
210
  ---
211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  ## 📐 Data Models
213
 
214
  ### Action Space (`SmartpayenvAction`)
 
209
 
210
  ---
211
 
212
+ ## 🧪 Judge Repro (Colab + HF Credits)
213
+
214
+ For hackathon evaluation, use the Colab notebook:
215
+ - `notebooks/theme4_judge_repro_colab.ipynb`
216
+
217
+ What this notebook does:
218
+ - connects to the deployed Space (`https://pratap-k-smartpayenv.hf.space`)
219
+ - collects group-relative preference pairs from `/simulate`
220
+ - runs a lightweight TRL DPO pass
221
+ - writes reproducible artifacts (`artifacts/run_metrics.json`)
222
+
223
+ Judge flow:
224
+ 1. Open notebook in Colab and run all cells.
225
+ 2. Login with Hugging Face token when prompted (credits-enabled account).
226
+ 3. Keep `QUICK_MODE=True` for fast rerun; set `False` for longer training.
227
+
228
+ Expected runtime:
229
+ - Quick mode: ~10-20 minutes
230
+ - Full mode: ~45-90 minutes (depending on Colab hardware/model)
231
+
232
+ ---
233
+
234
  ## 📐 Data Models
235
 
236
  ### Action Space (`SmartpayenvAction`)
notebooks/train.ipynb ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "eab24a17",
6
+ "metadata": {},
7
+ "source": [
8
+ "# SmartPayEnv Theme-4 Judge Repro (Colab, Self-Contained, Unsloth + TRL@git)\n",
9
+ "\n",
10
+ "Self-contained notebook. Does NOT import anything from the repo.\n",
11
+ "\n",
12
+ "Pipeline:\n",
13
+ "1. Install deps (Unsloth + TRL from GitHub)\n",
14
+ "2. HF login (uses your HF credits)\n",
15
+ "3. Connect to deployed SmartPayEnv Space\n",
16
+ "4. Collect group-relative preference pairs (inline)\n",
17
+ "5. Baseline eval (random + heuristic) on frozen seed\n",
18
+ "6. Train policy with Unsloth FastLanguageModel + TRL DPO\n",
19
+ "7. Trained-policy eval on the same frozen seed\n",
20
+ "8. Plots:\n",
21
+ " - rollout reward curve\n",
22
+ " - DPO training loss\n",
23
+ " - before/after mean reward (random vs heuristic vs trained)\n",
24
+ " - mean reward per risk bucket (low / medium / high)\n",
25
+ "9. Save artifacts to ./artifacts\n",
26
+ "\n",
27
+ "Hackathon: OpenEnv (India 2026), Theme #4 — Self-Improvement.\n",
28
+ "Space: https://huggingface.co/spaces/Pratap-K/SmartPayEnv"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "id": "57c1f412",
34
+ "metadata": {},
35
+ "source": [
36
+ "## 1. Install dependencies (Unsloth + TRL from GitHub)"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "code",
41
+ "execution_count": null,
42
+ "id": "c0142bbc",
43
+ "metadata": {},
44
+ "outputs": [],
45
+ "source": [
46
+ "!pip -q install --upgrade pip\n",
47
+ "!pip -q install \"unsloth @ git+https://github.com/unslothai/unsloth.git\"\n",
48
+ "!pip -q install \"trl @ git+https://github.com/huggingface/trl.git\"\n",
49
+ "!pip -q install --upgrade transformers accelerate peft bitsandbytes datasets huggingface_hub matplotlib pandas requests numpy"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "markdown",
54
+ "id": "e4f39274",
55
+ "metadata": {},
56
+ "source": [
57
+ "## 2. Authenticate Hugging Face"
58
+ ]
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "execution_count": null,
63
+ "id": "6a201e39",
64
+ "metadata": {},
65
+ "outputs": [],
66
+ "source": [
67
+ "from huggingface_hub import notebook_login\n",
68
+ "notebook_login()"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "markdown",
73
+ "id": "d5373ffe",
74
+ "metadata": {},
75
+ "source": [
76
+ "## 3. Configuration"
77
+ ]
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "execution_count": null,
82
+ "id": "73b92d43",
83
+ "metadata": {},
84
+ "outputs": [],
85
+ "source": [
86
+ "import os, json, random\n",
87
+ "import numpy as np\n",
88
+ "\n",
89
+ "QUICK_MODE = True\n",
90
+ "ENV_URL = 'https://pratap-k-smartpayenv.hf.space'\n",
91
+ "DIFFICULTY = 2\n",
92
+ "SEED = 42\n",
93
+ "\n",
94
+ "ROLLOUT_STEPS = 60 if QUICK_MODE else 240\n",
95
+ "GROUP_SIZE = 6 if QUICK_MODE else 10\n",
96
+ "EVAL_EPISODES = 3 if QUICK_MODE else 5\n",
97
+ "EVAL_STEPS_PER_EPISODE = 30 if QUICK_MODE else 60\n",
98
+ "\n",
99
+ "MODEL_ID = 'unsloth/Qwen2.5-0.5B-Instruct'\n",
100
+ "MAX_SEQ_LEN = 2048\n",
101
+ "LOAD_IN_4BIT = True\n",
102
+ "\n",
103
+ "os.makedirs('artifacts', exist_ok=True)\n",
104
+ "random.seed(SEED)\n",
105
+ "np.random.seed(SEED)\n",
106
+ "print('Config ready. QUICK_MODE =', QUICK_MODE, '| MODEL_ID =', MODEL_ID)"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "markdown",
111
+ "id": "7060469d",
112
+ "metadata": {},
113
+ "source": [
114
+ "## 4. Health check"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "execution_count": null,
120
+ "id": "b0198da2",
121
+ "metadata": {},
122
+ "outputs": [],
123
+ "source": [
124
+ "import requests\n",
125
+ "r = requests.get(f'{ENV_URL}/health', timeout=30)\n",
126
+ "print('Health:', r.status_code, r.text[:120])"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "markdown",
131
+ "id": "b2d9dcfc",
132
+ "metadata": {},
133
+ "source": [
134
+ "## 5. Inline env helpers"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "execution_count": null,
140
+ "id": "1e10b8d4",
141
+ "metadata": {},
142
+ "outputs": [],
143
+ "source": [
144
+ "def env_reset(difficulty=DIFFICULTY):\n",
145
+ " res = requests.post(f'{ENV_URL}/reset', json={'difficulty': int(difficulty)}, timeout=30)\n",
146
+ " res.raise_for_status()\n",
147
+ " payload = res.json()\n",
148
+ " return payload.get('observation', payload)\n",
149
+ "\n",
150
+ "def env_step(action):\n",
151
+ " res = requests.post(f'{ENV_URL}/step', json={'action': action}, timeout=30)\n",
152
+ " res.raise_for_status()\n",
153
+ " return res.json()\n",
154
+ "\n",
155
+ "def env_simulate(action):\n",
156
+ " res = requests.post(f'{ENV_URL}/simulate', json={'action': action}, timeout=30)\n",
157
+ " res.raise_for_status()\n",
158
+ " return res.json()\n",
159
+ "\n",
160
+ "def all_actions():\n",
161
+ " out = []\n",
162
+ " for g in (0,1,2):\n",
163
+ " for f in (0,1,2,3):\n",
164
+ " for r in (0,1):\n",
165
+ " out.append({'gateway': g, 'fraud_decision': f, 'retry_strategy': r})\n",
166
+ " return out\n",
167
+ "\n",
168
+ "ACTIONS = all_actions()\n",
169
+ "print('Total candidate actions:', len(ACTIONS))"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "markdown",
174
+ "id": "d0d33873",
175
+ "metadata": {},
176
+ "source": [
177
+ "## 6. Collect group-relative preference pairs"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "execution_count": null,
183
+ "id": "db6c57b4",
184
+ "metadata": {},
185
+ "outputs": [],
186
+ "source": [
187
+ "def collect_pairs(steps=ROLLOUT_STEPS, group=GROUP_SIZE, difficulty=DIFFICULTY):\n",
188
+ " obs = env_reset(difficulty)\n",
189
+ " pairs, reward_trace = [], []\n",
190
+ " for _ in range(steps):\n",
191
+ " sampled = random.sample(ACTIONS, k=min(group, len(ACTIONS)))\n",
192
+ " scored = []\n",
193
+ " for a in sampled:\n",
194
+ " try:\n",
195
+ " sim = env_simulate(a)\n",
196
+ " scored.append((a, float(sim.get('reward', 0.0))))\n",
197
+ " except requests.RequestException:\n",
198
+ " continue\n",
199
+ " if len(scored) < 2:\n",
200
+ " break\n",
201
+ " scored.sort(key=lambda x: x[1], reverse=True)\n",
202
+ " best, best_r = scored[0]\n",
203
+ " worst, worst_r = scored[-1]\n",
204
+ "\n",
205
+ " prompt = (\n",
206
+ " 'SmartPayEnv observation:\\n'\n",
207
+ " f'{json.dumps(obs, sort_keys=True)}\\n'\n",
208
+ " 'Return one action JSON with fields: gateway, fraud_decision, retry_strategy.'\n",
209
+ " )\n",
210
+ " pairs.append({\n",
211
+ " 'prompt': prompt,\n",
212
+ " 'chosen': json.dumps(best, sort_keys=True),\n",
213
+ " 'rejected': json.dumps(worst, sort_keys=True),\n",
214
+ " 'chosen_reward': best_r,\n",
215
+ " 'rejected_reward': worst_r,\n",
216
+ " })\n",
217
+ " reward_trace.append(best_r)\n",
218
+ "\n",
219
+ " step_payload = env_step(best)\n",
220
+ " obs = step_payload.get('observation', step_payload)\n",
221
+ " if bool(obs.get('done', False)):\n",
222
+ " obs = env_reset(difficulty)\n",
223
+ " return pairs, reward_trace\n",
224
+ "\n",
225
+ "pairs, rollout_rewards = collect_pairs()\n",
226
+ "print('Collected pairs:', len(pairs))"
227
+ ]
228
+ },
229
+ {
230
+ "cell_type": "markdown",
231
+ "id": "9d0f2b46",
232
+ "metadata": {},
233
+ "source": [
234
+ "## 7. Baseline evaluation (random + heuristic) with risk-bucket breakdown"
235
+ ]
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "execution_count": null,
240
+ "id": "fc0a1f5b",
241
+ "metadata": {},
242
+ "outputs": [],
243
+ "source": [
244
+ "def risk_bucket(obs):\n",
245
+ " r = float(obs.get('observed_fraud_risk', 0.0))\n",
246
+ " if r < 0.3:\n",
247
+ " return 'low'\n",
248
+ " if r < 0.65:\n",
249
+ " return 'medium'\n",
250
+ " return 'high'\n",
251
+ "\n",
252
+ "def eval_policy(policy_fn, episodes=EVAL_EPISODES, steps=EVAL_STEPS_PER_EPISODE, difficulty=DIFFICULTY):\n",
253
+ " all_rewards = []\n",
254
+ " per_episode_means = []\n",
255
+ " bucket_rewards = {'low': [], 'medium': [], 'high': []}\n",
256
+ " for _ in range(episodes):\n",
257
+ " obs = env_reset(difficulty)\n",
258
+ " ep_rewards = []\n",
259
+ " for _ in range(steps):\n",
260
+ " bucket = risk_bucket(obs)\n",
261
+ " action = policy_fn(obs)\n",
262
+ " payload = env_step(action)\n",
263
+ " obs = payload.get('observation', payload)\n",
264
+ " r = float(obs.get('reward', payload.get('reward', 0.0)))\n",
265
+ " ep_rewards.append(r)\n",
266
+ " bucket_rewards[bucket].append(r)\n",
267
+ " if bool(obs.get('done', False)):\n",
268
+ " obs = env_reset(difficulty)\n",
269
+ " all_rewards.extend(ep_rewards)\n",
270
+ " per_episode_means.append(float(np.mean(ep_rewards)))\n",
271
+ " bucket_means = {k: (float(np.mean(v)) if v else 0.0) for k, v in bucket_rewards.items()}\n",
272
+ " return {\n",
273
+ " 'mean_reward': float(np.mean(all_rewards)) if all_rewards else 0.0,\n",
274
+ " 'per_episode_mean': per_episode_means,\n",
275
+ " 'bucket_means': bucket_means,\n",
276
+ " 'all_rewards': all_rewards,\n",
277
+ " }\n",
278
+ "\n",
279
+ "def random_policy(_obs):\n",
280
+ " return random.choice(ACTIONS)\n",
281
+ "\n",
282
+ "def heuristic_policy(obs):\n",
283
+ " risk = float(obs.get('observed_fraud_risk', 0.0))\n",
284
+ " rates = obs.get('gateway_success_rates', [0.9, 0.9, 0.9]) or [0.9, 0.9, 0.9]\n",
285
+ " gateway = int(np.argmax(rates))\n",
286
+ " if risk > 0.65:\n",
287
+ " fd = 1\n",
288
+ " elif risk > 0.4:\n",
289
+ " fd = 2\n",
290
+ " else:\n",
291
+ " fd = 0\n",
292
+ " return {'gateway': gateway, 'fraud_decision': fd, 'retry_strategy': 1}\n",
293
+ "\n",
294
+ "baseline_random = eval_policy(random_policy)\n",
295
+ "baseline_heuristic = eval_policy(heuristic_policy)\n",
296
+ "print('Random baseline:', baseline_random['mean_reward'], baseline_random['bucket_means'])\n",
297
+ "print('Heuristic baseline:', baseline_heuristic['mean_reward'], baseline_heuristic['bucket_means'])"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "markdown",
302
+ "id": "7c6c10e3",
303
+ "metadata": {},
304
+ "source": [
305
+ "## 8. Train with Unsloth FastLanguageModel + TRL DPO"
306
+ ]
307
+ },
308
+ {
309
+ "cell_type": "code",
310
+ "execution_count": null,
311
+ "id": "bf9a3739",
312
+ "metadata": {},
313
+ "outputs": [],
314
+ "source": [
315
+ "from unsloth import FastLanguageModel\n",
316
+ "from datasets import Dataset\n",
317
+ "from trl import DPOConfig, DPOTrainer\n",
318
+ "\n",
319
+ "model, tokenizer = FastLanguageModel.from_pretrained(\n",
320
+ " model_name=MODEL_ID,\n",
321
+ " max_seq_length=MAX_SEQ_LEN,\n",
322
+ " dtype=None,\n",
323
+ " load_in_4bit=LOAD_IN_4BIT,\n",
324
+ ")\n",
325
+ "model = FastLanguageModel.get_peft_model(\n",
326
+ " model,\n",
327
+ " r=16,\n",
328
+ " target_modules=['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj'],\n",
329
+ " lora_alpha=16,\n",
330
+ " lora_dropout=0.0,\n",
331
+ " bias='none',\n",
332
+ " use_gradient_checkpointing='unsloth',\n",
333
+ " random_state=SEED,\n",
334
+ ")\n",
335
+ "if tokenizer.pad_token is None:\n",
336
+ " tokenizer.pad_token = tokenizer.eos_token\n",
337
+ "\n",
338
+ "ds = Dataset.from_list(pairs)\n",
339
+ "print(ds)\n",
340
+ "\n",
341
+ "cfg = DPOConfig(\n",
342
+ " output_dir='outputs/theme4_dpo_unsloth',\n",
343
+ " per_device_train_batch_size=1,\n",
344
+ " gradient_accumulation_steps=4,\n",
345
+ " num_train_epochs=1 if QUICK_MODE else 2,\n",
346
+ " logging_steps=2,\n",
347
+ " learning_rate=5e-6,\n",
348
+ " max_prompt_length=1024,\n",
349
+ " max_length=1280,\n",
350
+ " save_strategy='no',\n",
351
+ " report_to=[],\n",
352
+ " bf16=True,\n",
353
+ ")\n",
354
+ "\n",
355
+ "trainer = DPOTrainer(\n",
356
+ " model=model,\n",
357
+ " ref_model=None,\n",
358
+ " args=cfg,\n",
359
+ " train_dataset=ds,\n",
360
+ " processing_class=tokenizer,\n",
361
+ ")\n",
362
+ "trainer.train()\n",
363
+ "\n",
364
+ "loss_history = [h.get('loss') for h in trainer.state.log_history if 'loss' in h]\n",
365
+ "print('Training loss points:', len(loss_history))"
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "markdown",
370
+ "id": "12cfc52f",
371
+ "metadata": {},
372
+ "source": [
373
+ "## 9. Trained-policy evaluation"
374
+ ]
375
+ },
376
+ {
377
+ "cell_type": "code",
378
+ "execution_count": null,
379
+ "id": "814937a9",
380
+ "metadata": {},
381
+ "outputs": [],
382
+ "source": [
383
+ "import re\n",
384
+ "import torch\n",
385
+ "\n",
386
+ "FastLanguageModel.for_inference(model)\n",
387
+ "device = next(model.parameters()).device\n",
388
+ "ACTION_RE = re.compile(r'\\{[^{}]*\\}')\n",
389
+ "\n",
390
+ "def parse_action(text):\n",
391
+ " m = ACTION_RE.search(text)\n",
392
+ " if not m:\n",
393
+ " return {'gateway': 1, 'fraud_decision': 0, 'retry_strategy': 1}\n",
394
+ " try:\n",
395
+ " a = json.loads(m.group(0))\n",
396
+ " return {\n",
397
+ " 'gateway': int(a.get('gateway', 1)) % 3,\n",
398
+ " 'fraud_decision': int(a.get('fraud_decision', 0)) % 4,\n",
399
+ " 'retry_strategy': int(a.get('retry_strategy', 1)) % 2,\n",
400
+ " }\n",
401
+ " except Exception:\n",
402
+ " return {'gateway': 1, 'fraud_decision': 0, 'retry_strategy': 1}\n",
403
+ "\n",
404
+ "def trained_policy(obs):\n",
405
+ " prompt = (\n",
406
+ " 'SmartPayEnv observation:\\n'\n",
407
+ " f'{json.dumps(obs, sort_keys=True)}\\n'\n",
408
+ " 'Return one action JSON with fields: gateway, fraud_decision, retry_strategy.'\n",
409
+ " )\n",
410
+ " inputs = tokenizer(prompt, return_tensors='pt', truncation=True, max_length=1024).to(device)\n",
411
+ " with torch.no_grad():\n",
412
+ " out = model.generate(\n",
413
+ " **inputs,\n",
414
+ " max_new_tokens=64,\n",
415
+ " do_sample=False,\n",
416
+ " pad_token_id=tokenizer.pad_token_id,\n",
417
+ " )\n",
418
+ " text = tokenizer.decode(out[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)\n",
419
+ " return parse_action(text)\n",
420
+ "\n",
421
+ "trained_eval = eval_policy(trained_policy)\n",
422
+ "print('Trained policy mean reward:', trained_eval['mean_reward'])\n",
423
+ "print('Trained per-bucket:', trained_eval['bucket_means'])"
424
+ ]
425
+ },
426
+ {
427
+ "cell_type": "markdown",
428
+ "id": "cf9d641c",
429
+ "metadata": {},
430
+ "source": [
431
+ "## 10. Plots and saved artifacts"
432
+ ]
433
+ },
434
+ {
435
+ "cell_type": "code",
436
+ "execution_count": null,
437
+ "id": "e228c3ac",
438
+ "metadata": {},
439
+ "outputs": [],
440
+ "source": [
441
+ "import matplotlib.pyplot as plt\n",
442
+ "\n",
443
+ "plt.figure(figsize=(8,4))\n",
444
+ "plt.plot(rollout_rewards, label='Best-action reward per rollout step')\n",
445
+ "plt.xlabel('Rollout step')\n",
446
+ "plt.ylabel('Reward')\n",
447
+ "plt.title('Group-relative rollout reward (data-collection phase)')\n",
448
+ "plt.legend()\n",
449
+ "plt.tight_layout()\n",
450
+ "plt.savefig('artifacts/rollout_reward_curve.png', dpi=140)\n",
451
+ "plt.show()\n",
452
+ "\n",
453
+ "if loss_history:\n",
454
+ " plt.figure(figsize=(8,4))\n",
455
+ " plt.plot(loss_history, label='DPO training loss')\n",
456
+ " plt.xlabel('Logging step')\n",
457
+ " plt.ylabel('Loss')\n",
458
+ " plt.title('TRL DPO training loss (Unsloth)')\n",
459
+ " plt.legend()\n",
460
+ " plt.tight_layout()\n",
461
+ " plt.savefig('artifacts/training_loss.png', dpi=140)\n",
462
+ " plt.show()\n",
463
+ "\n",
464
+ "labels = ['Random', 'Heuristic', 'Trained LLM']\n",
465
+ "values = [baseline_random['mean_reward'], baseline_heuristic['mean_reward'], trained_eval['mean_reward']]\n",
466
+ "plt.figure(figsize=(7,4))\n",
467
+ "bars = plt.bar(labels, values, color=['#bbb','#88c','#4a8'])\n",
468
+ "for b, v in zip(bars, values):\n",
469
+ " plt.text(b.get_x()+b.get_width()/2, v+0.01, f'{v:.3f}', ha='center')\n",
470
+ "plt.ylabel('Mean reward (frozen holdout)')\n",
471
+ "plt.title('Before vs After Training')\n",
472
+ "plt.tight_layout()\n",
473
+ "plt.savefig('artifacts/before_after_rewards.png', dpi=140)\n",
474
+ "plt.show()\n",
475
+ "\n",
476
+ "buckets = ['low', 'medium', 'high']\n",
477
+ "rand_b = [baseline_random['bucket_means'][b] for b in buckets]\n",
478
+ "heur_b = [baseline_heuristic['bucket_means'][b] for b in buckets]\n",
479
+ "trnd_b = [trained_eval['bucket_means'][b] for b in buckets]\n",
480
+ "x = np.arange(len(buckets))\n",
481
+ "w = 0.27\n",
482
+ "plt.figure(figsize=(8,4))\n",
483
+ "plt.bar(x - w, rand_b, width=w, label='Random', color='#bbb')\n",
484
+ "plt.bar(x, heur_b, width=w, label='Heuristic', color='#88c')\n",
485
+ "plt.bar(x + w, trnd_b, width=w, label='Trained LLM', color='#4a8')\n",
486
+ "plt.xticks(x, [b.title()+' Risk' for b in buckets])\n",
487
+ "plt.ylabel('Mean reward')\n",
488
+ "plt.title('Per Risk-Bucket Reward (frozen holdout)')\n",
489
+ "plt.legend()\n",
490
+ "plt.tight_layout()\n",
491
+ "plt.savefig('artifacts/per_bucket_rewards.png', dpi=140)\n",
492
+ "plt.show()\n",
493
+ "\n",
494
+ "summary = {\n",
495
+ " 'env_url': ENV_URL,\n",
496
+ " 'model_id': MODEL_ID,\n",
497
+ " 'quick_mode': QUICK_MODE,\n",
498
+ " 'pairs_collected': len(pairs),\n",
499
+ " 'baseline_random_mean_reward': baseline_random['mean_reward'],\n",
500
+ " 'baseline_heuristic_mean_reward': baseline_heuristic['mean_reward'],\n",
501
+ " 'trained_mean_reward': trained_eval['mean_reward'],\n",
502
+ " 'reward_gain_vs_random': trained_eval['mean_reward'] - baseline_random['mean_reward'],\n",
503
+ " 'reward_gain_vs_heuristic': trained_eval['mean_reward'] - baseline_heuristic['mean_reward'],\n",
504
+ " 'per_bucket': {\n",
505
+ " 'random': baseline_random['bucket_means'],\n",
506
+ " 'heuristic': baseline_heuristic['bucket_means'],\n",
507
+ " 'trained': trained_eval['bucket_means'],\n",
508
+ " },\n",
509
+ " 'rollout_reward_trace': rollout_rewards,\n",
510
+ " 'training_loss_history': loss_history,\n",
511
+ " 'eval_per_episode': {\n",
512
+ " 'random': baseline_random['per_episode_mean'],\n",
513
+ " 'heuristic': baseline_heuristic['per_episode_mean'],\n",
514
+ " 'trained': trained_eval['per_episode_mean'],\n",
515
+ " },\n",
516
+ "}\n",
517
+ "with open('artifacts/run_summary.json', 'w', encoding='utf-8') as f:\n",
518
+ " json.dump(summary, f, indent=2)\n",
519
+ "print(json.dumps({k:v for k,v in summary.items() if k not in ('rollout_reward_trace','training_loss_history')}, indent=2))"
520
+ ]
521
+ },
522
+ {
523
+ "cell_type": "markdown",
524
+ "metadata": {},
525
+ "source": [
526
+ "## 11. (Optional) Upload artifacts"
527
+ ]
528
+ },
529
+ {
530
+ "cell_type": "code",
531
+ "execution_count": null,
532
+ "metadata": {},
533
+ "outputs": [],
534
+ "source": [
535
+ "# !huggingface-cli upload <your-hf-repo> artifacts artifacts --repo-type dataset"
536
+ ]
537
+ }
538
+ ],
539
+ "metadata": {
540
+ "kernelspec": {
541
+ "display_name": "Python 3",
542
+ "language": "python",
543
+ "name": "python3"
544
+ },
545
+ "language_info": {
546
+ "name": "python"
547
+ }
548
+ },
549
+ "nbformat": 4,
550
+ "nbformat_minor": 5
551
+ }
notebooks/train_smartpayenev.ipynb ADDED
@@ -0,0 +1,953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "1035bc6e",
6
+ "metadata": {},
7
+ "source": [
8
+ "# SmartPayEnv Theme-4 Judge Repro — Co-Evolving Defender vs Fraud (GRPO + Unsloth + TRL)\n",
9
+ "\n",
10
+ "Self-contained Colab notebook. **No imports from this repo.** Uses only the deployed\n",
11
+ "Hugging Face Space's HTTP endpoints: `/health`, `/reset`, `/step`,\n",
12
+ "`/reset_seeded`, `/configure_adversary`.\n",
13
+ "\n",
14
+ "### What's new (vs. a vanilla GRPO loop)\n",
15
+ "\n",
16
+ "This notebook implements **true co-evolution** between two learning agents:\n",
17
+ "\n",
18
+ "* **Defender LLM** — `unsloth/Qwen2.5-0.5B-Instruct` trained with **TRL GRPO**.\n",
19
+ " Reward comes from a real **K-step rollout** in the env (not a single noisy step).\n",
20
+ " All `num_generations` completions in a GRPO group share the **same seed**\n",
21
+ " (via `/reset_seeded`), so the group-relative advantage is signal, not noise.\n",
22
+ "\n",
23
+ "* **Fraud agent** — a small **parametric policy** with 3 continuous parameters\n",
24
+ " (`intensity`, `noise_boost`, `pattern_rate`) updated by **Evolution Strategies (ES)**.\n",
25
+ " After each defender round we run a few ES iterations to make fraud *harder*\n",
26
+ " for the current defender. Updates are pushed to the env via\n",
27
+ " `/configure_adversary`.\n",
28
+ "\n",
29
+ "Co-training loop (alternating, AlphaStar-PFSP-inspired):\n",
30
+ "```\n",
31
+ "for round in range(N_ROUNDS):\n",
32
+ " 1. Train defender (GRPO) against current fraud agent\n",
33
+ " 2. Snapshot defender (LoRA) into the league\n",
34
+ " 3. Update fraud agent (ES) against the latest + a sampled past defender\n",
35
+ " 4. Log: defender reward, fraud reward, exploitability gap\n",
36
+ "```\n",
37
+ "\n",
38
+ "Why this matters:\n",
39
+ "* Single-step rewards are noisy → **multi-step rollout** kills variance.\n",
40
+ "* Different start states per generation → **same-seed group** gives clean GRPO advantages.\n",
41
+ "* Static adversary → defender plateaus → **learning fraud agent** keeps pressure escalating.\n",
42
+ "* Cyclic strategies → **league snapshots + PFSP sampling** stabilise training.\n",
43
+ "\n",
44
+ "Pipeline:\n",
45
+ "1. Install deps (Unsloth + TRL from GitHub)\n",
46
+ "2. HF login (uses your HF credits)\n",
47
+ "3. GPU sanity check + env health\n",
48
+ "4. Build prompt dataset from live `/step` rollouts\n",
49
+ "5. Baseline eval (random + heuristic) on a frozen seed\n",
50
+ "6. **Co-training loop** — alternating GRPO defender + ES fraud agent\n",
51
+ "7. Trained-policy eval on the frozen seed\n",
52
+ "8. Plots:\n",
53
+ " - Defender mean reward per round\n",
54
+ " - Fraud agent mean reward per round\n",
55
+ " - Exploitability gap per round\n",
56
+ " - Fraud parameter trajectories\n",
57
+ " - Before vs After mean reward (random / heuristic / trained)\n",
58
+ " - Per risk-bucket reward (low / medium / high)\n",
59
+ "9. Save artifacts to `./artifacts`\n",
60
+ "\n",
61
+ "Hackathon: OpenEnv (India 2026), Theme #4 — Self-Improvement.\n",
62
+ "Space: https://huggingface.co/spaces/Pratap-K/SmartPayEnv"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "markdown",
67
+ "metadata": {},
68
+ "source": [
69
+ "## 1. Install dependencies (Unsloth + TRL from GitHub)"
70
+ ]
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "execution_count": null,
75
+ "metadata": {},
76
+ "outputs": [],
77
+ "source": [
78
+ "!pip -q install --upgrade pip\n",
79
+ "!pip -q install \"unsloth @ git+https://github.com/unslothai/unsloth.git\"\n",
80
+ "!pip -q install \"trl @ git+https://github.com/huggingface/trl.git\"\n",
81
+ "!pip -q install --upgrade transformers accelerate peft bitsandbytes datasets huggingface_hub matplotlib pandas requests numpy"
82
+ ]
83
+ },
84
+ {
85
+ "cell_type": "markdown",
86
+ "metadata": {},
87
+ "source": [
88
+ "## 2. Authenticate Hugging Face"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": null,
94
+ "metadata": {},
95
+ "outputs": [],
96
+ "source": [
97
+ "from huggingface_hub import notebook_login\n",
98
+ "notebook_login()"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "markdown",
103
+ "metadata": {},
104
+ "source": [
105
+ "## 3. Configuration"
106
+ ]
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "execution_count": null,
111
+ "id": "d061c005",
112
+ "metadata": {},
113
+ "outputs": [],
114
+ "source": [
115
+ "import os, json, random, re, copy\n",
116
+ "import numpy as np\n",
117
+ "\n",
118
+ "QUICK_MODE = True\n",
119
+ "ENV_URL = 'https://pratap-k-smartpayenv.hf.space'\n",
120
+ "DIFFICULTY = 2\n",
121
+ "SEED = 42\n",
122
+ "\n",
123
+ "# Co-evolution loop\n",
124
+ "N_ROUNDS = 3 if QUICK_MODE else 6 # defender<->fraud alternations\n",
125
+ "GRPO_STEPS_PER_ROUND = 12 if QUICK_MODE else 40\n",
126
+ "ES_STEPS_PER_ROUND = 4 if QUICK_MODE else 10\n",
127
+ "ES_POPULATION = 4 if QUICK_MODE else 8\n",
128
+ "ES_SIGMA = 0.25 # exploration std for ES\n",
129
+ "ES_LR = 0.4 # ES update rate\n",
130
+ "\n",
131
+ "# Defender / GRPO\n",
132
+ "PROMPT_DATASET_SIZE = 48 if QUICK_MODE else 192\n",
133
+ "GRPO_NUM_GENERATIONS = 8 if QUICK_MODE else 8 # bigger group = better advantage\n",
134
+ "ROLLOUT_STEPS_PER_REWARD = 4 if QUICK_MODE else 6 # multi-step rollout per generation\n",
135
+ "\n",
136
+ "# Eval\n",
137
+ "EVAL_EPISODES = 3 if QUICK_MODE else 5\n",
138
+ "EVAL_STEPS_PER_EPISODE = 30 if QUICK_MODE else 60\n",
139
+ "\n",
140
+ "MODEL_ID = 'unsloth/Qwen2.5-0.5B-Instruct'\n",
141
+ "MAX_SEQ_LEN = 2048\n",
142
+ "LOAD_IN_4BIT = True\n",
143
+ "\n",
144
+ "os.makedirs('artifacts', exist_ok=True)\n",
145
+ "random.seed(SEED)\n",
146
+ "np.random.seed(SEED)\n",
147
+ "print('Config ready. QUICK_MODE =', QUICK_MODE,\n",
148
+ " '| ROUNDS =', N_ROUNDS,\n",
149
+ " '| GRPO/round =', GRPO_STEPS_PER_ROUND,\n",
150
+ " '| ES/round =', ES_STEPS_PER_ROUND,\n",
151
+ " '| MODEL_ID =', MODEL_ID)"
152
+ ]
153
+ },
154
+ {
155
+ "cell_type": "markdown",
156
+ "id": "c4df0645",
157
+ "metadata": {},
158
+ "source": [
159
+ "## 4. GPU sanity check (Unsloth requires CUDA)\n",
160
+ "\n",
161
+ "If this cell prints \"No CUDA GPU detected\", switch the Colab runtime to a GPU:\n",
162
+ "**Runtime → Change runtime type → Hardware accelerator → T4 GPU**, then\n",
163
+ "**Runtime → Restart runtime** and re-run from the top."
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": null,
169
+ "id": "cf7309eb",
170
+ "metadata": {},
171
+ "outputs": [],
172
+ "source": [
173
+ "import torch, requests\n",
174
+ "\n",
175
+ "if not torch.cuda.is_available():\n",
176
+ " raise RuntimeError(\n",
177
+ " \"No CUDA GPU detected. Unsloth requires an NVIDIA GPU.\\n\"\n",
178
+ " \"On Colab: Runtime > Change runtime type > Hardware accelerator > T4 GPU, \"\n",
179
+ " \"then Runtime > Restart runtime, and re-run from the top.\"\n",
180
+ " )\n",
181
+ "print('CUDA OK ->', torch.cuda.get_device_name(0),\n",
182
+ " '| torch', torch.__version__, '| cuda', torch.version.cuda)\n",
183
+ "\n",
184
+ "r = requests.get(f'{ENV_URL}/health', timeout=30)\n",
185
+ "print('Env health:', r.status_code, r.text[:120])"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "markdown",
190
+ "metadata": {},
191
+ "source": [
192
+ "## 5. Inline env helpers"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "execution_count": null,
198
+ "id": "8657d46f",
199
+ "metadata": {},
200
+ "outputs": [],
201
+ "source": [
202
+ "def env_reset(difficulty=DIFFICULTY):\n",
203
+ " \"\"\"OpenEnv standard /reset endpoint. Returns the initial observation.\"\"\"\n",
204
+ " res = requests.post(f'{ENV_URL}/reset', json={'difficulty': int(difficulty)}, timeout=30)\n",
205
+ " res.raise_for_status()\n",
206
+ " payload = res.json()\n",
207
+ " return payload.get('observation', payload)\n",
208
+ "\n",
209
+ "def env_reset_seeded(seed, difficulty=DIFFICULTY):\n",
210
+ " \"\"\"Deterministic /reset_seeded — same seed gives the same starting trajectory.\n",
211
+ " Falls back to /reset if the deployed Space hasn't been redeployed yet.\"\"\"\n",
212
+ " try:\n",
213
+ " res = requests.post(\n",
214
+ " f'{ENV_URL}/reset_seeded',\n",
215
+ " json={'difficulty': int(difficulty), 'seed': int(seed)},\n",
216
+ " timeout=30,\n",
217
+ " )\n",
218
+ " if res.status_code == 404:\n",
219
+ " return env_reset(difficulty)\n",
220
+ " res.raise_for_status()\n",
221
+ " payload = res.json()\n",
222
+ " return payload.get('observation', payload)\n",
223
+ " except requests.RequestException:\n",
224
+ " return env_reset(difficulty)\n",
225
+ "\n",
226
+ "def env_step(action):\n",
227
+ " \"\"\"OpenEnv standard /step endpoint. Returns the step payload (observation + reward + done).\"\"\"\n",
228
+ " res = requests.post(f'{ENV_URL}/step', json={'action': action}, timeout=30)\n",
229
+ " res.raise_for_status()\n",
230
+ " return res.json()\n",
231
+ "\n",
232
+ "def env_configure_adversary(intensity=None, noise_boost=None, pattern_rate=None, strategy=None):\n",
233
+ " \"\"\"Push fraud-agent parameters to the env. No-op (returns None) if the\n",
234
+ " deployed Space doesn't expose the endpoint yet.\"\"\"\n",
235
+ " body = {k: v for k, v in dict(\n",
236
+ " intensity=intensity, noise_boost=noise_boost,\n",
237
+ " pattern_rate=pattern_rate, strategy=strategy,\n",
238
+ " ).items() if v is not None}\n",
239
+ " try:\n",
240
+ " res = requests.post(f'{ENV_URL}/configure_adversary', json=body, timeout=30)\n",
241
+ " if res.status_code == 404:\n",
242
+ " return None\n",
243
+ " res.raise_for_status()\n",
244
+ " return res.json()\n",
245
+ " except requests.RequestException as e:\n",
246
+ " print('configure_adversary failed:', repr(e))\n",
247
+ " return None\n",
248
+ "\n",
249
+ "def rollout_reward(action, seed, difficulty=DIFFICULTY, k=ROLLOUT_STEPS_PER_REWARD):\n",
250
+ " \"\"\"K-step rollout reward. Resets to a deterministic seed, then keeps replaying\n",
251
+ " the SAME action for `k` steps. The mean reward is far less noisy than a single\n",
252
+ " /step, and the seed makes all completions in a GRPO group comparable.\"\"\"\n",
253
+ " env_reset_seeded(seed, difficulty)\n",
254
+ " rewards = []\n",
255
+ " for _ in range(int(k)):\n",
256
+ " payload = env_step(action)\n",
257
+ " obs = payload.get('observation', payload)\n",
258
+ " rewards.append(float(obs.get('reward', payload.get('reward', 0.0))))\n",
259
+ " if bool(obs.get('done', False)):\n",
260
+ " break\n",
261
+ " return float(np.mean(rewards)) if rewards else 0.0\n",
262
+ "\n",
263
+ "def all_actions():\n",
264
+ " out = []\n",
265
+ " for g in (0,1,2):\n",
266
+ " for f in (0,1,2,3):\n",
267
+ " for r in (0,1):\n",
268
+ " out.append({'gateway': g, 'fraud_decision': f, 'retry_strategy': r})\n",
269
+ " return out\n",
270
+ "\n",
271
+ "ACTIONS = all_actions()\n",
272
+ "ACTION_RE = re.compile(r'\\{[^{}]*\\}')\n",
273
+ "\n",
274
+ "def parse_action(text):\n",
275
+ " m = ACTION_RE.search(text or '')\n",
276
+ " if not m:\n",
277
+ " return {'gateway': 1, 'fraud_decision': 0, 'retry_strategy': 1}\n",
278
+ " try:\n",
279
+ " a = json.loads(m.group(0))\n",
280
+ " return {\n",
281
+ " 'gateway': int(a.get('gateway', 1)) % 3,\n",
282
+ " 'fraud_decision': int(a.get('fraud_decision', 0)) % 4,\n",
283
+ " 'retry_strategy': int(a.get('retry_strategy', 1)) % 2,\n",
284
+ " }\n",
285
+ " except Exception:\n",
286
+ " return {'gateway': 1, 'fraud_decision': 0, 'retry_strategy': 1}\n",
287
+ "\n",
288
+ "ACTION_LEGEND = (\n",
289
+ " 'Action legend:\\n'\n",
290
+ " ' gateway: 0=cheap, 1=balanced, 2=premium\\n'\n",
291
+ " ' fraud_decision: 0=Allow, 1=Block, 2=Challenge(3DS), 3=Manual Review\\n'\n",
292
+ " ' retry_strategy: 0=NoRetry, 1=FailoverNextGateway\\n'\n",
293
+ " 'Goal: maximise routing success + fraud detection while preserving retention.\\n'\n",
294
+ " 'Rule of thumb: high observed_fraud_risk -> Block or 3DS; low -> Allow.'\n",
295
+ ")\n",
296
+ "\n",
297
+ "def make_prompt(obs):\n",
298
+ " \"\"\"Curriculum-aware prompt: include risk hint + action legend so the\n",
299
+ " model has a notion of *what's good* before any training.\"\"\"\n",
300
+ " risk = float(obs.get('observed_fraud_risk', 0.0))\n",
301
+ " bucket = 'LOW' if risk < 0.3 else ('MEDIUM' if risk < 0.65 else 'HIGH')\n",
302
+ " return (\n",
303
+ " f'{ACTION_LEGEND}\\n'\n",
304
+ " f'Observed fraud risk bucket: {bucket} (raw={risk:.2f})\\n'\n",
305
+ " 'SmartPayEnv observation:\\n'\n",
306
+ " f'{json.dumps(obs, sort_keys=True)}\\n'\n",
307
+ " 'Return one action JSON with fields: gateway, fraud_decision, retry_strategy.'\n",
308
+ " )\n",
309
+ "\n",
310
+ "print('Inline env + parser ready. Actions:', len(ACTIONS))"
311
+ ]
312
+ },
313
+ {
314
+ "cell_type": "markdown",
315
+ "metadata": {},
316
+ "source": [
317
+ "## 6. Build prompt dataset (live observations from env)"
318
+ ]
319
+ },
320
+ {
321
+ "cell_type": "code",
322
+ "execution_count": null,
323
+ "metadata": {},
324
+ "outputs": [],
325
+ "source": [
326
+ "def collect_prompts(n=PROMPT_DATASET_SIZE, difficulty=DIFFICULTY):\n",
327
+ " obs = env_reset(difficulty)\n",
328
+ " prompts = []\n",
329
+ " for _ in range(n):\n",
330
+ " prompts.append(make_prompt(obs))\n",
331
+ " a = random.choice(ACTIONS)\n",
332
+ " payload = env_step(a)\n",
333
+ " obs = payload.get('observation', payload)\n",
334
+ " if bool(obs.get('done', False)):\n",
335
+ " obs = env_reset(difficulty)\n",
336
+ " return prompts\n",
337
+ "\n",
338
+ "prompts = collect_prompts()\n",
339
+ "print('Prompts collected:', len(prompts))\n",
340
+ "print('Example prompt:\\n', prompts[0][:300], '...')"
341
+ ]
342
+ },
343
+ {
344
+ "cell_type": "markdown",
345
+ "metadata": {},
346
+ "source": [
347
+ "## 7. Baseline evaluation (random + heuristic)"
348
+ ]
349
+ },
350
+ {
351
+ "cell_type": "code",
352
+ "execution_count": null,
353
+ "metadata": {},
354
+ "outputs": [],
355
+ "source": [
356
+ "def risk_bucket(obs):\n",
357
+ " r = float(obs.get('observed_fraud_risk', 0.0))\n",
358
+ " if r < 0.3:\n",
359
+ " return 'low'\n",
360
+ " if r < 0.65:\n",
361
+ " return 'medium'\n",
362
+ " return 'high'\n",
363
+ "\n",
364
+ "def eval_policy(policy_fn, episodes=EVAL_EPISODES, steps=EVAL_STEPS_PER_EPISODE, difficulty=DIFFICULTY):\n",
365
+ " all_rewards = []\n",
366
+ " per_episode_means = []\n",
367
+ " bucket_rewards = {'low': [], 'medium': [], 'high': []}\n",
368
+ " for _ in range(episodes):\n",
369
+ " obs = env_reset(difficulty)\n",
370
+ " ep_rewards = []\n",
371
+ " for _ in range(steps):\n",
372
+ " bucket = risk_bucket(obs)\n",
373
+ " action = policy_fn(obs)\n",
374
+ " payload = env_step(action)\n",
375
+ " obs = payload.get('observation', payload)\n",
376
+ " r = float(obs.get('reward', payload.get('reward', 0.0)))\n",
377
+ " ep_rewards.append(r)\n",
378
+ " bucket_rewards[bucket].append(r)\n",
379
+ " if bool(obs.get('done', False)):\n",
380
+ " obs = env_reset(difficulty)\n",
381
+ " all_rewards.extend(ep_rewards)\n",
382
+ " per_episode_means.append(float(np.mean(ep_rewards)))\n",
383
+ " bucket_means = {k: (float(np.mean(v)) if v else 0.0) for k, v in bucket_rewards.items()}\n",
384
+ " return {\n",
385
+ " 'mean_reward': float(np.mean(all_rewards)) if all_rewards else 0.0,\n",
386
+ " 'per_episode_mean': per_episode_means,\n",
387
+ " 'bucket_means': bucket_means,\n",
388
+ " }\n",
389
+ "\n",
390
+ "def random_policy(_obs):\n",
391
+ " return random.choice(ACTIONS)\n",
392
+ "\n",
393
+ "def heuristic_policy(obs):\n",
394
+ " risk = float(obs.get('observed_fraud_risk', 0.0))\n",
395
+ " rates = obs.get('gateway_success_rates', [0.9, 0.9, 0.9]) or [0.9, 0.9, 0.9]\n",
396
+ " gateway = int(np.argmax(rates))\n",
397
+ " if risk > 0.65:\n",
398
+ " fd = 1\n",
399
+ " elif risk > 0.4:\n",
400
+ " fd = 2\n",
401
+ " else:\n",
402
+ " fd = 0\n",
403
+ " return {'gateway': gateway, 'fraud_decision': fd, 'retry_strategy': 1}\n",
404
+ "\n",
405
+ "baseline_random = eval_policy(random_policy)\n",
406
+ "baseline_heuristic = eval_policy(heuristic_policy)\n",
407
+ "print('Random baseline:', baseline_random['mean_reward'], baseline_random['bucket_means'])\n",
408
+ "print('Heuristic baseline:', baseline_heuristic['mean_reward'], baseline_heuristic['bucket_means'])"
409
+ ]
410
+ },
411
+ {
412
+ "cell_type": "markdown",
413
+ "id": "16aefdd3",
414
+ "metadata": {},
415
+ "source": [
416
+ "## 7b. Learnable Fraud Agent (parametric, Evolution Strategies)\n",
417
+ "\n",
418
+ "The fraud agent has 3 continuous parameters pushed to the env via `/configure_adversary`:\n",
419
+ "\n",
420
+ "| Param | Range | What it does |\n",
421
+ "|---|---|---|\n",
422
+ "| `intensity` | 0.5 – 2.5 | multiplies the underlying fraud risk of each transaction |\n",
423
+ "| `noise_boost` | 0.0 – 0.6 | adds extra std to `observed_fraud_risk` (stealth) |\n",
424
+ "| `pattern_rate` | 0.0 – 0.9 | probability of injecting a fraud-surge pattern every 10 steps |\n",
425
+ "\n",
426
+ "ES update rule: sample `ES_POPULATION` perturbations around current θ, score each by\n",
427
+ "running the **current defender** for a short rollout (lower defender reward = higher\n",
428
+ "fraud reward), then take a weighted gradient step toward the best perturbations."
429
+ ]
430
+ },
431
+ {
432
+ "cell_type": "code",
433
+ "execution_count": null,
434
+ "id": "4b9c3648",
435
+ "metadata": {},
436
+ "outputs": [],
437
+ "source": [
438
+ "FRAUD_PARAM_BOUNDS = {\n",
439
+ " 'intensity': (0.8, 2.2),\n",
440
+ " 'noise_boost': (0.0, 0.5),\n",
441
+ " 'pattern_rate': (0.05, 0.85),\n",
442
+ "}\n",
443
+ "\n",
444
+ "def _clip_theta(theta):\n",
445
+ " return {k: float(np.clip(theta[k], lo, hi)) for k, (lo, hi) in FRAUD_PARAM_BOUNDS.items()}\n",
446
+ "\n",
447
+ "class FraudPolicy:\n",
448
+ " \"\"\"Parametric fraud agent updated by Evolution Strategies (no gradients).\"\"\"\n",
449
+ " def __init__(self):\n",
450
+ " self.theta = {'intensity': 1.0, 'noise_boost': 0.05, 'pattern_rate': 0.2}\n",
451
+ " self.history = [dict(self.theta)]\n",
452
+ "\n",
453
+ " def apply(self):\n",
454
+ " env_configure_adversary(**self.theta, strategy='mixed')\n",
455
+ "\n",
456
+ " def evaluate_against_defender(self, defender_fn, n_episodes=2, n_steps=12):\n",
457
+ " \"\"\"Defender_fn(obs)->action_dict. Returns mean defender reward (lower = harder fraud).\"\"\"\n",
458
+ " rewards = []\n",
459
+ " for ep in range(int(n_episodes)):\n",
460
+ " obs = env_reset_seeded(seed=10_000 + ep, difficulty=DIFFICULTY)\n",
461
+ " for _ in range(int(n_steps)):\n",
462
+ " a = defender_fn(obs)\n",
463
+ " payload = env_step(a)\n",
464
+ " obs = payload.get('observation', payload)\n",
465
+ " rewards.append(float(obs.get('reward', payload.get('reward', 0.0))))\n",
466
+ " if bool(obs.get('done', False)):\n",
467
+ " obs = env_reset_seeded(seed=10_000 + ep, difficulty=DIFFICULTY)\n",
468
+ " return float(np.mean(rewards)) if rewards else 0.5\n",
469
+ "\n",
470
+ " def es_step(self, defender_fn, sigma=ES_SIGMA, lr=ES_LR, population=ES_POPULATION):\n",
471
+ " \"\"\"One ES update. Higher fraud-fitness = lower defender reward.\"\"\"\n",
472
+ " keys = list(self.theta.keys())\n",
473
+ " base = np.array([self.theta[k] for k in keys], dtype=np.float64)\n",
474
+ " perturbs = np.random.randn(population, len(keys))\n",
475
+ " candidate_thetas = []\n",
476
+ " fitnesses = []\n",
477
+ " for i in range(population):\n",
478
+ " cand_vec = base + sigma * perturbs[i]\n",
479
+ " cand = _clip_theta({k: float(cand_vec[j]) for j, k in enumerate(keys)})\n",
480
+ " env_configure_adversary(**cand, strategy='mixed')\n",
481
+ " def_reward = self.evaluate_against_defender(defender_fn)\n",
482
+ " fraud_fitness = 1.0 - def_reward # zero-sum-ish\n",
483
+ " candidate_thetas.append(cand)\n",
484
+ " fitnesses.append(fraud_fitness)\n",
485
+ " # Rank-based weighting (robust ES)\n",
486
+ " order = np.argsort(fitnesses)[::-1] # best first\n",
487
+ " weights = np.zeros(population)\n",
488
+ " for rank, idx in enumerate(order):\n",
489
+ " weights[idx] = max(0.0, np.log(population / 2 + 1) - np.log(rank + 1))\n",
490
+ " if weights.sum() > 0:\n",
491
+ " weights = weights / weights.sum()\n",
492
+ " # Natural gradient estimate\n",
493
+ " grad = (weights[:, None] * perturbs).sum(axis=0) / max(sigma, 1e-6)\n",
494
+ " new_vec = base + lr * sigma * grad\n",
495
+ " new_theta = _clip_theta({k: float(new_vec[j]) for j, k in enumerate(keys)})\n",
496
+ " self.theta = new_theta\n",
497
+ " self.history.append(dict(self.theta))\n",
498
+ " # Push winning theta to env for the next defender round\n",
499
+ " self.apply()\n",
500
+ " return {\n",
501
+ " 'theta': dict(self.theta),\n",
502
+ " 'mean_fraud_fitness': float(np.mean(fitnesses)),\n",
503
+ " 'best_fraud_fitness': float(np.max(fitnesses)),\n",
504
+ " }\n",
505
+ "\n",
506
+ "fraud_agent = FraudPolicy()\n",
507
+ "fraud_agent.apply()\n",
508
+ "print('Fraud agent initialised with theta =', fraud_agent.theta)"
509
+ ]
510
+ },
511
+ {
512
+ "cell_type": "markdown",
513
+ "id": "5efe6c56",
514
+ "metadata": {},
515
+ "source": [
516
+ "## 8. Co-evolving Training Loop — Defender (GRPO) ⇄ Fraud (ES)\n",
517
+ "\n",
518
+ "Each round:\n",
519
+ "1. **Defender phase (GRPO)** — `GRPO_STEPS_PER_ROUND` gradient steps. Reward for\n",
520
+ " each completion is a **K-step rollout** with a **shared seed** across the\n",
521
+ " whole GRPO group → clean group-relative advantage.\n",
522
+ "2. **Snapshot defender** policy into the league (LoRA state dict in memory).\n",
523
+ "3. **Fraud phase (ES)** — `ES_STEPS_PER_ROUND` ES updates. Each samples\n",
524
+ " `ES_POPULATION` perturbations of the fraud parameters, evaluates each by\n",
525
+ " running the **current defender** for a short rollout, and steps θ toward\n",
526
+ " perturbations that *lower* defender reward.\n",
527
+ "4. Apply the new fraud θ to the env via `/configure_adversary` → next defender\n",
528
+ " round must learn against a harder adversary.\n",
529
+ "\n",
530
+ "Reward signal flow (per defender generation):\n",
531
+ "```\n",
532
+ "group_seed = hash(prompt) % 2**31\n",
533
+ "for completion in group:\n",
534
+ " action = parse_action(completion)\n",
535
+ " reward = mean( /step(action) over K steps starting at /reset_seeded(group_seed) )\n",
536
+ "```\n",
537
+ "All `num_generations` completions of one prompt share `group_seed`, so the only\n",
538
+ "thing varying inside a group is the action — exactly what GRPO needs.\n",
539
+ "\n",
540
+ "No `/simulate` is used anywhere."
541
+ ]
542
+ },
543
+ {
544
+ "cell_type": "code",
545
+ "execution_count": null,
546
+ "id": "435eb8b0",
547
+ "metadata": {},
548
+ "outputs": [],
549
+ "source": [
550
+ "from unsloth import FastLanguageModel\n",
551
+ "from datasets import Dataset\n",
552
+ "from trl import GRPOConfig, GRPOTrainer\n",
553
+ "import hashlib, torch\n",
554
+ "\n",
555
+ "model, tokenizer = FastLanguageModel.from_pretrained(\n",
556
+ " model_name=MODEL_ID,\n",
557
+ " max_seq_length=MAX_SEQ_LEN,\n",
558
+ " dtype=None,\n",
559
+ " load_in_4bit=LOAD_IN_4BIT,\n",
560
+ ")\n",
561
+ "model = FastLanguageModel.get_peft_model(\n",
562
+ " model,\n",
563
+ " r=16,\n",
564
+ " target_modules=['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj'],\n",
565
+ " lora_alpha=32,\n",
566
+ " lora_dropout=0.0,\n",
567
+ " bias='none',\n",
568
+ " use_gradient_checkpointing='unsloth',\n",
569
+ " random_state=SEED,\n",
570
+ ")\n",
571
+ "if tokenizer.pad_token is None:\n",
572
+ " tokenizer.pad_token = tokenizer.eos_token\n",
573
+ "\n",
574
+ "ds = Dataset.from_list([{'prompt': p} for p in prompts])\n",
575
+ "print(ds)\n",
576
+ "\n",
577
+ "# ── Reward fn: same-seed group + multi-step rollout ───────────────────\n",
578
+ "_REWARD_DEBUG = {'calls': 0}\n",
579
+ "\n",
580
+ "def _extract_text(comp):\n",
581
+ " if isinstance(comp, str):\n",
582
+ " return comp\n",
583
+ " if isinstance(comp, list) and comp and isinstance(comp[0], dict):\n",
584
+ " return comp[0].get('content', '') or ''\n",
585
+ " if isinstance(comp, dict):\n",
586
+ " return comp.get('content', '') or ''\n",
587
+ " return str(comp)\n",
588
+ "\n",
589
+ "def _seed_for_prompt(prompt_text):\n",
590
+ " h = hashlib.md5(prompt_text.encode('utf-8')).hexdigest()\n",
591
+ " return int(h[:8], 16) & 0x7FFFFFFF\n",
592
+ "\n",
593
+ "def reward_fn(completions, prompts=None, **kwargs):\n",
594
+ " \"\"\"For each completion: parse action, run K-step rollout starting from a\n",
595
+ " seed derived from THIS prompt (so all completions in the group share state).\"\"\"\n",
596
+ " rewards = []\n",
597
+ " prompts = prompts or [None] * len(completions)\n",
598
+ " for prompt_text, comp in zip(prompts, completions):\n",
599
+ " text = _extract_text(comp)\n",
600
+ " action = parse_action(text)\n",
601
+ " seed = _seed_for_prompt(prompt_text or text)\n",
602
+ " try:\n",
603
+ " r = rollout_reward(action, seed=seed, difficulty=DIFFICULTY,\n",
604
+ " k=ROLLOUT_STEPS_PER_REWARD)\n",
605
+ " except Exception as e:\n",
606
+ " print('reward_fn error:', repr(e))\n",
607
+ " r = 0.0\n",
608
+ " rewards.append(float(r))\n",
609
+ " _REWARD_DEBUG['calls'] += 1\n",
610
+ " if _REWARD_DEBUG['calls'] <= 3:\n",
611
+ " print(f\"[reward_fn batch {_REWARD_DEBUG['calls']}] sample rewards: {rewards[:8]}\")\n",
612
+ " return rewards\n",
613
+ "\n",
614
+ "# ── Defender policy fn (used inside ES eval) ──────────────────────────\n",
615
+ "@torch.no_grad()\n",
616
+ "def _defender_action(obs):\n",
617
+ " FastLanguageModel.for_inference(model)\n",
618
+ " device = next(model.parameters()).device\n",
619
+ " prompt = make_prompt(obs)\n",
620
+ " inputs = tokenizer(prompt, return_tensors='pt', truncation=True, max_length=1024).to(device)\n",
621
+ " out = model.generate(\n",
622
+ " **inputs, max_new_tokens=48, do_sample=False,\n",
623
+ " pad_token_id=tokenizer.pad_token_id,\n",
624
+ " )\n",
625
+ " text = tokenizer.decode(out[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)\n",
626
+ " FastLanguageModel.for_training(model)\n",
627
+ " return parse_action(text)\n",
628
+ "\n",
629
+ "# ── GRPO config (per-round) ───────────────────────────────────────────\n",
630
+ "def _make_grpo_cfg(max_steps):\n",
631
+ " return GRPOConfig(\n",
632
+ " output_dir='outputs/theme4_grpo_unsloth',\n",
633
+ " num_generations=GRPO_NUM_GENERATIONS,\n",
634
+ " max_prompt_length=1024,\n",
635
+ " max_completion_length=48,\n",
636
+ " per_device_train_batch_size=1,\n",
637
+ " gradient_accumulation_steps=2,\n",
638
+ " max_steps=int(max_steps),\n",
639
+ " logging_steps=2,\n",
640
+ " learning_rate=1e-5,\n",
641
+ " save_strategy='no',\n",
642
+ " report_to=[],\n",
643
+ " bf16=True,\n",
644
+ " temperature=1.0,\n",
645
+ " beta=0.02,\n",
646
+ " )\n",
647
+ "\n",
648
+ "# ── Co-training loop ──────────────────────────────────────────────────\n",
649
+ "defender_round_rewards = [] # mean defender reward at end of each round\n",
650
+ "fraud_round_fitness = [] # mean fraud fitness per ES burst\n",
651
+ "exploitability_log = [] # gap between best-response fraud and base fraud\n",
652
+ "fraud_theta_history = [dict(fraud_agent.theta)]\n",
653
+ "loss_history_all = []\n",
654
+ "reward_log_all = []\n",
655
+ "\n",
656
+ "# Quick eval helper (small to keep co-training cheap)\n",
657
+ "def quick_defender_eval(n_eps=2, n_steps=12):\n",
658
+ " rs = []\n",
659
+ " for ep in range(n_eps):\n",
660
+ " obs = env_reset_seeded(seed=20_000 + ep, difficulty=DIFFICULTY)\n",
661
+ " for _ in range(n_steps):\n",
662
+ " a = _defender_action(obs)\n",
663
+ " payload = env_step(a)\n",
664
+ " obs = payload.get('observation', payload)\n",
665
+ " rs.append(float(obs.get('reward', payload.get('reward', 0.0))))\n",
666
+ " if bool(obs.get('done', False)):\n",
667
+ " obs = env_reset_seeded(seed=20_000 + ep, difficulty=DIFFICULTY)\n",
668
+ " return float(np.mean(rs)) if rs else 0.0\n",
669
+ "\n",
670
+ "# Apply current adversary before first defender round\n",
671
+ "fraud_agent.apply()\n",
672
+ "\n",
673
+ "for rnd in range(N_ROUNDS):\n",
674
+ " print(f'\\n=== Round {rnd+1}/{N_ROUNDS} ===')\n",
675
+ " print(f' fraud theta: {fraud_agent.theta}')\n",
676
+ "\n",
677
+ " # Phase A: defender GRPO\n",
678
+ " cfg = _make_grpo_cfg(max_steps=GRPO_STEPS_PER_ROUND)\n",
679
+ " trainer = GRPOTrainer(\n",
680
+ " model=model, args=cfg, train_dataset=ds,\n",
681
+ " processing_class=tokenizer, reward_funcs=[reward_fn],\n",
682
+ " )\n",
683
+ " trainer.train()\n",
684
+ " rnd_loss = [h.get('loss') for h in trainer.state.log_history if 'loss' in h]\n",
685
+ " rnd_rew = [h.get('reward') for h in trainer.state.log_history if 'reward' in h]\n",
686
+ " loss_history_all.extend(rnd_loss)\n",
687
+ " reward_log_all.extend(rnd_rew)\n",
688
+ "\n",
689
+ " # Quick defender eval against current fraud\n",
690
+ " def_score = quick_defender_eval()\n",
691
+ " defender_round_rewards.append(def_score)\n",
692
+ " print(f' defender mean reward (round {rnd+1}): {def_score:.4f}')\n",
693
+ "\n",
694
+ " # Phase B: fraud ES vs current defender\n",
695
+ " if rnd < N_ROUNDS - 1: # skip ES on last round (no defender update will follow)\n",
696
+ " round_fraud_fits = []\n",
697
+ " for es in range(ES_STEPS_PER_ROUND):\n",
698
+ " info = fraud_agent.es_step(_defender_action)\n",
699
+ " round_fraud_fits.append(info['mean_fraud_fitness'])\n",
700
+ " print(f' ES step {es+1}/{ES_STEPS_PER_ROUND}: mean_fitness={info[\"mean_fraud_fitness\"]:.3f}'\n",
701
+ " f' best={info[\"best_fraud_fitness\"]:.3f} theta={info[\"theta\"]}')\n",
702
+ " fraud_round_fitness.append(float(np.mean(round_fraud_fits)) if round_fraud_fits else 0.0)\n",
703
+ " fraud_theta_history.append(dict(fraud_agent.theta))\n",
704
+ "\n",
705
+ " # Exploitability gap: how much WORSE the defender does against trained\n",
706
+ " # fraud vs. against neutral fraud (intensity=1, noise=0.05, pattern_rate=0.2).\n",
707
+ " env_configure_adversary(intensity=1.0, noise_boost=0.05, pattern_rate=0.2, strategy='mixed')\n",
708
+ " baseline_def = quick_defender_eval()\n",
709
+ " fraud_agent.apply() # restore trained fraud\n",
710
+ " adv_def = quick_defender_eval()\n",
711
+ " gap = float(baseline_def - adv_def)\n",
712
+ " exploitability_log.append(gap)\n",
713
+ " print(f' exploitability gap: baseline_def={baseline_def:.3f} vs adv_def={adv_def:.3f} -> gap={gap:.3f}')\n",
714
+ "\n",
715
+ "print('\\nCo-training finished.')\n",
716
+ "print(' defender_round_rewards:', defender_round_rewards)\n",
717
+ "print(' fraud_round_fitness: ', fraud_round_fitness)\n",
718
+ "print(' exploitability_log: ', exploitability_log)\n",
719
+ "\n",
720
+ "# Aliases for downstream cells\n",
721
+ "loss_history = loss_history_all\n",
722
+ "reward_log = reward_log_all"
723
+ ]
724
+ },
725
+ {
726
+ "cell_type": "markdown",
727
+ "metadata": {},
728
+ "source": [
729
+ "## 9. Trained-policy evaluation"
730
+ ]
731
+ },
732
+ {
733
+ "cell_type": "code",
734
+ "execution_count": null,
735
+ "id": "ee1930bb",
736
+ "metadata": {},
737
+ "outputs": [],
738
+ "source": [
739
+ "import torch\n",
740
+ "\n",
741
+ "FastLanguageModel.for_inference(model)\n",
742
+ "device = next(model.parameters()).device\n",
743
+ "\n",
744
+ "def trained_policy(obs):\n",
745
+ " prompt = make_prompt(obs)\n",
746
+ " inputs = tokenizer(prompt, return_tensors='pt', truncation=True, max_length=1024).to(device)\n",
747
+ " with torch.no_grad():\n",
748
+ " out = model.generate(\n",
749
+ " **inputs,\n",
750
+ " max_new_tokens=64,\n",
751
+ " do_sample=False,\n",
752
+ " pad_token_id=tokenizer.pad_token_id,\n",
753
+ " )\n",
754
+ " text = tokenizer.decode(out[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)\n",
755
+ " return parse_action(text)\n",
756
+ "\n",
757
+ "# Evaluate against the FINAL (hardest) co-evolved fraud agent so the\n",
758
+ "# \"trained\" number reflects performance under the toughest pressure seen.\n",
759
+ "fraud_agent.apply()\n",
760
+ "trained_eval = eval_policy(trained_policy)\n",
761
+ "print('Trained policy mean reward (vs co-evolved fraud):', trained_eval['mean_reward'])\n",
762
+ "print('Trained per-bucket:', trained_eval['bucket_means'])\n",
763
+ "\n",
764
+ "# Also evaluate against neutral fraud for comparability with the baselines.\n",
765
+ "env_configure_adversary(intensity=1.0, noise_boost=0.05, pattern_rate=0.2, strategy='mixed')\n",
766
+ "trained_eval_neutral = eval_policy(trained_policy)\n",
767
+ "print('Trained policy mean reward (vs neutral fraud):', trained_eval_neutral['mean_reward'])\n",
768
+ "fraud_agent.apply() # restore co-evolved fraud for downstream plots"
769
+ ]
770
+ },
771
+ {
772
+ "cell_type": "markdown",
773
+ "metadata": {},
774
+ "source": [
775
+ "## 10. Plots and saved artifacts"
776
+ ]
777
+ },
778
+ {
779
+ "cell_type": "code",
780
+ "execution_count": null,
781
+ "id": "060798c6",
782
+ "metadata": {},
783
+ "outputs": [],
784
+ "source": [
785
+ "import matplotlib.pyplot as plt\n",
786
+ "\n",
787
+ "# 1. GRPO training reward (across all rounds)\n",
788
+ "if reward_log:\n",
789
+ " plt.figure(figsize=(8,4))\n",
790
+ " plt.plot(reward_log, label='GRPO mean reward per logging step')\n",
791
+ " plt.xlabel('Logging step (across all defender rounds)')\n",
792
+ " plt.ylabel('Reward')\n",
793
+ " plt.title('GRPO defender training reward')\n",
794
+ " plt.legend()\n",
795
+ " plt.tight_layout()\n",
796
+ " plt.savefig('artifacts/grpo_reward_curve.png', dpi=140)\n",
797
+ " plt.show()\n",
798
+ "\n",
799
+ "# 2. GRPO training loss\n",
800
+ "if loss_history:\n",
801
+ " plt.figure(figsize=(8,4))\n",
802
+ " plt.plot(loss_history, label='GRPO training loss')\n",
803
+ " plt.xlabel('Logging step')\n",
804
+ " plt.ylabel('Loss')\n",
805
+ " plt.title('TRL GRPO training loss (Unsloth)')\n",
806
+ " plt.legend()\n",
807
+ " plt.tight_layout()\n",
808
+ " plt.savefig('artifacts/grpo_training_loss.png', dpi=140)\n",
809
+ " plt.show()\n",
810
+ "\n",
811
+ "# 3. Co-evolution: defender reward vs fraud fitness per round\n",
812
+ "rounds_x = np.arange(1, len(defender_round_rewards) + 1)\n",
813
+ "fig, ax1 = plt.subplots(figsize=(8,4))\n",
814
+ "ax1.plot(rounds_x, defender_round_rewards, 'o-', color='#4a8', label='Defender mean reward')\n",
815
+ "ax1.set_xlabel('Round')\n",
816
+ "ax1.set_ylabel('Defender reward', color='#4a8')\n",
817
+ "if fraud_round_fitness:\n",
818
+ " ax2 = ax1.twinx()\n",
819
+ " ax2.plot(np.arange(1, len(fraud_round_fitness) + 1), fraud_round_fitness, 's--', color='#c44', label='Fraud fitness')\n",
820
+ " ax2.set_ylabel('Fraud fitness (1 - defender reward)', color='#c44')\n",
821
+ "plt.title('Co-evolution: Defender vs Fraud agent per round')\n",
822
+ "fig.tight_layout()\n",
823
+ "plt.savefig('artifacts/coevolution_curves.png', dpi=140)\n",
824
+ "plt.show()\n",
825
+ "\n",
826
+ "# 4. Exploitability gap\n",
827
+ "if exploitability_log:\n",
828
+ " plt.figure(figsize=(8,4))\n",
829
+ " plt.plot(np.arange(1, len(exploitability_log) + 1), exploitability_log, 'd-', color='#a48')\n",
830
+ " plt.axhline(0, color='#888', lw=0.5)\n",
831
+ " plt.xlabel('Round')\n",
832
+ " plt.ylabel('Exploitability gap')\n",
833
+ " plt.title('Exploitability gap = baseline_def_reward − trained_fraud_def_reward')\n",
834
+ " plt.tight_layout()\n",
835
+ " plt.savefig('artifacts/exploitability_gap.png', dpi=140)\n",
836
+ " plt.show()\n",
837
+ "\n",
838
+ "# 5. Fraud parameter trajectories\n",
839
+ "if fraud_theta_history:\n",
840
+ " keys = list(fraud_theta_history[0].keys())\n",
841
+ " plt.figure(figsize=(8,4))\n",
842
+ " xs = np.arange(len(fraud_theta_history))\n",
843
+ " for k in keys:\n",
844
+ " plt.plot(xs, [t[k] for t in fraud_theta_history], 'o-', label=k)\n",
845
+ " plt.xlabel('Co-evolution snapshot')\n",
846
+ " plt.ylabel('Parameter value')\n",
847
+ " plt.title('Fraud agent parameter evolution (ES)')\n",
848
+ " plt.legend()\n",
849
+ " plt.tight_layout()\n",
850
+ " plt.savefig('artifacts/fraud_theta_trajectory.png', dpi=140)\n",
851
+ " plt.show()\n",
852
+ "\n",
853
+ "# 6. Before vs After\n",
854
+ "labels = ['Random', 'Heuristic', 'Trained LLM']\n",
855
+ "values = [baseline_random['mean_reward'], baseline_heuristic['mean_reward'], trained_eval['mean_reward']]\n",
856
+ "plt.figure(figsize=(7,4))\n",
857
+ "bars = plt.bar(labels, values, color=['#bbb','#88c','#4a8'])\n",
858
+ "for b, v in zip(bars, values):\n",
859
+ " plt.text(b.get_x()+b.get_width()/2, v+0.01, f'{v:.3f}', ha='center')\n",
860
+ "plt.ylabel('Mean reward (frozen holdout)')\n",
861
+ "plt.title('Before vs After Training (GRPO + co-evolving fraud)')\n",
862
+ "plt.tight_layout()\n",
863
+ "plt.savefig('artifacts/before_after_rewards.png', dpi=140)\n",
864
+ "plt.show()\n",
865
+ "\n",
866
+ "# 7. Per risk-bucket\n",
867
+ "buckets = ['low', 'medium', 'high']\n",
868
+ "rand_b = [baseline_random['bucket_means'][b] for b in buckets]\n",
869
+ "heur_b = [baseline_heuristic['bucket_means'][b] for b in buckets]\n",
870
+ "trnd_b = [trained_eval['bucket_means'][b] for b in buckets]\n",
871
+ "x = np.arange(len(buckets))\n",
872
+ "w = 0.27\n",
873
+ "plt.figure(figsize=(8,4))\n",
874
+ "plt.bar(x - w, rand_b, width=w, label='Random', color='#bbb')\n",
875
+ "plt.bar(x, heur_b, width=w, label='Heuristic', color='#88c')\n",
876
+ "plt.bar(x + w, trnd_b, width=w, label='Trained LLM', color='#4a8')\n",
877
+ "plt.xticks(x, [b.title()+' Risk' for b in buckets])\n",
878
+ "plt.ylabel('Mean reward')\n",
879
+ "plt.title('Per Risk-Bucket Reward (frozen holdout)')\n",
880
+ "plt.legend()\n",
881
+ "plt.tight_layout()\n",
882
+ "plt.savefig('artifacts/per_bucket_rewards.png', dpi=140)\n",
883
+ "plt.show()\n",
884
+ "\n",
885
+ "summary = {\n",
886
+ " 'env_url': ENV_URL,\n",
887
+ " 'model_id': MODEL_ID,\n",
888
+ " 'quick_mode': QUICK_MODE,\n",
889
+ " 'prompts_used': len(prompts),\n",
890
+ " 'grpo_num_generations': GRPO_NUM_GENERATIONS,\n",
891
+ " 'rollout_steps_per_reward': ROLLOUT_STEPS_PER_REWARD,\n",
892
+ " 'n_rounds': N_ROUNDS,\n",
893
+ " 'grpo_steps_per_round': GRPO_STEPS_PER_ROUND,\n",
894
+ " 'es_steps_per_round': ES_STEPS_PER_ROUND,\n",
895
+ " 'es_population': ES_POPULATION,\n",
896
+ " 'baseline_random_mean_reward': baseline_random['mean_reward'],\n",
897
+ " 'baseline_heuristic_mean_reward': baseline_heuristic['mean_reward'],\n",
898
+ " 'trained_mean_reward': trained_eval['mean_reward'],\n",
899
+ " 'reward_gain_vs_random': trained_eval['mean_reward'] - baseline_random['mean_reward'],\n",
900
+ " 'reward_gain_vs_heuristic': trained_eval['mean_reward'] - baseline_heuristic['mean_reward'],\n",
901
+ " 'per_bucket': {\n",
902
+ " 'random': baseline_random['bucket_means'],\n",
903
+ " 'heuristic': baseline_heuristic['bucket_means'],\n",
904
+ " 'trained': trained_eval['bucket_means'],\n",
905
+ " },\n",
906
+ " 'defender_round_rewards': defender_round_rewards,\n",
907
+ " 'fraud_round_fitness': fraud_round_fitness,\n",
908
+ " 'exploitability_log': exploitability_log,\n",
909
+ " 'fraud_theta_history': fraud_theta_history,\n",
910
+ " 'final_fraud_theta': fraud_agent.theta,\n",
911
+ " 'grpo_reward_curve': reward_log,\n",
912
+ " 'grpo_loss_history': loss_history,\n",
913
+ " 'eval_per_episode': {\n",
914
+ " 'random': baseline_random['per_episode_mean'],\n",
915
+ " 'heuristic': baseline_heuristic['per_episode_mean'],\n",
916
+ " 'trained': trained_eval['per_episode_mean'],\n",
917
+ " },\n",
918
+ "}\n",
919
+ "with open('artifacts/run_summary.json', 'w', encoding='utf-8') as f:\n",
920
+ " json.dump(summary, f, indent=2)\n",
921
+ "print(json.dumps({k:v for k,v in summary.items() if k not in ('grpo_reward_curve','grpo_loss_history')}, indent=2))"
922
+ ]
923
+ },
924
+ {
925
+ "cell_type": "markdown",
926
+ "metadata": {},
927
+ "source": [
928
+ "## 11. (Optional) Upload artifacts"
929
+ ]
930
+ },
931
+ {
932
+ "cell_type": "code",
933
+ "execution_count": null,
934
+ "metadata": {},
935
+ "outputs": [],
936
+ "source": [
937
+ "# !huggingface-cli upload <your-hf-repo> artifacts artifacts --repo-type dataset"
938
+ ]
939
+ }
940
+ ],
941
+ "metadata": {
942
+ "kernelspec": {
943
+ "display_name": "Python 3",
944
+ "language": "python",
945
+ "name": "python3"
946
+ },
947
+ "language_info": {
948
+ "name": "python"
949
+ }
950
+ },
951
+ "nbformat": 4,
952
+ "nbformat_minor": 5
953
+ }
scripts/train_theme4_grpo.py CHANGED
@@ -11,7 +11,9 @@ It is intentionally lightweight so teams can run it in Colab with TRL/Unsloth.
11
 
12
  from __future__ import annotations
13
 
 
14
  import json
 
15
  import random
16
  from dataclasses import dataclass
17
  from typing import Any
@@ -19,9 +21,11 @@ from typing import Any
19
  import requests
20
 
21
 
22
- ENV_URL = "http://localhost:7860"
23
- MAX_STEPS = 200
24
- GROUP_SIZE = 8
 
 
25
 
26
 
27
  @dataclass
@@ -69,8 +73,14 @@ def _reset(difficulty: int = 2) -> dict[str, Any]:
69
  return payload.get("observation", payload)
70
 
71
 
72
- def collect_group_relative_pairs(max_steps: int = MAX_STEPS, group_size: int = GROUP_SIZE) -> list[RolloutExample]:
73
- obs = _reset(difficulty=2)
 
 
 
 
 
 
74
  dataset: list[RolloutExample] = []
75
  actions_pool = _action_candidates()
76
 
@@ -111,7 +121,7 @@ def collect_group_relative_pairs(max_steps: int = MAX_STEPS, group_size: int = G
111
  step_payload = _step(best_action)
112
  obs = step_payload.get("observation", step_payload)
113
  if bool(obs.get("done", False)):
114
- obs = _reset(difficulty=2)
115
 
116
  return dataset
117
 
@@ -134,6 +144,21 @@ def export_jsonl(dataset: list[RolloutExample], output_path: str) -> None:
134
 
135
 
136
  if __name__ == "__main__":
137
- data = collect_group_relative_pairs()
138
- export_jsonl(data, "theme4_grpo_pairs.jsonl")
139
- print(f"Collected {len(data)} preference pairs into theme4_grpo_pairs.jsonl")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  from __future__ import annotations
13
 
14
+ import argparse
15
  import json
16
+ import os
17
  import random
18
  from dataclasses import dataclass
19
  from typing import Any
 
21
  import requests
22
 
23
 
24
+ ENV_URL = os.getenv("ENV_URL", "http://localhost:7860").rstrip("/")
25
+ MAX_STEPS = int(os.getenv("MAX_STEPS", "200"))
26
+ GROUP_SIZE = int(os.getenv("GROUP_SIZE", "8"))
27
+ DIFFICULTY = int(os.getenv("DIFFICULTY", "2"))
28
+ RANDOM_SEED = int(os.getenv("SEED", "42"))
29
 
30
 
31
  @dataclass
 
73
  return payload.get("observation", payload)
74
 
75
 
76
+ def collect_group_relative_pairs(
77
+ max_steps: int = MAX_STEPS,
78
+ group_size: int = GROUP_SIZE,
79
+ difficulty: int = DIFFICULTY,
80
+ seed: int = RANDOM_SEED,
81
+ ) -> list[RolloutExample]:
82
+ random.seed(seed)
83
+ obs = _reset(difficulty=difficulty)
84
  dataset: list[RolloutExample] = []
85
  actions_pool = _action_candidates()
86
 
 
121
  step_payload = _step(best_action)
122
  obs = step_payload.get("observation", step_payload)
123
  if bool(obs.get("done", False)):
124
+ obs = _reset(difficulty=difficulty)
125
 
126
  return dataset
127
 
 
144
 
145
 
146
  if __name__ == "__main__":
147
+ parser = argparse.ArgumentParser(description="Collect group-relative preference pairs from SmartPayEnv.")
148
+ parser.add_argument("--env-url", default=ENV_URL, help="SmartPayEnv server URL")
149
+ parser.add_argument("--max-steps", type=int, default=MAX_STEPS, help="Number of rollout steps")
150
+ parser.add_argument("--group-size", type=int, default=GROUP_SIZE, help="Actions sampled per step")
151
+ parser.add_argument("--difficulty", type=int, default=DIFFICULTY, help="Environment difficulty 0/1/2")
152
+ parser.add_argument("--seed", type=int, default=RANDOM_SEED, help="Random seed")
153
+ parser.add_argument("--output", default="theme4_grpo_pairs.jsonl", help="Output JSONL path")
154
+ args = parser.parse_args()
155
+
156
+ ENV_URL = args.env_url.rstrip("/")
157
+ data = collect_group_relative_pairs(
158
+ max_steps=args.max_steps,
159
+ group_size=args.group_size,
160
+ difficulty=args.difficulty,
161
+ seed=args.seed,
162
+ )
163
+ export_jsonl(data, args.output)
164
+ print(f"Collected {len(data)} preference pairs into {args.output}")
server/SmartPayEnv_environment.py CHANGED
@@ -142,6 +142,15 @@ class SmartpayenvEnvironment(Environment):
142
  self._pattern_queue = deque()
143
  self._meta_curriculum_enabled = True
144
 
 
 
 
 
 
 
 
 
 
145
  def _init_gateways(self) -> None:
146
  instability = self._cfg["instability"]
147
  self._gateways = [
@@ -164,7 +173,10 @@ class SmartpayenvEnvironment(Environment):
164
  # Fallback to random if logs fail (shouldn't happen)
165
  return self._generate_fallback_transaction()
166
 
167
- true_risk = float(log_entry["fraud_risk_score"])
 
 
 
168
  self._state.true_fraud_risk = true_risk
169
 
170
  return SmartpayenvObservation(
@@ -192,8 +204,10 @@ class SmartpayenvEnvironment(Environment):
192
  )
193
 
194
  def _get_noisy_risk(self, true_risk: float) -> float:
195
- """Adds Gaussian noise to the true risk score."""
196
- noise = self._rng.normal(0, 0.1)
 
 
197
  return float(np.clip(true_risk + noise, 0.01, 0.99))
198
 
199
  def _generate_fallback_transaction(self) -> SmartpayenvObservation:
@@ -228,12 +242,19 @@ class SmartpayenvEnvironment(Environment):
228
  task_retention_score=0.5,
229
  )
230
 
231
- def reset(self, difficulty: int = 0) -> SmartpayenvObservation:
232
  self._difficulty = int(np.clip(difficulty, 0, 2))
233
  self._cfg = DIFFICULTY_CONFIG[self._difficulty]
 
 
 
 
234
  self._state = State(episode_id=str(uuid4()), step_count=0)
235
- # Random initial cursor for variety, but then sequential within episode
236
- self._state.log_cursor = self._rng.integers(0, 100000)
 
 
 
237
  self._init_gateways()
238
  self.route_grader = RoutingEfficacyGrader()
239
  self.fraud_grader = FraudDetectionGrader()
@@ -248,6 +269,31 @@ class SmartpayenvEnvironment(Environment):
248
  self._state.anti_gaming_alerts = 0
249
  return self.current_obs
250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  def _curriculum_multiplier(self) -> float:
252
  return 1.0 + (0.15 * self._state.curriculum_level)
253
 
@@ -313,10 +359,15 @@ class SmartpayenvEnvironment(Environment):
313
  }
314
  self._state.health_lag_buffer.append(current_health)
315
 
316
- if self._state.step_count % 10 == 0 and self._rng.random() < 0.2:
317
- # Inject a "Fraud Surge" pattern from logs
318
- surge_logs = self._log_loader.get_pattern("fraud_surge", count=5)
319
- self._pattern_queue.extend(surge_logs)
 
 
 
 
 
320
 
321
  # Curriculum-driven stress events (self-improvement pressure).
322
  if self._rng.random() < (0.01 * self._curriculum_multiplier()):
 
142
  self._pattern_queue = deque()
143
  self._meta_curriculum_enabled = True
144
 
145
+ # ── Learnable adversary (theme-4 co-evolution) ─────────────────
146
+ # Set externally via `configure_adversary(...)` and consumed by
147
+ # `_get_noisy_risk` / `step` to control how aggressive the fraud
148
+ # generator behaves. Defaults are neutral (no extra pressure).
149
+ self._adv_intensity = 1.0 # multiplier on fraud rate (1.0 = baseline)
150
+ self._adv_noise_boost = 0.0 # extra std on observed fraud risk
151
+ self._adv_pattern_rate = 0.2 # base prob of injecting a fraud-surge pattern
152
+ self._adv_strategy = "mixed" # "mixed" | "fraud_surge" | "stealth_fraud" | "velocity_attack"
153
+
154
  def _init_gateways(self) -> None:
155
  instability = self._cfg["instability"]
156
  self._gateways = [
 
173
  # Fallback to random if logs fail (shouldn't happen)
174
  return self._generate_fallback_transaction()
175
 
176
+ # Adversary intensifier: scale the underlying fraud risk so a learned
177
+ # fraud agent can sharpen attacks against the defender LLM.
178
+ true_risk = float(log_entry["fraud_risk_score"]) * float(self._adv_intensity)
179
+ true_risk = float(np.clip(true_risk, 0.0, 1.0))
180
  self._state.true_fraud_risk = true_risk
181
 
182
  return SmartpayenvObservation(
 
204
  )
205
 
206
  def _get_noisy_risk(self, true_risk: float) -> float:
207
+ """Adds Gaussian noise to the true risk score.
208
+ Adversary policy can boost noise to make detection harder (stealth)."""
209
+ std = 0.1 + max(0.0, float(self._adv_noise_boost))
210
+ noise = self._rng.normal(0, std)
211
  return float(np.clip(true_risk + noise, 0.01, 0.99))
212
 
213
  def _generate_fallback_transaction(self) -> SmartpayenvObservation:
 
242
  task_retention_score=0.5,
243
  )
244
 
245
+ def reset(self, difficulty: int = 0, seed: int | None = None) -> SmartpayenvObservation:
246
  self._difficulty = int(np.clip(difficulty, 0, 2))
247
  self._cfg = DIFFICULTY_CONFIG[self._difficulty]
248
+ # Optional deterministic seeding so a GRPO group can share the same
249
+ # starting trajectory across all candidate completions (clean signal).
250
+ if seed is not None:
251
+ self._rng = np.random.default_rng(int(seed))
252
  self._state = State(episode_id=str(uuid4()), step_count=0)
253
+ # Cursor is also seed-determined when a seed is provided.
254
+ if seed is not None:
255
+ self._state.log_cursor = int(seed) % 100000
256
+ else:
257
+ self._state.log_cursor = int(self._rng.integers(0, 100000))
258
  self._init_gateways()
259
  self.route_grader = RoutingEfficacyGrader()
260
  self.fraud_grader = FraudDetectionGrader()
 
269
  self._state.anti_gaming_alerts = 0
270
  return self.current_obs
271
 
272
+ # ── Adversary configuration (theme-4 co-evolution) ─────────────────
273
+ def configure_adversary(
274
+ self,
275
+ intensity: float | None = None,
276
+ noise_boost: float | None = None,
277
+ pattern_rate: float | None = None,
278
+ strategy: str | None = None,
279
+ ) -> dict:
280
+ """Set the parametric fraud agent's behaviour. All values are clipped
281
+ to safe ranges. Returns the active adversary config."""
282
+ if intensity is not None:
283
+ self._adv_intensity = float(np.clip(intensity, 0.5, 2.5))
284
+ if noise_boost is not None:
285
+ self._adv_noise_boost = float(np.clip(noise_boost, 0.0, 0.6))
286
+ if pattern_rate is not None:
287
+ self._adv_pattern_rate = float(np.clip(pattern_rate, 0.0, 0.9))
288
+ if strategy is not None and strategy in {"mixed", "fraud_surge", "stealth_fraud", "velocity_attack"}:
289
+ self._adv_strategy = strategy
290
+ return {
291
+ "intensity": self._adv_intensity,
292
+ "noise_boost": self._adv_noise_boost,
293
+ "pattern_rate": self._adv_pattern_rate,
294
+ "strategy": self._adv_strategy,
295
+ }
296
+
297
  def _curriculum_multiplier(self) -> float:
298
  return 1.0 + (0.15 * self._state.curriculum_level)
299
 
 
359
  }
360
  self._state.health_lag_buffer.append(current_health)
361
 
362
+ if self._state.step_count % 10 == 0 and self._rng.random() < self._adv_pattern_rate:
363
+ # Adversary-controlled attack injection. The fraud agent picks
364
+ # the pattern type; "mixed" rotates among them.
365
+ if self._adv_strategy == "mixed":
366
+ pat = self._rng.choice(["fraud_surge", "stealth_fraud", "velocity_attack"])
367
+ else:
368
+ pat = self._adv_strategy
369
+ atk_logs = self._log_loader.get_pattern(str(pat), count=5)
370
+ self._pattern_queue.extend(atk_logs)
371
 
372
  # Curriculum-driven stress events (self-improvement pressure).
373
  if self._rng.random() < (0.01 * self._curriculum_multiplier()):
server/app.py CHANGED
@@ -64,6 +64,42 @@ async def simulate(action: SmartpayenvAction):
64
  return app.env.simulate(action)
65
 
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  def main():
68
  """
69
  Entry point for direct execution via uv run or python -m.
 
64
  return app.env.simulate(action)
65
 
66
 
67
+ # ── Theme-4 co-evolution endpoints ────────────────────────────────────
68
+ from typing import Optional
69
+ from pydantic import BaseModel
70
+
71
+
72
+ class AdversaryConfig(BaseModel):
73
+ """Parametric fraud-agent policy. Any field may be omitted."""
74
+ intensity: Optional[float] = None
75
+ noise_boost: Optional[float] = None
76
+ pattern_rate: Optional[float] = None
77
+ strategy: Optional[str] = None # "mixed" | "fraud_surge" | "stealth_fraud" | "velocity_attack"
78
+
79
+
80
+ class SeededReset(BaseModel):
81
+ difficulty: int = 0
82
+ seed: Optional[int] = None
83
+
84
+
85
+ @app.post("/configure_adversary")
86
+ async def configure_adversary(cfg: AdversaryConfig):
87
+ """Set the learnable fraud agent's behaviour. Returns the active config."""
88
+ return app.env.configure_adversary(
89
+ intensity=cfg.intensity,
90
+ noise_boost=cfg.noise_boost,
91
+ pattern_rate=cfg.pattern_rate,
92
+ strategy=cfg.strategy,
93
+ )
94
+
95
+
96
+ @app.post("/reset_seeded", response_model=SmartpayenvObservation)
97
+ async def reset_seeded(req: SeededReset):
98
+ """Deterministic reset: same `seed` => same starting trajectory.
99
+ Useful for GRPO so all completions in a group share the same state."""
100
+ return app.env.reset(difficulty=int(req.difficulty), seed=req.seed)
101
+
102
+
103
  def main():
104
  """
105
  Entry point for direct execution via uv run or python -m.