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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AP Commander β GRPO Training Script
|
| 3 |
+
Tracks: overall reward, per-component rewards, decision distribution,
|
| 4 |
+
format compliance, env errors, sample generations, reward curve.
|
| 5 |
+
"""
|
| 6 |
+
import os, json, re, random, time, datetime, collections
|
| 7 |
+
import requests
|
| 8 |
+
import matplotlib
|
| 9 |
+
matplotlib.use('Agg')
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
ENV_URL = 'https://pathikreet-ap-clerk-env.hf.space'
|
| 14 |
+
MODEL_NAME = os.environ.get('MODEL_NAME', 'Qwen/Qwen2.5-7B-Instruct')
|
| 15 |
+
NUM_EPOCHS = int(os.environ.get('NUM_EPOCHS', '3'))
|
| 16 |
+
NUM_GENERATIONS = int(os.environ.get('NUM_GENERATIONS', '8'))
|
| 17 |
+
LOG_SAMPLES_EVERY = 20 # print a sample generation every N reward calls
|
| 18 |
+
|
| 19 |
+
SYSTEM_PROMPT = """You are an AI Accounts Payable Clerk. Review the invoice, PO, and GRN, then output ONLY valid JSON:
|
| 20 |
+
{"decision": "APPROVE_FULL"|"APPROVE_PARTIAL"|"REJECT"|"ESCALATE"|"QUERY_VENDOR",
|
| 21 |
+
"approved_amount": <float>,
|
| 22 |
+
"reason_code": "MATCH_CONFIRMED"|"QUANTITY_MISMATCH"|"PRICE_DISCREPANCY"|"POLICY_VIOLATION"|"NO_PO_FOUND"|"DUPLICATE_INVOICE"|"VENDOR_MISMATCH"|"TAX_DISCREPANCY"|"PENDING_CLARIFICATION"|"MANAGER_REVIEW",
|
| 23 |
+
"explanation": "<cite specific $ amounts>"}"""
|
| 24 |
+
|
| 25 |
+
TRAIN_TASKS = [
|
| 26 |
+
'easy_perfect_match', 'easy_no_po_found',
|
| 27 |
+
'medium_quantity_shortfall', 'medium_price_discrepancy',
|
| 28 |
+
'medium_split_delivery', 'medium_vendor_mismatch',
|
| 29 |
+
'hard_policy_violation', 'hard_duplicate_invoice',
|
| 30 |
+
'hard_partial_po_match', 'hard_tax_discrepancy',
|
| 31 |
+
'long_invoice_dispute', 'long_policy_migration',
|
| 32 |
+
'long_batch_reconciliation', 'long_manager_chain',
|
| 33 |
+
'long_fraud_investigation', 'long_audit_trail',
|
| 34 |
+
'long_multi_vendor_split',
|
| 35 |
+
]
|
| 36 |
+
EVAL_TASKS = [
|
| 37 |
+
'easy_perfect_match', 'easy_no_po_found',
|
| 38 |
+
'medium_quantity_shortfall', 'medium_price_discrepancy',
|
| 39 |
+
'medium_split_delivery', 'medium_vendor_mismatch',
|
| 40 |
+
'hard_policy_violation', 'hard_duplicate_invoice',
|
| 41 |
+
'hard_partial_po_match', 'hard_tax_discrepancy',
|
| 42 |
+
'long_invoice_dispute', 'long_policy_migration',
|
| 43 |
+
'long_batch_reconciliation', 'long_manager_chain',
|
| 44 |
+
'long_fraud_investigation', 'long_audit_trail',
|
| 45 |
+
'long_multi_vendor_split',
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
VALID_DECISIONS = {'APPROVE_FULL','APPROVE_PARTIAL','REJECT','ESCALATE','QUERY_VENDOR','HOLD'}
|
| 49 |
+
VALID_REASON_CODES = {'MATCH_CONFIRMED','QUANTITY_MISMATCH','PRICE_DISCREPANCY','POLICY_VIOLATION',
|
| 50 |
+
'NO_PO_FOUND','DUPLICATE_INVOICE','VENDOR_MISMATCH','TAX_DISCREPANCY',
|
| 51 |
+
'PENDING_CLARIFICATION','MANAGER_REVIEW'}
|
| 52 |
+
|
| 53 |
+
# Task difficulty map used by curriculum sampler
|
| 54 |
+
_TASK_DIFFICULTY = {
|
| 55 |
+
'easy_perfect_match': 'easy', 'easy_no_po_found': 'easy',
|
| 56 |
+
'medium_quantity_shortfall': 'medium', 'medium_price_discrepancy': 'medium',
|
| 57 |
+
'medium_split_delivery': 'medium', 'medium_vendor_mismatch': 'medium',
|
| 58 |
+
'hard_policy_violation': 'hard', 'hard_duplicate_invoice': 'hard',
|
| 59 |
+
'hard_partial_po_match': 'hard', 'hard_tax_discrepancy': 'hard',
|
| 60 |
+
'long_invoice_dispute': 'long', 'long_policy_migration': 'long',
|
| 61 |
+
'long_batch_reconciliation': 'long', 'long_manager_chain': 'long',
|
| 62 |
+
'long_fraud_investigation': 'long', 'long_audit_trail': 'long',
|
| 63 |
+
'long_multi_vendor_split': 'long',
|
| 64 |
+
}
|
| 65 |
+
_DIFFICULTY_ORDER = ['easy', 'medium', 'hard', 'long']
|
| 66 |
+
_UNLOCK_THRESHOLDS = {'easy': 0.70, 'medium': 0.65, 'hard': 0.60}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ββ Curriculum sampler ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 70 |
+
|
| 71 |
+
class CurriculumSampler:
|
| 72 |
+
"""
|
| 73 |
+
Tracks per-difficulty running mean and unlocks harder tasks once thresholds
|
| 74 |
+
are met. Used both for building the training dataset and for gating tasks in
|
| 75 |
+
the reward function so early training stays on easier tasks.
|
| 76 |
+
"""
|
| 77 |
+
def __init__(self):
|
| 78 |
+
self._rewards: dict = collections.defaultdict(list) # task_id β [rewards]
|
| 79 |
+
self.unlocked: set = {'easy'}
|
| 80 |
+
|
| 81 |
+
def record(self, task_id: str, reward: float):
|
| 82 |
+
self._rewards[task_id].append(reward)
|
| 83 |
+
self._try_unlock()
|
| 84 |
+
|
| 85 |
+
def mean_for_difficulty(self, diff: str) -> float:
|
| 86 |
+
vals = []
|
| 87 |
+
for tid, d in _TASK_DIFFICULTY.items():
|
| 88 |
+
if d == diff:
|
| 89 |
+
vals.extend(self._rewards.get(tid, []))
|
| 90 |
+
return sum(vals) / len(vals) if vals else 0.0
|
| 91 |
+
|
| 92 |
+
def _try_unlock(self):
|
| 93 |
+
for i, diff in enumerate(_DIFFICULTY_ORDER[:-1]):
|
| 94 |
+
if diff in self.unlocked:
|
| 95 |
+
m = self.mean_for_difficulty(diff)
|
| 96 |
+
if m >= _UNLOCK_THRESHOLDS.get(diff, 0.70):
|
| 97 |
+
nxt = _DIFFICULTY_ORDER[i + 1]
|
| 98 |
+
if nxt not in self.unlocked:
|
| 99 |
+
self.unlocked.add(nxt)
|
| 100 |
+
print(f'\n[CURRICULUM] Unlocked {nxt}! mean({diff})={m:.3f} '
|
| 101 |
+
f'>= threshold {_UNLOCK_THRESHOLDS[diff]}')
|
| 102 |
+
|
| 103 |
+
def gate_task(self, task_id: str) -> str:
|
| 104 |
+
"""If task's difficulty is not yet unlocked, return easiest unlocked task."""
|
| 105 |
+
if _TASK_DIFFICULTY.get(task_id, 'easy') in self.unlocked:
|
| 106 |
+
return task_id
|
| 107 |
+
easiest = [t for t, d in _TASK_DIFFICULTY.items() if d == 'easy']
|
| 108 |
+
return random.choice(easiest)
|
| 109 |
+
|
| 110 |
+
def build_dataset_tasks(self) -> list:
|
| 111 |
+
"""
|
| 112 |
+
Curriculum-weighted task list:
|
| 113 |
+
easy β 10 seeds (always included)
|
| 114 |
+
medium β 5 seeds (if unlocked)
|
| 115 |
+
hard β 2 seeds (if unlocked)
|
| 116 |
+
long β 2 seeds (if unlocked)
|
| 117 |
+
Returns list of (task_id, seed) pairs.
|
| 118 |
+
"""
|
| 119 |
+
rows = []
|
| 120 |
+
seeds_per_diff = {'easy': 10, 'medium': 5, 'hard': 2, 'long': 2}
|
| 121 |
+
for task_id, diff in _TASK_DIFFICULTY.items():
|
| 122 |
+
if diff in self.unlocked:
|
| 123 |
+
n = seeds_per_diff[diff]
|
| 124 |
+
rows.extend([(task_id, s) for s in range(1, n + 1)])
|
| 125 |
+
return rows
|
| 126 |
+
|
| 127 |
+
def status_line(self) -> str:
|
| 128 |
+
parts = []
|
| 129 |
+
for d in _DIFFICULTY_ORDER:
|
| 130 |
+
m = self.mean_for_difficulty(d)
|
| 131 |
+
unlk = 'β' if d in self.unlocked else 'β'
|
| 132 |
+
parts.append(f'{d}={m:.2f}{unlk}')
|
| 133 |
+
return ' | '.join(parts)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
CURRICULUM = CurriculumSampler()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# ββ Per-step greedy follow-up policy βββββββββββββββββββββββββββββββββββββββββββ
|
| 140 |
+
|
| 141 |
+
def _greedy_followup(obs_dict: dict) -> dict:
|
| 142 |
+
"""
|
| 143 |
+
Scripted policy for intermediate follow-up steps (used in multi-step rollouts).
|
| 144 |
+
Reads context_notes added by the environment after ESCALATE/QUERY_VENDOR/HOLD
|
| 145 |
+
and picks the most appropriate next terminal action.
|
| 146 |
+
"""
|
| 147 |
+
notes = ' '.join(obs_dict.get('context_notes', [])).lower()
|
| 148 |
+
total = abs(float(obs_dict.get('invoice', {}).get('invoice_total', 0) or 0))
|
| 149 |
+
|
| 150 |
+
# Manager / VP approved β APPROVE_FULL
|
| 151 |
+
if any(k in notes for k in ('manager approved', 'vp approved', 'cfo approved',
|
| 152 |
+
'pre-approved', 'pre-approv', 'approved by')):
|
| 153 |
+
return {'decision': 'APPROVE_FULL', 'approved_amount': total,
|
| 154 |
+
'reason_code': 'MATCH_CONFIRMED',
|
| 155 |
+
'explanation': f'Approval confirmed via escalation chain. Approving ${total:.2f}.'}
|
| 156 |
+
|
| 157 |
+
# Compliance cleared β APPROVE_FULL
|
| 158 |
+
if 'compliance' in notes and any(k in notes for k in ('cleared', 'approved', 'pass')):
|
| 159 |
+
return {'decision': 'APPROVE_FULL', 'approved_amount': total,
|
| 160 |
+
'reason_code': 'MATCH_CONFIRMED',
|
| 161 |
+
'explanation': f'Compliance review cleared. Approving ${total:.2f}.'}
|
| 162 |
+
|
| 163 |
+
# Fraudulent / duplicate / deny β REJECT
|
| 164 |
+
if any(k in notes for k in ('fraudulent', 'duplicate', 'already paid', 'deny',
|
| 165 |
+
'invalid', 'false claim')):
|
| 166 |
+
return {'decision': 'REJECT', 'approved_amount': 0.0,
|
| 167 |
+
'reason_code': 'DUPLICATE_INVOICE',
|
| 168 |
+
'explanation': 'Vendor response or audit confirms fraud/duplicate. Rejecting.'}
|
| 169 |
+
|
| 170 |
+
# Compliance flagged / SOX violation β REJECT
|
| 171 |
+
if any(k in notes for k in ('flagged', 'violation', 'sox', 'gdpr', 'non-compliant')):
|
| 172 |
+
return {'decision': 'REJECT', 'approved_amount': 0.0,
|
| 173 |
+
'reason_code': 'POLICY_VIOLATION',
|
| 174 |
+
'explanation': 'Compliance review flagged a violation. Rejecting.'}
|
| 175 |
+
|
| 176 |
+
# Confused vendor / ambiguous β ESCALATE
|
| 177 |
+
if any(k in notes for k in ('confused', 'unclear', 'unable to confirm')):
|
| 178 |
+
return {'decision': 'ESCALATE', 'approved_amount': 0.0,
|
| 179 |
+
'reason_code': 'MANAGER_REVIEW',
|
| 180 |
+
'explanation': 'Vendor response ambiguous. Escalating to manager.'}
|
| 181 |
+
|
| 182 |
+
# Default: safe rejection
|
| 183 |
+
return {'decision': 'REJECT', 'approved_amount': 0.0,
|
| 184 |
+
'reason_code': 'PENDING_CLARIFICATION',
|
| 185 |
+
'explanation': 'Could not resolve after investigation. Rejecting for safety.'}
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# ββ Metrics tracker ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 189 |
+
|
| 190 |
+
class Metrics:
|
| 191 |
+
def __init__(self):
|
| 192 |
+
self.step = 0
|
| 193 |
+
self.reward_history = [] # (step, mean_reward) β overall
|
| 194 |
+
self.diff_reward_hist = collections.defaultdict(list) # diff β [(step, mean)]
|
| 195 |
+
self.format_history = [] # (step, format_rate) β compliance over time
|
| 196 |
+
self.episode_len_hist = [] # all episode lengths (for histogram)
|
| 197 |
+
self.ep_len_by_task = collections.defaultdict(list) # task_id β [lengths]
|
| 198 |
+
self.decision_history = [] # [(step, Counter)] for stacked-bar over time
|
| 199 |
+
self.decision_counts = collections.Counter()
|
| 200 |
+
self.parse_failures = 0
|
| 201 |
+
self.env_errors = 0
|
| 202 |
+
self.format_scores = []
|
| 203 |
+
self.reward_by_task = collections.defaultdict(list)
|
| 204 |
+
self.total_calls = 0
|
| 205 |
+
self._start_time = time.time()
|
| 206 |
+
self._step_decisions = collections.Counter() # decisions in current step batch
|
| 207 |
+
|
| 208 |
+
def log_step(self, rewards, decisions, format_ok_list, task_ids, errors,
|
| 209 |
+
episode_lengths=None):
|
| 210 |
+
self.step += 1
|
| 211 |
+
self.total_calls += len(rewards)
|
| 212 |
+
mean_r = sum(rewards) / len(rewards) if rewards else 0.0
|
| 213 |
+
self.reward_history.append((self.step, mean_r))
|
| 214 |
+
|
| 215 |
+
# Per-difficulty reward history
|
| 216 |
+
diff_rewards: dict = collections.defaultdict(list)
|
| 217 |
+
for tid, r in zip(task_ids, rewards):
|
| 218 |
+
d = _TASK_DIFFICULTY.get(tid, 'easy')
|
| 219 |
+
diff_rewards[d].append(r)
|
| 220 |
+
for d, rs in diff_rewards.items():
|
| 221 |
+
self.diff_reward_hist[d].append((self.step, sum(rs) / len(rs)))
|
| 222 |
+
|
| 223 |
+
for d in decisions:
|
| 224 |
+
self.decision_counts[d] += 1
|
| 225 |
+
self._step_decisions[d] += 1
|
| 226 |
+
# Snapshot decision distribution every step for stacked-bar
|
| 227 |
+
self.decision_history.append((self.step, dict(self._step_decisions)))
|
| 228 |
+
|
| 229 |
+
fmt_ok_count = sum(1 for ok in format_ok_list if ok)
|
| 230 |
+
fmt_rate = fmt_ok_count / len(format_ok_list) if format_ok_list else 0.0
|
| 231 |
+
self.format_history.append((self.step, fmt_rate))
|
| 232 |
+
for ok in format_ok_list:
|
| 233 |
+
self.format_scores.append(1.0 if ok else 0.0)
|
| 234 |
+
|
| 235 |
+
for tid, r in zip(task_ids, rewards):
|
| 236 |
+
self.reward_by_task[tid].append(r)
|
| 237 |
+
|
| 238 |
+
if episode_lengths:
|
| 239 |
+
for tid, ep_len in zip(task_ids, episode_lengths):
|
| 240 |
+
self.episode_len_hist.append(ep_len)
|
| 241 |
+
self.ep_len_by_task[tid].append(ep_len)
|
| 242 |
+
|
| 243 |
+
self.env_errors += errors
|
| 244 |
+
self._flush_live()
|
| 245 |
+
|
| 246 |
+
def _flush_live(self):
|
| 247 |
+
recent = self.reward_history[-20:]
|
| 248 |
+
recent_mean = sum(r for _, r in recent) / len(recent) if recent else 0.0
|
| 249 |
+
fmt_rate = sum(self.format_scores) / len(self.format_scores) if self.format_scores else 0.0
|
| 250 |
+
task_means = {t: round(sum(v)/len(v), 3) for t, v in self.reward_by_task.items()}
|
| 251 |
+
elapsed = (time.time() - self._start_time) / 60
|
| 252 |
+
payload = {
|
| 253 |
+
'step': self.step,
|
| 254 |
+
'total_calls': self.total_calls,
|
| 255 |
+
'recent_mean': round(recent_mean, 4),
|
| 256 |
+
'format_rate': round(fmt_rate, 4),
|
| 257 |
+
'parse_failures': self.parse_failures,
|
| 258 |
+
'env_errors': self.env_errors,
|
| 259 |
+
'elapsed_min': round(elapsed, 1),
|
| 260 |
+
'reward_history': [{'step': s, 'reward': r} for s, r in self.reward_history],
|
| 261 |
+
'decision_counts': dict(self.decision_counts),
|
| 262 |
+
'task_means': task_means,
|
| 263 |
+
}
|
| 264 |
+
try:
|
| 265 |
+
with open('/app/metrics_live.json', 'w') as f:
|
| 266 |
+
json.dump(payload, f)
|
| 267 |
+
except Exception:
|
| 268 |
+
pass
|
| 269 |
+
|
| 270 |
+
def print_summary(self):
|
| 271 |
+
recent = self.reward_history[-10:] if self.reward_history else []
|
| 272 |
+
recent_mean = sum(r for _, r in recent) / len(recent) if recent else 0.0
|
| 273 |
+
fmt_rate = sum(self.format_scores) / len(self.format_scores) if self.format_scores else 0.0
|
| 274 |
+
print(f'\n[METRICS] step={self.step} | recent_reward={recent_mean:.3f} | '
|
| 275 |
+
f'format_ok={fmt_rate:.1%} | parse_fails={self.parse_failures} | '
|
| 276 |
+
f'env_errors={self.env_errors} | total_calls={self.total_calls}')
|
| 277 |
+
top_decisions = self.decision_counts.most_common(5)
|
| 278 |
+
print(f'[METRICS] decisions: {dict(top_decisions)}')
|
| 279 |
+
if self.reward_by_task:
|
| 280 |
+
task_means = {t: round(sum(v)/len(v), 3) for t, v in self.reward_by_task.items()}
|
| 281 |
+
print(f'[METRICS] per_task_reward: {task_means}')
|
| 282 |
+
|
| 283 |
+
def save_all_metrics_figures(self, run_dir: str):
|
| 284 |
+
"""
|
| 285 |
+
Save six standard RL research metric figures to run_dir.
|
| 286 |
+
All figures follow conventions used in academic RL papers:
|
| 287 |
+
- Named axes (xlabel, ylabel)
|
| 288 |
+
- Figure caption as fig.text below the plot
|
| 289 |
+
- Dark GitHub-style theme consistent with project
|
| 290 |
+
- Smoothed curves with raw data visible in background
|
| 291 |
+
"""
|
| 292 |
+
PALETTE = {'easy': '#3fb950', 'medium': '#d29922', 'hard': '#f85149', 'long': '#a371f7'}
|
| 293 |
+
BG = '#0d1117'
|
| 294 |
+
PANEL = '#161b22'
|
| 295 |
+
GRID = '#21262d'
|
| 296 |
+
TEXT = '#e6edf3'
|
| 297 |
+
SUBTEXT = '#8b949e'
|
| 298 |
+
ACCENT = '#58a6ff'
|
| 299 |
+
|
| 300 |
+
def _setup(ax, xlabel='', ylabel='', title=''):
|
| 301 |
+
ax.set_facecolor(PANEL)
|
| 302 |
+
ax.tick_params(colors=TEXT, labelsize=8)
|
| 303 |
+
for sp in ax.spines.values():
|
| 304 |
+
sp.set_color('#30363d')
|
| 305 |
+
ax.spines['top'].set_visible(False)
|
| 306 |
+
ax.spines['right'].set_visible(False)
|
| 307 |
+
ax.yaxis.grid(True, color=GRID, linewidth=0.6, alpha=0.8)
|
| 308 |
+
ax.xaxis.grid(True, color=GRID, linewidth=0.4, alpha=0.4)
|
| 309 |
+
ax.set_axisbelow(True)
|
| 310 |
+
if xlabel: ax.set_xlabel(xlabel, color=SUBTEXT, fontsize=9)
|
| 311 |
+
if ylabel: ax.set_ylabel(ylabel, color=SUBTEXT, fontsize=9)
|
| 312 |
+
if title: ax.set_title(title, color=TEXT, fontsize=10, fontweight='bold', pad=8)
|
| 313 |
+
|
| 314 |
+
def _smooth(values, window=None):
|
| 315 |
+
if len(values) < 3:
|
| 316 |
+
return values
|
| 317 |
+
w = window or max(3, len(values) // 12)
|
| 318 |
+
return np.convolve(values, np.ones(w)/w, mode='valid'), w
|
| 319 |
+
|
| 320 |
+
def _caption(fig, text):
|
| 321 |
+
fig.text(0.5, 0.01, text, ha='center', va='bottom',
|
| 322 |
+
color=SUBTEXT, fontsize=7, style='italic')
|
| 323 |
+
|
| 324 |
+
ts = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
|
| 325 |
+
|
| 326 |
+
# ββ Figure 1: Mean Episode Return (reward curve) ββββββββββββββββββββββ
|
| 327 |
+
if self.reward_history:
|
| 328 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
| 329 |
+
fig.patch.set_facecolor(BG)
|
| 330 |
+
steps = [s for s, _ in self.reward_history]
|
| 331 |
+
rewards = [r for _, r in self.reward_history]
|
| 332 |
+
ax.plot(steps, rewards, color=ACCENT, alpha=0.25, linewidth=1, label='Per-batch mean')
|
| 333 |
+
if len(rewards) >= 5:
|
| 334 |
+
sm, w = _smooth(rewards)
|
| 335 |
+
ax.plot(steps[w-1:], sm, color=ACCENT, linewidth=2, label=f'EMA (w={w})')
|
| 336 |
+
ax.axhline(0.5, color=SUBTEXT, linestyle='--', linewidth=1, alpha=0.5, label='Chance baseline (0.5)')
|
| 337 |
+
recent_mean = sum(rewards[-20:]) / min(20, len(rewards))
|
| 338 |
+
ax.axhline(recent_mean, color='#f78166', linestyle=':', linewidth=1.5,
|
| 339 |
+
label=f'Recent mean = {recent_mean:.3f}')
|
| 340 |
+
ax.set_ylim(0, 1.05)
|
| 341 |
+
ax.legend(fontsize=8, facecolor=PANEL, edgecolor='#30363d', labelcolor=TEXT)
|
| 342 |
+
_setup(ax, xlabel='Training Step (reward function call batch)',
|
| 343 |
+
ylabel='Mean Episode Return [0.01 β 0.99]',
|
| 344 |
+
title='Training Reward Curve β AP Commander GRPO')
|
| 345 |
+
_caption(fig, f'Each step = one GRPO batch. Reward = discounted accumulated score from AP Commander environment. | {ts}')
|
| 346 |
+
plt.tight_layout(rect=[0, 0.04, 1, 1])
|
| 347 |
+
p = os.path.join(run_dir, 'fig1_reward_curve.png')
|
| 348 |
+
plt.savefig(p, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 349 |
+
plt.close()
|
| 350 |
+
print(f'[METRICS] {p}')
|
| 351 |
+
|
| 352 |
+
# ββ Figure 2: Per-Difficulty Learning Curves ββββββββββββββββββββββββββ
|
| 353 |
+
if self.diff_reward_hist:
|
| 354 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
| 355 |
+
fig.patch.set_facecolor(BG)
|
| 356 |
+
for diff in _DIFFICULTY_ORDER:
|
| 357 |
+
hist = self.diff_reward_hist.get(diff, [])
|
| 358 |
+
if not hist:
|
| 359 |
+
continue
|
| 360 |
+
steps_d = [s for s, _ in hist]
|
| 361 |
+
rewards_d = [r for _, r in hist]
|
| 362 |
+
color = PALETTE.get(diff, ACCENT)
|
| 363 |
+
ax.plot(steps_d, rewards_d, color=color, alpha=0.20, linewidth=1)
|
| 364 |
+
if len(rewards_d) >= 5:
|
| 365 |
+
sm, w = _smooth(rewards_d)
|
| 366 |
+
ax.plot(steps_d[w-1:], sm, color=color, linewidth=2.5, label=f'{diff} (n={len(steps_d)})')
|
| 367 |
+
else:
|
| 368 |
+
ax.plot(steps_d, rewards_d, color=color, linewidth=2.5, label=diff)
|
| 369 |
+
for thr_diff, thr_val in _UNLOCK_THRESHOLDS.items():
|
| 370 |
+
ax.axhline(thr_val, color=PALETTE.get(thr_diff, SUBTEXT),
|
| 371 |
+
linestyle='--', linewidth=0.8, alpha=0.5)
|
| 372 |
+
ax.set_ylim(0, 1.05)
|
| 373 |
+
ax.legend(fontsize=9, facecolor=PANEL, edgecolor='#30363d', labelcolor=TEXT)
|
| 374 |
+
_setup(ax, xlabel='Training Step',
|
| 375 |
+
ylabel='Mean Reward per Difficulty Tier [0.01 β 0.99]',
|
| 376 |
+
title='Curriculum Learning Curves β Easy / Medium / Hard / Long-Horizon')
|
| 377 |
+
_caption(fig, f'Dashed lines = curriculum unlock thresholds. Each line = rolling mean of all tasks in that difficulty tier. | {ts}')
|
| 378 |
+
plt.tight_layout(rect=[0, 0.04, 1, 1])
|
| 379 |
+
p = os.path.join(run_dir, 'fig2_difficulty_curves.png')
|
| 380 |
+
plt.savefig(p, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 381 |
+
plt.close()
|
| 382 |
+
print(f'[METRICS] {p}')
|
| 383 |
+
|
| 384 |
+
# ββ Figure 3: Episode Length Distribution βββββββββββββββββββββββββββββ
|
| 385 |
+
if self.episode_len_hist:
|
| 386 |
+
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
|
| 387 |
+
fig.patch.set_facecolor(BG)
|
| 388 |
+
# Overall histogram
|
| 389 |
+
max_len = max(self.episode_len_hist)
|
| 390 |
+
bins = range(1, max_len + 2)
|
| 391 |
+
axes[0].hist(self.episode_len_hist, bins=bins, color=ACCENT, alpha=0.85,
|
| 392 |
+
edgecolor=BG, rwidth=0.8)
|
| 393 |
+
_setup(axes[0], xlabel='Episode Length (number of env steps)',
|
| 394 |
+
ylabel='Count of Episodes',
|
| 395 |
+
title='Episode Length Distribution (all tasks)')
|
| 396 |
+
axes[0].axvline(np.mean(self.episode_len_hist), color='#f78166',
|
| 397 |
+
linestyle='--', linewidth=1.5,
|
| 398 |
+
label=f'Mean = {np.mean(self.episode_len_hist):.1f}')
|
| 399 |
+
axes[0].legend(fontsize=8, facecolor=PANEL, edgecolor='#30363d', labelcolor=TEXT)
|
| 400 |
+
# Per-difficulty mean episode length bar
|
| 401 |
+
diff_ep_means = {}
|
| 402 |
+
for diff in _DIFFICULTY_ORDER:
|
| 403 |
+
lens = []
|
| 404 |
+
for tid, d in _TASK_DIFFICULTY.items():
|
| 405 |
+
if d == diff:
|
| 406 |
+
lens.extend(self.ep_len_by_task.get(tid, []))
|
| 407 |
+
if lens:
|
| 408 |
+
diff_ep_means[diff] = np.mean(lens)
|
| 409 |
+
if diff_ep_means:
|
| 410 |
+
diffs = list(diff_ep_means.keys())
|
| 411 |
+
means = list(diff_ep_means.values())
|
| 412 |
+
colors = [PALETTE.get(d, ACCENT) for d in diffs]
|
| 413 |
+
axes[1].bar(diffs, means, color=colors, alpha=0.85, edgecolor=BG, width=0.5)
|
| 414 |
+
for i, (d, m) in enumerate(zip(diffs, means)):
|
| 415 |
+
axes[1].text(i, m + 0.05, f'{m:.1f}', ha='center', color=TEXT, fontsize=9,
|
| 416 |
+
fontweight='bold')
|
| 417 |
+
axes[1].set_ylim(0, max(means) * 1.3)
|
| 418 |
+
_setup(axes[1], xlabel='Difficulty Tier',
|
| 419 |
+
ylabel='Mean Episode Length (steps)',
|
| 420 |
+
title='Mean Episode Length by Difficulty')
|
| 421 |
+
fig.suptitle('Episode Length Analysis β Multi-Step Decision Behavior', color=TEXT, fontsize=11, y=1.01)
|
| 422 |
+
_caption(fig, f'Long-horizon tasks expected to have higher mean episode lengths as agent learns to use ESCALATE/QUERY_VENDOR. | {ts}')
|
| 423 |
+
plt.tight_layout(rect=[0, 0.04, 1, 1])
|
| 424 |
+
p = os.path.join(run_dir, 'fig3_episode_lengths.png')
|
| 425 |
+
plt.savefig(p, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 426 |
+
plt.close()
|
| 427 |
+
print(f'[METRICS] {p}')
|
| 428 |
+
|
| 429 |
+
# ββ Figure 4: Format Compliance Rate Over Time ββββββββββββββββββββββββ
|
| 430 |
+
if self.format_history:
|
| 431 |
+
fig, ax = plt.subplots(figsize=(10, 3.5))
|
| 432 |
+
fig.patch.set_facecolor(BG)
|
| 433 |
+
steps_f = [s for s, _ in self.format_history]
|
| 434 |
+
fmt_vals = [r for _, r in self.format_history]
|
| 435 |
+
ax.plot(steps_f, fmt_vals, color='#d29922', alpha=0.25, linewidth=1)
|
| 436 |
+
if len(fmt_vals) >= 5:
|
| 437 |
+
sm, w = _smooth(fmt_vals)
|
| 438 |
+
ax.plot(steps_f[w-1:], sm, color='#d29922', linewidth=2.5,
|
| 439 |
+
label=f'EMA (w={w})')
|
| 440 |
+
final_rate = sum(self.format_scores) / max(1, len(self.format_scores))
|
| 441 |
+
ax.axhline(final_rate, color='#3fb950', linestyle='--', linewidth=1.5,
|
| 442 |
+
label=f'Overall rate = {final_rate:.1%}')
|
| 443 |
+
ax.set_ylim(0, 1.05)
|
| 444 |
+
ax.legend(fontsize=8, facecolor=PANEL, edgecolor='#30363d', labelcolor=TEXT)
|
| 445 |
+
_setup(ax, xlabel='Training Step',
|
| 446 |
+
ylabel='Format Compliance Rate [0 β 1]',
|
| 447 |
+
title='JSON Format Compliance Over Training')
|
| 448 |
+
_caption(fig, f'Format compliance = fraction of completions producing valid JSON with correct fields. Parse failures = {self.parse_failures}. | {ts}')
|
| 449 |
+
plt.tight_layout(rect=[0, 0.04, 1, 1])
|
| 450 |
+
p = os.path.join(run_dir, 'fig4_format_compliance.png')
|
| 451 |
+
plt.savefig(p, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 452 |
+
plt.close()
|
| 453 |
+
print(f'[METRICS] {p}')
|
| 454 |
+
|
| 455 |
+
# ββ Figure 5: Decision Distribution Over Time (stacked bar) ββββββββββ
|
| 456 |
+
if self.decision_history and len(self.decision_history) >= 3:
|
| 457 |
+
all_decisions = sorted(set(self.decision_counts.keys()))
|
| 458 |
+
# Sample ~20 evenly-spaced checkpoints for readability
|
| 459 |
+
n_checkpoints = min(20, len(self.decision_history))
|
| 460 |
+
idxs = [int(i * (len(self.decision_history) - 1) / (n_checkpoints - 1))
|
| 461 |
+
for i in range(n_checkpoints)]
|
| 462 |
+
ckpt_steps = [self.decision_history[i][0] for i in idxs]
|
| 463 |
+
ckpt_counts = [self.decision_history[i][1] for i in idxs]
|
| 464 |
+
# Convert to fractions
|
| 465 |
+
fracs = []
|
| 466 |
+
for c in ckpt_counts:
|
| 467 |
+
total_c = sum(c.values()) or 1
|
| 468 |
+
fracs.append({d: c.get(d, 0) / total_c for d in all_decisions})
|
| 469 |
+
fig, ax = plt.subplots(figsize=(12, 4))
|
| 470 |
+
fig.patch.set_facecolor(BG)
|
| 471 |
+
dec_colors = ['#3fb950','#f85149','#d29922','#a371f7','#58a6ff','#f0883e']
|
| 472 |
+
bottom = np.zeros(len(ckpt_steps))
|
| 473 |
+
for j, dec in enumerate(all_decisions):
|
| 474 |
+
vals = np.array([f[dec] for f in fracs])
|
| 475 |
+
ax.bar(range(len(ckpt_steps)), vals, bottom=bottom,
|
| 476 |
+
label=dec, color=dec_colors[j % len(dec_colors)],
|
| 477 |
+
alpha=0.85, edgecolor=BG)
|
| 478 |
+
bottom += vals
|
| 479 |
+
ax.set_xticks(range(len(ckpt_steps)))
|
| 480 |
+
ax.set_xticklabels([str(s) for s in ckpt_steps], rotation=45, fontsize=7)
|
| 481 |
+
ax.set_ylim(0, 1.05)
|
| 482 |
+
ax.legend(fontsize=7, facecolor=PANEL, edgecolor='#30363d', labelcolor=TEXT,
|
| 483 |
+
loc='upper right', bbox_to_anchor=(1.15, 1))
|
| 484 |
+
_setup(ax, xlabel='Training Step (checkpoint)',
|
| 485 |
+
ylabel='Fraction of Decisions',
|
| 486 |
+
title='Decision Distribution Over Training (Stacked Bar)')
|
| 487 |
+
_caption(fig, f'Each bar = cumulative decision distribution up to that checkpoint. Ideal: APPROVE_FULL grows for easy tasks, REJECT for fraud/duplicate tasks. | {ts}')
|
| 488 |
+
plt.tight_layout(rect=[0, 0.04, 0.88, 1])
|
| 489 |
+
p = os.path.join(run_dir, 'fig5_decision_distribution.png')
|
| 490 |
+
plt.savefig(p, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 491 |
+
plt.close()
|
| 492 |
+
print(f'[METRICS] {p}')
|
| 493 |
+
|
| 494 |
+
# ββ Figure 6: Per-Task Training Mean (horizontal bar) βββββββββββββββββ
|
| 495 |
+
if self.reward_by_task:
|
| 496 |
+
task_means = {t: sum(v)/len(v) for t, v in self.reward_by_task.items()}
|
| 497 |
+
tasks = sorted(task_means, key=lambda t: (_DIFFICULTY_ORDER.index(_TASK_DIFFICULTY.get(t,'easy')), t))
|
| 498 |
+
means = [task_means[t] for t in tasks]
|
| 499 |
+
colors = [PALETTE.get(_TASK_DIFFICULTY.get(t,'easy'), ACCENT) for t in tasks]
|
| 500 |
+
short = [t.replace('easy_','').replace('medium_','').replace('hard_','').replace('long_','').replace('_',' ').title() for t in tasks]
|
| 501 |
+
|
| 502 |
+
fig, ax = plt.subplots(figsize=(10, max(4, len(tasks) * 0.45)))
|
| 503 |
+
fig.patch.set_facecolor(BG)
|
| 504 |
+
yp = range(len(tasks))
|
| 505 |
+
ax.barh(list(yp), means, color=colors, alpha=0.85, edgecolor=BG)
|
| 506 |
+
ax.set_yticks(list(yp))
|
| 507 |
+
ax.set_yticklabels(short, fontsize=8)
|
| 508 |
+
ax.set_xlim(0, 1.05)
|
| 509 |
+
overall_mean = sum(means) / len(means)
|
| 510 |
+
ax.axvline(overall_mean, color='#f78166', linestyle='--', linewidth=1.5,
|
| 511 |
+
label=f'Overall mean = {overall_mean:.3f}')
|
| 512 |
+
ax.axvline(0.5, color=SUBTEXT, linestyle=':', linewidth=1, alpha=0.5)
|
| 513 |
+
for i, m in enumerate(means):
|
| 514 |
+
ax.text(m + 0.01, i, f'{m:.3f}', va='center', color=TEXT, fontsize=7)
|
| 515 |
+
from matplotlib.patches import Patch
|
| 516 |
+
legend_els = [Patch(facecolor=PALETTE[d], label=d.title()) for d in _DIFFICULTY_ORDER if d in PALETTE]
|
| 517 |
+
legend_els.append(plt.Line2D([0],[0], color='#f78166', linestyle='--', label=f'Mean {overall_mean:.3f}'))
|
| 518 |
+
ax.legend(handles=legend_els, fontsize=8, facecolor=PANEL, edgecolor='#30363d', labelcolor=TEXT)
|
| 519 |
+
_setup(ax, xlabel='Mean Training Reward [0.01 β 0.99]',
|
| 520 |
+
ylabel='Task',
|
| 521 |
+
title='Per-Task Training Mean Reward (all episodes)')
|
| 522 |
+
_caption(fig, f'Tasks ordered by difficulty. Green β₯ 0.7 = curriculum mastered. Orange = in progress. Red < 0.4 = needs more training. | {ts}')
|
| 523 |
+
plt.tight_layout(rect=[0, 0.04, 1, 1])
|
| 524 |
+
p = os.path.join(run_dir, 'fig6_per_task_means.png')
|
| 525 |
+
plt.savefig(p, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 526 |
+
plt.close()
|
| 527 |
+
print(f'[METRICS] {p}')
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
METRICS = Metrics()
|
| 531 |
+
_EPISODE_LOG_PATH: str = '' # set to run_dir/episodes.jsonl once run_dir is known
|
| 532 |
+
|
| 533 |
+
# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 534 |
+
|
| 535 |
+
def obs_to_prompt(obs: dict) -> str:
|
| 536 |
+
inv = obs['invoice']
|
| 537 |
+
lines = '\n'.join(
|
| 538 |
+
f" {li['description']}: qty={li['quantity']}, unit_price=${li['unit_price']:.2f}"
|
| 539 |
+
for li in inv.get('line_items', [])
|
| 540 |
+
)
|
| 541 |
+
pos = '\n'.join(
|
| 542 |
+
f" PO {p['po_number']} ({p['status']}) {p['vendor_name']}: " +
|
| 543 |
+
', '.join(f"{l['description']} qty={l['ordered_quantity']} @${l['agreed_unit_price']:.2f}"
|
| 544 |
+
for l in p.get('lines', []))
|
| 545 |
+
for p in obs.get('purchase_orders', [])
|
| 546 |
+
)
|
| 547 |
+
grns = '\n'.join(
|
| 548 |
+
f" GRN {g['grn_id']} (PO {g['po_number']}): " +
|
| 549 |
+
', '.join(f"{l['description']} recv={l['received_quantity']}"
|
| 550 |
+
for l in g.get('lines', []))
|
| 551 |
+
for g in obs.get('goods_receipts', [])
|
| 552 |
+
)
|
| 553 |
+
context = '\n'.join(f' {n}' for n in obs.get('context_notes', []))
|
| 554 |
+
paid = ', '.join(obs.get('paid_invoice_ids', []))
|
| 555 |
+
return (
|
| 556 |
+
f"TASK: {obs['task_name']}\n{obs['task_description']}\n\n"
|
| 557 |
+
f"INVOICE {inv['invoice_id']} | {inv['vendor_name']} | ${inv['invoice_total']:,.2f}\n{lines}\n"
|
| 558 |
+
f"Freight: ${inv.get('freight_charge',0):.2f}\n\n"
|
| 559 |
+
f"PURCHASE ORDERS:\n{pos}\n\nGOODS RECEIPTS:\n{grns}\n"
|
| 560 |
+
+ (f"PAID LEDGER: {paid}\n" if paid else "")
|
| 561 |
+
+ (f"CONTEXT:\n{context}\n" if context else "")
|
| 562 |
+
+ f"\nPOLICY:\n{obs['company_policy']}\n\nOutput JSON decision."
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def parse_action(raw: str) -> tuple[dict, bool]:
|
| 567 |
+
"""Returns (action_dict, format_ok). format_ok=False means parse failed."""
|
| 568 |
+
clean = re.sub(r'```(?:json)?\s*|\s*```', '', raw).strip()
|
| 569 |
+
m = re.search(r'\{.*\}', clean, re.DOTALL)
|
| 570 |
+
if m:
|
| 571 |
+
try:
|
| 572 |
+
action = json.loads(m.group())
|
| 573 |
+
# Validate required fields and enum values
|
| 574 |
+
if (action.get('decision') in VALID_DECISIONS and
|
| 575 |
+
action.get('reason_code') in VALID_REASON_CODES and
|
| 576 |
+
isinstance(action.get('approved_amount'), (int, float)) and
|
| 577 |
+
isinstance(action.get('explanation'), str) and
|
| 578 |
+
len(action.get('explanation', '')) > 10):
|
| 579 |
+
return action, True
|
| 580 |
+
except Exception:
|
| 581 |
+
pass
|
| 582 |
+
METRICS.parse_failures += 1
|
| 583 |
+
return {'decision': 'REJECT', 'approved_amount': 0.0,
|
| 584 |
+
'reason_code': 'NO_PO_FOUND', 'explanation': 'parse error fallback'}, False
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def run_episode(task_id: str, action_json: dict, seed=None) -> float:
|
| 588 |
+
try:
|
| 589 |
+
r = requests.post(f'{ENV_URL}/reset',
|
| 590 |
+
json={'task_id': task_id, 'seed': seed}, timeout=20)
|
| 591 |
+
r.raise_for_status()
|
| 592 |
+
data = r.json()
|
| 593 |
+
step_r = requests.post(f'{ENV_URL}/step',
|
| 594 |
+
json={'session_id': data['session_id'], 'action': action_json},
|
| 595 |
+
timeout=20)
|
| 596 |
+
step_r.raise_for_status()
|
| 597 |
+
return float(step_r.json()['reward']['score'])
|
| 598 |
+
except Exception:
|
| 599 |
+
return 0.01
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def run_episode_accumulated(task_id: str, first_action: dict, seed=None,
|
| 603 |
+
discount: float = 0.9, max_steps: int = 20,
|
| 604 |
+
episode_log: list | None = None) -> tuple[float, int]:
|
| 605 |
+
"""
|
| 606 |
+
Run a full multi-step episode accumulating discounted per-step rewards.
|
| 607 |
+
Returns (score, episode_length) so callers can track step counts.
|
| 608 |
+
Model's first action starts the episode; _greedy_followup() handles
|
| 609 |
+
subsequent steps so multi-step sequences earn full accumulated credit.
|
| 610 |
+
E.g. QUERY_VENDORβREJECT = 0.01 + 0.9*0.99 = 0.901 > shortcut REJECT = ~0.4
|
| 611 |
+
|
| 612 |
+
episode_log: if provided, appended with one dict per env step for JSONL logging.
|
| 613 |
+
"""
|
| 614 |
+
try:
|
| 615 |
+
r = requests.post(f'{ENV_URL}/reset',
|
| 616 |
+
json={'task_id': task_id, 'seed': seed}, timeout=20)
|
| 617 |
+
r.raise_for_status()
|
| 618 |
+
reset_data = r.json()
|
| 619 |
+
session_id = reset_data['session_id']
|
| 620 |
+
action = first_action
|
| 621 |
+
total = 0.0
|
| 622 |
+
steps_taken = 0
|
| 623 |
+
for step_n in range(max_steps):
|
| 624 |
+
step_r = requests.post(f'{ENV_URL}/step',
|
| 625 |
+
json={'session_id': session_id, 'action': action},
|
| 626 |
+
timeout=20)
|
| 627 |
+
step_r.raise_for_status()
|
| 628 |
+
result = step_r.json()
|
| 629 |
+
r_score = float(result['reward']['score'])
|
| 630 |
+
done = result['done']
|
| 631 |
+
obs_back = result.get('observation', {})
|
| 632 |
+
total += (discount ** step_n) * r_score
|
| 633 |
+
steps_taken = step_n + 1
|
| 634 |
+
if episode_log is not None:
|
| 635 |
+
episode_log.append({
|
| 636 |
+
'step_n': step_n,
|
| 637 |
+
'decision': action.get('decision'),
|
| 638 |
+
'approved_amount': action.get('approved_amount'),
|
| 639 |
+
'reason_code': action.get('reason_code'),
|
| 640 |
+
'explanation': (action.get('explanation') or '')[:120],
|
| 641 |
+
'step_score': round(r_score, 4),
|
| 642 |
+
'done': done,
|
| 643 |
+
'context_notes': obs_back.get('context_notes', []),
|
| 644 |
+
'action_history': obs_back.get('action_history', []),
|
| 645 |
+
})
|
| 646 |
+
if done:
|
| 647 |
+
break
|
| 648 |
+
action = _greedy_followup(obs_back)
|
| 649 |
+
return min(0.99, max(0.01, total)), steps_taken
|
| 650 |
+
except Exception as e:
|
| 651 |
+
return 0.01, 1
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ββ Two independent reward functions (guide: use multiple, not one) βββββββββββββ
|
| 655 |
+
|
| 656 |
+
def env_reward_fn(completions, task_id=None, seed=None, **kwargs):
|
| 657 |
+
"""
|
| 658 |
+
Environment reward: accumulated discounted per-step reward from AP Commander.
|
| 659 |
+
Curriculum gating redirects locked tasks to easier ones during early training.
|
| 660 |
+
Writes one JSONL record per episode to _EPISODE_LOG_PATH for full verifiability.
|
| 661 |
+
"""
|
| 662 |
+
task_ids = task_id if task_id is not None else ['easy_perfect_match'] * len(completions)
|
| 663 |
+
seeds = seed if seed is not None else [random.randint(1, 999)] * len(completions)
|
| 664 |
+
|
| 665 |
+
rewards, decisions, format_ok_list, ep_lengths, errors = [], [], [], [], 0
|
| 666 |
+
for completion, tid, s in zip(completions, task_ids, seeds):
|
| 667 |
+
gated_tid = CURRICULUM.gate_task(tid)
|
| 668 |
+
if gated_tid != tid:
|
| 669 |
+
print(f'[CURRICULUM] gate {tid} β {gated_tid}')
|
| 670 |
+
|
| 671 |
+
action, fmt_ok = parse_action(completion)
|
| 672 |
+
episode_steps = []
|
| 673 |
+
try:
|
| 674 |
+
score, ep_len = run_episode_accumulated(
|
| 675 |
+
gated_tid, action, seed=int(s), episode_log=episode_steps)
|
| 676 |
+
except Exception as e:
|
| 677 |
+
score, ep_len = 0.01, 1
|
| 678 |
+
errors += 1
|
| 679 |
+
|
| 680 |
+
rewards.append(score)
|
| 681 |
+
ep_lengths.append(ep_len)
|
| 682 |
+
decisions.append(action.get('decision', 'UNKNOWN'))
|
| 683 |
+
format_ok_list.append(fmt_ok)
|
| 684 |
+
CURRICULUM.record(gated_tid, score)
|
| 685 |
+
|
| 686 |
+
# Write structured episode record to JSONL for full verifiability
|
| 687 |
+
if _EPISODE_LOG_PATH:
|
| 688 |
+
try:
|
| 689 |
+
record = {
|
| 690 |
+
'reward_step': METRICS.step + 1,
|
| 691 |
+
'call_n': METRICS.total_calls + len(rewards),
|
| 692 |
+
'task_id': tid,
|
| 693 |
+
'gated_task_id': gated_tid,
|
| 694 |
+
'seed': int(s),
|
| 695 |
+
'format_ok': fmt_ok,
|
| 696 |
+
'score': round(score, 4),
|
| 697 |
+
'episode_len': ep_len,
|
| 698 |
+
'final_decision': action.get('decision'),
|
| 699 |
+
'steps': episode_steps,
|
| 700 |
+
'ts': datetime.datetime.now().isoformat(),
|
| 701 |
+
}
|
| 702 |
+
with open(_EPISODE_LOG_PATH, 'a') as _f:
|
| 703 |
+
_f.write(json.dumps(record) + '\n')
|
| 704 |
+
except Exception:
|
| 705 |
+
pass
|
| 706 |
+
|
| 707 |
+
if METRICS.total_calls % LOG_SAMPLES_EVERY == 0:
|
| 708 |
+
gated_note = f'β{gated_tid}' if gated_tid != tid else ''
|
| 709 |
+
print(f'\n[SAMPLE] task={tid}{gated_note} seed={s} fmt={fmt_ok} '
|
| 710 |
+
f'score={score:.3f} ep_len={ep_len}')
|
| 711 |
+
print(f' {action.get("decision")} ${action.get("approved_amount")} '
|
| 712 |
+
f'{action.get("reason_code")}')
|
| 713 |
+
print(f' {str(action.get("explanation",""))[:100]}')
|
| 714 |
+
print(f' curriculum: {CURRICULUM.status_line()}')
|
| 715 |
+
if episode_steps:
|
| 716 |
+
actor_notes = [n for step in episode_steps
|
| 717 |
+
for n in step.get('context_notes', [])]
|
| 718 |
+
if actor_notes:
|
| 719 |
+
print(f' actor_responses: {actor_notes[:2]}')
|
| 720 |
+
|
| 721 |
+
METRICS.log_step(rewards, decisions, format_ok_list, list(task_ids), errors,
|
| 722 |
+
episode_lengths=ep_lengths)
|
| 723 |
+
if METRICS.step % 5 == 0:
|
| 724 |
+
METRICS.print_summary()
|
| 725 |
+
print(f'[CURRICULUM] {CURRICULUM.status_line()}')
|
| 726 |
+
return rewards
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def format_reward_fn(completions, **kwargs):
|
| 730 |
+
"""Format reward: +0.05 if valid JSON with correct fields, -0.05 otherwise."""
|
| 731 |
+
results = []
|
| 732 |
+
for completion in completions:
|
| 733 |
+
_, ok = parse_action(completion)
|
| 734 |
+
results.append(0.05 if ok else -0.05)
|
| 735 |
+
return results
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
# ββ Eval helper ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 739 |
+
|
| 740 |
+
def eval_task(model, tokenizer, task_id: str, seed: int = 99) -> float:
|
| 741 |
+
import torch
|
| 742 |
+
model.eval()
|
| 743 |
+
try:
|
| 744 |
+
reset = requests.post(f'{ENV_URL}/reset', json={'task_id': task_id, 'seed': seed}, timeout=20).json()
|
| 745 |
+
obs, session_id = reset['observation'], reset['session_id']
|
| 746 |
+
messages = [{'role': 'system', 'content': SYSTEM_PROMPT},
|
| 747 |
+
{'role': 'user', 'content': obs_to_prompt(obs)}]
|
| 748 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 749 |
+
inputs = tokenizer(text, return_tensors='pt').to('cuda')
|
| 750 |
+
with torch.no_grad():
|
| 751 |
+
out = model.generate(**inputs, max_new_tokens=250, temperature=0.1, do_sample=True)
|
| 752 |
+
raw = tokenizer.decode(out[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
|
| 753 |
+
action, fmt_ok = parse_action(raw)
|
| 754 |
+
score = float(requests.post(f'{ENV_URL}/step',
|
| 755 |
+
json={'session_id': session_id, 'action': action},
|
| 756 |
+
timeout=20).json()['reward']['score'])
|
| 757 |
+
print(f' output: {raw[:120].strip()}')
|
| 758 |
+
return score
|
| 759 |
+
except Exception as e:
|
| 760 |
+
print(f' eval error: {e}')
|
| 761 |
+
return 0.01
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
# ββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 765 |
+
|
| 766 |
+
def _make_run_dir() -> str:
|
| 767 |
+
"""Create timestamped run directory under /app/runs/grpo/MODEL-NEpoch-DATETIME."""
|
| 768 |
+
model_slug = MODEL_NAME.split('/')[-1].lower().replace('.', '-')
|
| 769 |
+
ts = datetime.datetime.now().strftime('%Y-%m-%d_%H%M')
|
| 770 |
+
run_dir = f'/app/runs/grpo/{model_slug}-{NUM_EPOCHS}ep-{ts}'
|
| 771 |
+
os.makedirs(run_dir, exist_ok=True)
|
| 772 |
+
return run_dir
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def main():
|
| 776 |
+
# Authenticate with HF Hub if token provided (needed for gated models like Llama-3)
|
| 777 |
+
hf_token = os.environ.get('HF_TOKEN') or os.environ.get('HUGGING_FACE_HUB_TOKEN')
|
| 778 |
+
if hf_token:
|
| 779 |
+
from huggingface_hub import login
|
| 780 |
+
login(token=hf_token, add_to_git_credential=False)
|
| 781 |
+
print('[AUTH] Logged in to HF Hub.')
|
| 782 |
+
else:
|
| 783 |
+
print('[AUTH] No HF_TOKEN set β using public models only (Qwen recommended).')
|
| 784 |
+
|
| 785 |
+
# All run artifacts go into this timestamped dir β never overwrite a previous run
|
| 786 |
+
RUN_DIR = _make_run_dir()
|
| 787 |
+
print(f'[RUN] Artifacts β {RUN_DIR}')
|
| 788 |
+
|
| 789 |
+
# Point the global episode log path so env_reward_fn can write structured logs
|
| 790 |
+
global _EPISODE_LOG_PATH
|
| 791 |
+
_EPISODE_LOG_PATH = os.path.join(RUN_DIR, 'episodes.jsonl')
|
| 792 |
+
print(f'[RUN] Episode log β {_EPISODE_LOG_PATH}')
|
| 793 |
+
|
| 794 |
+
print(f'[ENV] Checking {ENV_URL}...')
|
| 795 |
+
h = requests.get(f'{ENV_URL}/health', timeout=30).json()
|
| 796 |
+
print(f"[ENV] status={h['status']} tasks={h.get('total_tasks')}")
|
| 797 |
+
|
| 798 |
+
print(f'[MODEL] Loading {MODEL_NAME}...')
|
| 799 |
+
import torch
|
| 800 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 801 |
+
from peft import LoraConfig, get_peft_model, TaskType
|
| 802 |
+
from datasets import Dataset
|
| 803 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 804 |
+
|
| 805 |
+
bnb_config = BitsAndBytesConfig(
|
| 806 |
+
load_in_4bit=True,
|
| 807 |
+
bnb_4bit_quant_type='nf4',
|
| 808 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 809 |
+
bnb_4bit_use_double_quant=True,
|
| 810 |
+
)
|
| 811 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
|
| 812 |
+
if tokenizer.pad_token is None:
|
| 813 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 814 |
+
|
| 815 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 816 |
+
MODEL_NAME,
|
| 817 |
+
quantization_config=bnb_config,
|
| 818 |
+
device_map='auto',
|
| 819 |
+
trust_remote_code=True,
|
| 820 |
+
)
|
| 821 |
+
model.enable_input_require_grads()
|
| 822 |
+
model.gradient_checkpointing_enable()
|
| 823 |
+
|
| 824 |
+
lora_cfg = LoraConfig(
|
| 825 |
+
r=16, lora_alpha=16,
|
| 826 |
+
target_modules=['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj'],
|
| 827 |
+
lora_dropout=0, bias='none',
|
| 828 |
+
task_type=TaskType.CAUSAL_LM,
|
| 829 |
+
)
|
| 830 |
+
model = get_peft_model(model, lora_cfg)
|
| 831 |
+
model.print_trainable_parameters()
|
| 832 |
+
|
| 833 |
+
# Baseline eval (before training)
|
| 834 |
+
print('\n[BASELINE] Before training:')
|
| 835 |
+
baseline = {}
|
| 836 |
+
for t in EVAL_TASKS:
|
| 837 |
+
s = eval_task(model, tokenizer, t)
|
| 838 |
+
baseline[t] = s
|
| 839 |
+
print(f' {t}: {s:.3f}')
|
| 840 |
+
print(f' Mean: {sum(baseline.values())/len(baseline):.3f}')
|
| 841 |
+
model.train()
|
| 842 |
+
|
| 843 |
+
# Dataset contains ALL 17 tasks Γ 5 seeds = 85 prompts.
|
| 844 |
+
# gate_task() in env_reward_fn handles curriculum redirection at reward time:
|
| 845 |
+
# locked tasks (medium/hard/long) redirect to easy during early training.
|
| 846 |
+
# As curriculum unlocks thresholds, redirection stops and full task variety flows.
|
| 847 |
+
print(f'\n[DATASET] Building prompts ({len(TRAIN_TASKS)} tasks Γ 5 seeds = {len(TRAIN_TASKS)*5})...')
|
| 848 |
+
task_seed_pairs = [(tid, s) for tid in TRAIN_TASKS for s in range(1, 6)]
|
| 849 |
+
rows = []
|
| 850 |
+
for task_id, seed in task_seed_pairs:
|
| 851 |
+
try:
|
| 852 |
+
reset = requests.post(f'{ENV_URL}/reset', json={'task_id': task_id, 'seed': seed}, timeout=20).json()
|
| 853 |
+
obs = reset['observation']
|
| 854 |
+
messages = [{'role': 'system', 'content': SYSTEM_PROMPT},
|
| 855 |
+
{'role': 'user', 'content': obs_to_prompt(obs)}]
|
| 856 |
+
rows.append({
|
| 857 |
+
'prompt': tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True),
|
| 858 |
+
'task_id': task_id,
|
| 859 |
+
'seed': seed,
|
| 860 |
+
})
|
| 861 |
+
except Exception as e:
|
| 862 |
+
print(f' skip {task_id} seed={seed}: {e}')
|
| 863 |
+
|
| 864 |
+
dataset = Dataset.from_list(rows)
|
| 865 |
+
print(f'[DATASET] {len(dataset)} samples across {len(TRAIN_TASKS)} tasks '
|
| 866 |
+
f'({sum(1 for r in rows if _TASK_DIFFICULTY.get(r["task_id"],"easy")=="long")} long-horizon) '
|
| 867 |
+
f'| curriculum: {CURRICULUM.status_line()}')
|
| 868 |
+
|
| 869 |
+
# Train
|
| 870 |
+
print(f'\n[TRAIN] {NUM_EPOCHS} epochs | {NUM_GENERATIONS} generations/prompt | {len(dataset)} samples')
|
| 871 |
+
model.train()
|
| 872 |
+
# generation_batch_size = per_device_train_batch_size (TRL default).
|
| 873 |
+
# TRL requires: generation_batch_size % num_generations == 0.
|
| 874 |
+
# Simplest fix: set per_device_train_batch_size = num_generations.
|
| 875 |
+
config = GRPOConfig(
|
| 876 |
+
output_dir = './ap_commander_grpo',
|
| 877 |
+
num_train_epochs = NUM_EPOCHS,
|
| 878 |
+
per_device_train_batch_size = NUM_GENERATIONS,
|
| 879 |
+
num_generations = NUM_GENERATIONS,
|
| 880 |
+
gradient_accumulation_steps = 1,
|
| 881 |
+
learning_rate = 2e-5,
|
| 882 |
+
max_completion_length = 250,
|
| 883 |
+
temperature = 0.9,
|
| 884 |
+
logging_steps = 1,
|
| 885 |
+
save_steps = 999,
|
| 886 |
+
report_to = 'none',
|
| 887 |
+
remove_unused_columns = False,
|
| 888 |
+
)
|
| 889 |
+
# Two independent reward functions (guide: use multiple, not one combined signal)
|
| 890 |
+
trainer = GRPOTrainer(
|
| 891 |
+
model=model, processing_class=tokenizer,
|
| 892 |
+
reward_funcs=[env_reward_fn, format_reward_fn],
|
| 893 |
+
args=config, train_dataset=dataset,
|
| 894 |
+
)
|
| 895 |
+
result = trainer.train()
|
| 896 |
+
print(f'\n[TRAIN] Done. Loss: {result.training_loss:.4f}')
|
| 897 |
+
|
| 898 |
+
METRICS.print_summary()
|
| 899 |
+
METRICS.save_all_metrics_figures(RUN_DIR)
|
| 900 |
+
|
| 901 |
+
# Save LoRA adapters (guide point 16: save adapters directly, do NOT merge 4-bit naively)
|
| 902 |
+
adapter_dir = os.path.join(RUN_DIR, 'adapter')
|
| 903 |
+
print(f'[SAVE] Saving LoRA adapters to {adapter_dir}...')
|
| 904 |
+
model.save_pretrained(adapter_dir)
|
| 905 |
+
tokenizer.save_pretrained(adapter_dir)
|
| 906 |
+
|
| 907 |
+
# Upload adapter to HF Hub as a model repo
|
| 908 |
+
try:
|
| 909 |
+
from huggingface_hub import HfApi
|
| 910 |
+
api = HfApi()
|
| 911 |
+
api.upload_folder(
|
| 912 |
+
folder_path=adapter_dir,
|
| 913 |
+
repo_id='Pathikreet/ap-commander-adapter',
|
| 914 |
+
repo_type='model',
|
| 915 |
+
commit_message=f'GRPO {datetime.datetime.now().strftime("%Y-%m-%d")} β {MODEL_NAME} {NUM_EPOCHS}ep',
|
| 916 |
+
)
|
| 917 |
+
print('[SAVE] Adapter pushed to HF Hub: Pathikreet/ap-commander-adapter')
|
| 918 |
+
except Exception as e:
|
| 919 |
+
print(f'[SAVE] HF Hub upload skipped: {e}')
|
| 920 |
+
|
| 921 |
+
# Post-training eval (all 10 tasks)
|
| 922 |
+
print('\n[POST-EVAL] After training:')
|
| 923 |
+
post = {}
|
| 924 |
+
model.eval()
|
| 925 |
+
for t in EVAL_TASKS:
|
| 926 |
+
s = eval_task(model, tokenizer, t)
|
| 927 |
+
post[t] = s
|
| 928 |
+
print(f' {t}: {s:.3f}')
|
| 929 |
+
print(f' Mean: {sum(post.values())/len(post):.3f}')
|
| 930 |
+
|
| 931 |
+
print('\n[COMPARE]')
|
| 932 |
+
for t in EVAL_TASKS:
|
| 933 |
+
d = post[t] - baseline[t]
|
| 934 |
+
sym = '+' if d >= 0 else ''
|
| 935 |
+
print(f' {t:<35} {baseline[t]:.3f} -> {post[t]:.3f} ({sym}{d:.3f})')
|
| 936 |
+
|
| 937 |
+
# ββ Before/After comparison figure (results.png β key result for demo) ββββ
|
| 938 |
+
BG, TEXT, SUBTEXT = '#0d1117', '#e6edf3', '#8b949e'
|
| 939 |
+
PANEL, GRID = '#161b22', '#21262d'
|
| 940 |
+
_fmt_rate = sum(METRICS.format_scores) / max(1, len(METRICS.format_scores))
|
| 941 |
+
|
| 942 |
+
eval_tasks_sorted = sorted(
|
| 943 |
+
EVAL_TASKS,
|
| 944 |
+
key=lambda t: (_DIFFICULTY_ORDER.index(_TASK_DIFFICULTY.get(t,'easy')), t)
|
| 945 |
+
)
|
| 946 |
+
DIFF_COLORS = {'easy': '#3fb950', 'medium': '#d29922', 'hard': '#f85149', 'long': '#a371f7'}
|
| 947 |
+
|
| 948 |
+
fig = plt.figure(figsize=(18, max(8, len(eval_tasks_sorted) * 0.45 + 2)))
|
| 949 |
+
fig.patch.set_facecolor(BG)
|
| 950 |
+
gs = fig.add_gridspec(1, 2, wspace=0.38)
|
| 951 |
+
|
| 952 |
+
# Panel left: before/after horizontal bars
|
| 953 |
+
ax_l = fig.add_subplot(gs[0, 0])
|
| 954 |
+
ax_l.set_facecolor(PANEL)
|
| 955 |
+
yp = np.arange(len(eval_tasks_sorted))
|
| 956 |
+
short = [t.replace('easy_','').replace('medium_','').replace('hard_','').replace('long_','')
|
| 957 |
+
.replace('_',' ').title() for t in eval_tasks_sorted]
|
| 958 |
+
bar_h = 0.35
|
| 959 |
+
bars_b = ax_l.barh(yp - bar_h/2, [baseline.get(t, 0) for t in eval_tasks_sorted],
|
| 960 |
+
bar_h, label='Before GRPO', color='#f85149', alpha=0.85, edgecolor=BG)
|
| 961 |
+
bars_a = ax_l.barh(yp + bar_h/2, [post.get(t, 0) for t in eval_tasks_sorted],
|
| 962 |
+
bar_h, label='After GRPO', color='#3fb950', alpha=0.85, edgecolor=BG)
|
| 963 |
+
ax_l.set_yticks(yp)
|
| 964 |
+
ax_l.set_yticklabels(short, fontsize=8, color=TEXT)
|
| 965 |
+
ax_l.set_xlim(0, 1.15)
|
| 966 |
+
ax_l.axvline(0.5, color=SUBTEXT, linestyle='--', linewidth=1, alpha=0.5)
|
| 967 |
+
# Color-code y-tick labels by difficulty
|
| 968 |
+
for i, t in enumerate(eval_tasks_sorted):
|
| 969 |
+
ax_l.get_yticklabels()[i].set_color(DIFF_COLORS.get(_TASK_DIFFICULTY.get(t,'easy'), TEXT))
|
| 970 |
+
ax_l.legend(fontsize=9, facecolor=PANEL, edgecolor='#30363d', labelcolor=TEXT)
|
| 971 |
+
ax_l.set_xlabel('Task Score [0.01 β 0.99]', color=SUBTEXT, fontsize=9)
|
| 972 |
+
ax_l.set_ylabel('Task (color = difficulty tier)', color=SUBTEXT, fontsize=9)
|
| 973 |
+
ax_l.set_title(f'Before vs After GRPO β {NUM_EPOCHS} Epochs', color=TEXT, fontsize=11,
|
| 974 |
+
fontweight='bold', pad=10)
|
| 975 |
+
ax_l.tick_params(colors=TEXT, labelsize=8)
|
| 976 |
+
for sp in ax_l.spines.values(): sp.set_color('#30363d')
|
| 977 |
+
ax_l.spines['top'].set_visible(False); ax_l.spines['right'].set_visible(False)
|
| 978 |
+
ax_l.xaxis.grid(True, color=GRID, linewidth=0.6, alpha=0.7)
|
| 979 |
+
ax_l.set_axisbelow(True)
|
| 980 |
+
|
| 981 |
+
# Panel right: delta (improvement) per task
|
| 982 |
+
ax_r = fig.add_subplot(gs[0, 1])
|
| 983 |
+
ax_r.set_facecolor(PANEL)
|
| 984 |
+
deltas = [post.get(t, 0) - baseline.get(t, 0) for t in eval_tasks_sorted]
|
| 985 |
+
d_colors = ['#3fb950' if d >= 0 else '#f85149' for d in deltas]
|
| 986 |
+
ax_r.barh(yp, deltas, color=d_colors, alpha=0.85, edgecolor=BG)
|
| 987 |
+
ax_r.set_yticks(yp)
|
| 988 |
+
ax_r.set_yticklabels(short, fontsize=8, color=TEXT)
|
| 989 |
+
ax_r.axvline(0, color=SUBTEXT, linewidth=1)
|
| 990 |
+
for i, d in enumerate(deltas):
|
| 991 |
+
ax_r.text(d + 0.005 * np.sign(d + 1e-9), i, f'{d:+.3f}',
|
| 992 |
+
va='center', color=TEXT, fontsize=7)
|
| 993 |
+
ax_r.set_xlabel('Score Delta (After β Before)', color=SUBTEXT, fontsize=9)
|
| 994 |
+
ax_r.set_ylabel('Task', color=SUBTEXT, fontsize=9)
|
| 995 |
+
ax_r.set_title('GRPO Improvement per Task', color=TEXT, fontsize=11,
|
| 996 |
+
fontweight='bold', pad=10)
|
| 997 |
+
ax_r.tick_params(colors=TEXT, labelsize=8)
|
| 998 |
+
for sp in ax_r.spines.values(): sp.set_color('#30363d')
|
| 999 |
+
ax_r.spines['top'].set_visible(False); ax_r.spines['right'].set_visible(False)
|
| 1000 |
+
ax_r.xaxis.grid(True, color=GRID, linewidth=0.6, alpha=0.7)
|
| 1001 |
+
ax_r.set_axisbelow(True)
|
| 1002 |
+
|
| 1003 |
+
mean_before = sum(baseline.get(t,0) for t in eval_tasks_sorted) / len(eval_tasks_sorted)
|
| 1004 |
+
mean_after = sum(post.get(t,0) for t in eval_tasks_sorted) / len(eval_tasks_sorted)
|
| 1005 |
+
fig.suptitle(
|
| 1006 |
+
f'AP Commander GRPO β {MODEL_NAME.split("/")[-1]} | {NUM_EPOCHS} epochs | '
|
| 1007 |
+
f'{NUM_GENERATIONS} generations | {len(TRAIN_TASKS)} tasks\n'
|
| 1008 |
+
f'Overall: {mean_before:.3f} β {mean_after:.3f} (+{mean_after-mean_before:.3f}) '
|
| 1009 |
+
f'| format={_fmt_rate:.1%} | parse_fails={METRICS.parse_failures} '
|
| 1010 |
+
f'| {datetime.datetime.now().strftime("%Y-%m-%d")}',
|
| 1011 |
+
color=TEXT, fontsize=10, y=1.01
|
| 1012 |
+
)
|
| 1013 |
+
fig.text(0.5, -0.01,
|
| 1014 |
+
'Task colors: green=easy, yellow=medium, red=hard, purple=long-horizon. '
|
| 1015 |
+
'Score range [0.01, 0.99] as per AP Commander environment specification.',
|
| 1016 |
+
ha='center', color=SUBTEXT, fontsize=8, style='italic')
|
| 1017 |
+
results_png = os.path.join(RUN_DIR, 'results.png')
|
| 1018 |
+
plt.savefig(results_png, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 1019 |
+
plt.close()
|
| 1020 |
+
print(f'[DONE] Saved {results_png}')
|
| 1021 |
+
|
| 1022 |
+
# Save JSON
|
| 1023 |
+
fmt_rate = sum(METRICS.format_scores) / max(1, len(METRICS.format_scores))
|
| 1024 |
+
output = {
|
| 1025 |
+
'timestamp': datetime.datetime.now().isoformat(),
|
| 1026 |
+
'run_dir': RUN_DIR,
|
| 1027 |
+
'model': MODEL_NAME,
|
| 1028 |
+
'epochs': NUM_EPOCHS,
|
| 1029 |
+
'num_generations': NUM_GENERATIONS,
|
| 1030 |
+
'per_device_train_batch_size': NUM_GENERATIONS,
|
| 1031 |
+
'train_tasks': TRAIN_TASKS,
|
| 1032 |
+
'eval_tasks': list(EVAL_TASKS),
|
| 1033 |
+
'hardware': 'A10G (HF Spaces)',
|
| 1034 |
+
'baseline': baseline,
|
| 1035 |
+
'post_training': post,
|
| 1036 |
+
'delta': {t: round(post.get(t,0) - baseline.get(t,0), 4) for t in EVAL_TASKS},
|
| 1037 |
+
'overall_baseline': round(mean_before, 4),
|
| 1038 |
+
'overall_post': round(mean_after, 4),
|
| 1039 |
+
'overall_delta': round(mean_after - mean_before, 4),
|
| 1040 |
+
'episode_log': _EPISODE_LOG_PATH,
|
| 1041 |
+
'metrics': {
|
| 1042 |
+
'total_reward_calls': METRICS.total_calls,
|
| 1043 |
+
'parse_failures': METRICS.parse_failures,
|
| 1044 |
+
'env_errors': METRICS.env_errors,
|
| 1045 |
+
'format_rate': round(fmt_rate, 4),
|
| 1046 |
+
'decision_counts': dict(METRICS.decision_counts),
|
| 1047 |
+
'per_task_mean': {t: round(sum(v)/len(v), 4) for t, v in METRICS.reward_by_task.items()},
|
| 1048 |
+
'mean_episode_length': round(sum(METRICS.episode_len_hist) / max(1, len(METRICS.episode_len_hist)), 2),
|
| 1049 |
+
'by_difficulty_post': {d: round(sum(post.get(t,0) for t,diff in _TASK_DIFFICULTY.items()
|
| 1050 |
+
if diff==d and t in post) /
|
| 1051 |
+
max(1, sum(1 for t,diff in _TASK_DIFFICULTY.items()
|
| 1052 |
+
if diff==d and t in post)), 4)
|
| 1053 |
+
for d in _DIFFICULTY_ORDER},
|
| 1054 |
+
},
|
| 1055 |
+
'figures': [
|
| 1056 |
+
'fig1_reward_curve.png',
|
| 1057 |
+
'fig2_difficulty_curves.png',
|
| 1058 |
+
'fig3_episode_lengths.png',
|
| 1059 |
+
'fig4_format_compliance.png',
|
| 1060 |
+
'fig5_decision_distribution.png',
|
| 1061 |
+
'fig6_per_task_means.png',
|
| 1062 |
+
'results.png',
|
| 1063 |
+
],
|
| 1064 |
+
}
|
| 1065 |
+
results_json = os.path.join(RUN_DIR, 'training_results.json')
|
| 1066 |
+
with open(results_json, 'w') as f:
|
| 1067 |
+
json.dump(output, f, indent=2)
|
| 1068 |
+
print(f'[DONE] Saved {results_json}')
|
| 1069 |
+
|
| 1070 |
+
# Copy live metrics into run dir as snapshot
|
| 1071 |
+
try:
|
| 1072 |
+
import shutil
|
| 1073 |
+
shutil.copy('/app/metrics_live.json', os.path.join(RUN_DIR, 'metrics_live.json'))
|
| 1074 |
+
except Exception:
|
| 1075 |
+
pass
|
| 1076 |
+
|
| 1077 |
+
# Persist entire run dir to HF Space repo (runs/grpo/MODEL-NEP-DATETIME/)
|
| 1078 |
+
# so artifacts survive container restarts and each run is independently addressable
|
| 1079 |
+
repo_run_path = RUN_DIR.replace('/app/', '') # strip /app/ prefix for repo path
|
| 1080 |
+
try:
|
| 1081 |
+
from huggingface_hub import HfApi
|
| 1082 |
+
api = HfApi()
|
| 1083 |
+
api.upload_folder(
|
| 1084 |
+
folder_path=RUN_DIR,
|
| 1085 |
+
path_in_repo=repo_run_path,
|
| 1086 |
+
repo_id='Pathikreet/ap-commander-training',
|
| 1087 |
+
repo_type='space',
|
| 1088 |
+
commit_message=f'Run artifacts: {os.path.basename(RUN_DIR)}',
|
| 1089 |
+
ignore_patterns=['adapter/*'], # adapter uploaded separately to model repo
|
| 1090 |
+
)
|
| 1091 |
+
print(f'[UPLOAD] Run folder β {repo_run_path} in Pathikreet/ap-commander-training')
|
| 1092 |
+
except Exception as e:
|
| 1093 |
+
print(f'[UPLOAD] artifact upload failed: {e}')
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
if __name__ == '__main__':
|
| 1097 |
+
main()
|