sync source for HF Jobs training run
Browse files- app.py +207 -0
- docs/baseline_comparison.png +3 -0
- docs/reward_curve.png +3 -0
- results/comparison.json +210 -0
- scripts/eval_trained.py +217 -0
- scripts/hf_job_entry.sh +82 -82
- scripts/plot_results.py +159 -0
app.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PromptOps Arena — HF Space demo (Gradio).
|
| 3 |
+
|
| 4 |
+
Tabs:
|
| 5 |
+
1. Try the env: pick a task, edit a system prompt, see the LLM-under-test
|
| 6 |
+
respond + the per-component reward. Up to 3 edit turns per episode.
|
| 7 |
+
2. Reward curve: training_log.jsonl rolling avg over GRPO rollouts.
|
| 8 |
+
3. Baselines vs trained agent: bar chart of mean reward / accuracy.
|
| 9 |
+
|
| 10 |
+
The frozen LLM-under-test runs in-process. ZeroGPU is used at first inference.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Dict, List, Tuple
|
| 20 |
+
|
| 21 |
+
# Make src importable regardless of where Gradio runs
|
| 22 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 23 |
+
|
| 24 |
+
import gradio as gr # type: ignore
|
| 25 |
+
|
| 26 |
+
# Default to the real backend on Spaces; allow override
|
| 27 |
+
os.environ.setdefault("PROMPTOPS_LLM_BACKEND", "transformers")
|
| 28 |
+
|
| 29 |
+
from src.envs.promptops_arena.server.environment import PromptOpsArenaEnvironment # noqa: E402
|
| 30 |
+
from src.envs.promptops_arena.tasks import load_tasks # noqa: E402
|
| 31 |
+
|
| 32 |
+
ENV = PromptOpsArenaEnvironment(split="test", seed=0)
|
| 33 |
+
ALL_TASKS: List[dict] = load_tasks(split="test")
|
| 34 |
+
TASKS_BY_ID: Dict[str, dict] = {t["id"]: t for t in ALL_TASKS}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
SUGGESTED_PROMPTS = {
|
| 38 |
+
"math": (
|
| 39 |
+
"You are a careful math solver. Solve step by step internally, then "
|
| 40 |
+
"output ONLY the final numeric answer inside <answer>...</answer> tags. "
|
| 41 |
+
"No units, no extra words."
|
| 42 |
+
),
|
| 43 |
+
"code": (
|
| 44 |
+
"You are a Python coder. Output exactly one ```python ...``` code block "
|
| 45 |
+
"containing only the requested function definition. No prose, no examples."
|
| 46 |
+
),
|
| 47 |
+
"json": (
|
| 48 |
+
"You are a JSON extractor. Output exactly one ```json ...``` code block "
|
| 49 |
+
"containing a valid JSON object that matches the schema. No prose."
|
| 50 |
+
),
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def list_task_choices() -> List[Tuple[str, str]]:
|
| 55 |
+
out: List[Tuple[str, str]] = []
|
| 56 |
+
for t in ALL_TASKS:
|
| 57 |
+
label = f"[{t['type']}] {t['id']}: {t['question'][:70]}"
|
| 58 |
+
out.append((label, t["id"]))
|
| 59 |
+
return out
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_task_info(task_id: str) -> Tuple[str, str, str]:
|
| 63 |
+
t = TASKS_BY_ID.get(task_id)
|
| 64 |
+
if not t:
|
| 65 |
+
return "", "", ""
|
| 66 |
+
schema = ""
|
| 67 |
+
if t.get("type") == "json" and "schema" in t:
|
| 68 |
+
schema = f"\n\nSchema: ```json\n{json.dumps(t['schema'], indent=2)}\n```"
|
| 69 |
+
if t.get("type") == "code" and "tests" in t:
|
| 70 |
+
schema = "\n\nUnit tests:\n```python\n" + "\n".join(t["tests"]) + "\n```"
|
| 71 |
+
return t["question"] + schema, t.get("type", ""), SUGGESTED_PROMPTS.get(t.get("type", ""), "")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def run_prompt(task_id: str, system_prompt: str) -> Tuple[str, str, str]:
|
| 75 |
+
"""Run one shot of [system_prompt, task] through the env."""
|
| 76 |
+
t = TASKS_BY_ID.get(task_id)
|
| 77 |
+
if t is None:
|
| 78 |
+
return "(no task selected)", "", ""
|
| 79 |
+
if not (system_prompt or "").strip():
|
| 80 |
+
return "(empty prompt)", "", ""
|
| 81 |
+
res = ENV.execute_prompt(t, system_prompt)
|
| 82 |
+
completion = res["completion"]
|
| 83 |
+
rd = res["reward"]
|
| 84 |
+
breakdown = (
|
| 85 |
+
f"correctness: {rd['correctness']:.2f}\n"
|
| 86 |
+
f"format : {rd['format']:.2f} (×0.1 in total)\n"
|
| 87 |
+
f"brevity : {rd['brevity']:+.3f}\n"
|
| 88 |
+
f"-------\n"
|
| 89 |
+
f"TOTAL : {rd['total']:+.3f}"
|
| 90 |
+
)
|
| 91 |
+
verifier = res.get("verifier", {})
|
| 92 |
+
details = verifier.get("details", "")
|
| 93 |
+
return completion, breakdown, details
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def load_reward_curve_image() -> str | None:
|
| 97 |
+
p = Path(__file__).resolve().parent / "docs" / "reward_curve.png"
|
| 98 |
+
return str(p) if p.exists() else None
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def load_comparison_image() -> str | None:
|
| 102 |
+
p = Path(__file__).resolve().parent / "docs" / "baseline_comparison.png"
|
| 103 |
+
return str(p) if p.exists() else None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def load_comparison_table() -> str:
|
| 107 |
+
p = Path(__file__).resolve().parent / "results" / "comparison.json"
|
| 108 |
+
if not p.exists():
|
| 109 |
+
return "_No comparison.json yet — train + run plot_results.py to populate._"
|
| 110 |
+
d = json.loads(p.read_text(encoding="utf-8"))
|
| 111 |
+
rows = d.get("policies", {})
|
| 112 |
+
if not rows:
|
| 113 |
+
return "_comparison.json is empty._"
|
| 114 |
+
lines = [
|
| 115 |
+
"| policy | n | correct | format | mean_reward |",
|
| 116 |
+
"|---|---:|---:|---:|---:|",
|
| 117 |
+
]
|
| 118 |
+
for label, r in rows.items():
|
| 119 |
+
lines.append(
|
| 120 |
+
f"| {label} | {r['n']} | {r['correct']} | {r['format']} | {r['mean_reward']:+.3f} |"
|
| 121 |
+
)
|
| 122 |
+
return "\n".join(lines)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# ---------------------------------------------------------------------------
|
| 126 |
+
# UI
|
| 127 |
+
# ---------------------------------------------------------------------------
|
| 128 |
+
|
| 129 |
+
INTRO = """
|
| 130 |
+
# PromptOps Arena 🎯
|
| 131 |
+
|
| 132 |
+
> An RL environment where an agent learns to **write better prompts** via GRPO,
|
| 133 |
+
> across math, code, and JSON-extraction tasks.
|
| 134 |
+
|
| 135 |
+
- **Agent (trained):** Qwen2.5-1.5B-Instruct + LoRA, optimized with GRPO.
|
| 136 |
+
- **LLM-under-test (frozen):** Qwen2.5-0.5B-Instruct.
|
| 137 |
+
- **Reward:** `correctness + 0.1·format + brevity_penalty`, all programmatic.
|
| 138 |
+
|
| 139 |
+
Try writing your own system prompts in the **Try the env** tab.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
with gr.Blocks(title="PromptOps Arena", theme=gr.themes.Soft()) as demo:
|
| 144 |
+
gr.Markdown(INTRO)
|
| 145 |
+
|
| 146 |
+
with gr.Tab("Try the env"):
|
| 147 |
+
with gr.Row():
|
| 148 |
+
task_dd = gr.Dropdown(
|
| 149 |
+
choices=list_task_choices(),
|
| 150 |
+
value=ALL_TASKS[0]["id"] if ALL_TASKS else None,
|
| 151 |
+
label="Pick a task",
|
| 152 |
+
interactive=True,
|
| 153 |
+
)
|
| 154 |
+
task_text = gr.Markdown(label="Task")
|
| 155 |
+
task_type_box = gr.Textbox(label="task type", interactive=False)
|
| 156 |
+
with gr.Row():
|
| 157 |
+
with gr.Column():
|
| 158 |
+
system_prompt = gr.Textbox(
|
| 159 |
+
label="Your system prompt (this is the action)",
|
| 160 |
+
lines=8,
|
| 161 |
+
placeholder="Write the system prompt to give to the small frozen LLM…",
|
| 162 |
+
)
|
| 163 |
+
with gr.Row():
|
| 164 |
+
suggest_btn = gr.Button("Use suggested prompt")
|
| 165 |
+
run_btn = gr.Button("▶ Run", variant="primary")
|
| 166 |
+
with gr.Column():
|
| 167 |
+
completion_out = gr.Textbox(
|
| 168 |
+
label="LLM-under-test completion", lines=8, interactive=False,
|
| 169 |
+
)
|
| 170 |
+
reward_out = gr.Textbox(
|
| 171 |
+
label="Reward decomposition", lines=6, interactive=False,
|
| 172 |
+
)
|
| 173 |
+
verifier_out = gr.Textbox(
|
| 174 |
+
label="Verifier details", lines=2, interactive=False,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
def _on_task(task_id):
|
| 178 |
+
text, ttype, suggested = get_task_info(task_id)
|
| 179 |
+
return text, ttype, suggested
|
| 180 |
+
|
| 181 |
+
task_dd.change(_on_task, inputs=task_dd, outputs=[task_text, task_type_box, system_prompt])
|
| 182 |
+
suggest_btn.click(_on_task, inputs=task_dd, outputs=[task_text, task_type_box, system_prompt])
|
| 183 |
+
run_btn.click(run_prompt, inputs=[task_dd, system_prompt],
|
| 184 |
+
outputs=[completion_out, reward_out, verifier_out])
|
| 185 |
+
|
| 186 |
+
with gr.Tab("Reward curve"):
|
| 187 |
+
gr.Markdown("### GRPO training reward curve\n"
|
| 188 |
+
"Each point is the env's total reward for one rollout during training.")
|
| 189 |
+
rc_img = gr.Image(value=load_reward_curve_image(), label="reward_curve.png",
|
| 190 |
+
interactive=False, show_label=False)
|
| 191 |
+
gr.Markdown(
|
| 192 |
+
"_If this is empty, training hasn't been run yet or `docs/reward_curve.png` "
|
| 193 |
+
"is missing. Run `scripts/plot_results.py` after training._"
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
with gr.Tab("Baselines vs trained agent"):
|
| 197 |
+
gr.Markdown("### Comparison on the held-out test split\n")
|
| 198 |
+
cmp_img = gr.Image(value=load_comparison_image(), label="baseline_comparison.png",
|
| 199 |
+
interactive=False, show_label=False)
|
| 200 |
+
gr.Markdown(load_comparison_table())
|
| 201 |
+
|
| 202 |
+
with gr.Tab("How it works"):
|
| 203 |
+
gr.Markdown((Path(__file__).resolve().parent / "docs" / "SCOPE.md").read_text(encoding="utf-8"))
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
if __name__ == "__main__":
|
| 207 |
+
demo.queue().launch()
|
docs/baseline_comparison.png
ADDED
|
Git LFS Details
|
docs/reward_curve.png
ADDED
|
Git LFS Details
|
results/comparison.json
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"policies": {
|
| 3 |
+
"zero_shot (stub)": {
|
| 4 |
+
"n": 30,
|
| 5 |
+
"correct": 0,
|
| 6 |
+
"format": 0,
|
| 7 |
+
"mean_reward": 0.0,
|
| 8 |
+
"by_type": {
|
| 9 |
+
"math": {
|
| 10 |
+
"n": 10,
|
| 11 |
+
"correct": 0,
|
| 12 |
+
"format": 0
|
| 13 |
+
},
|
| 14 |
+
"code": {
|
| 15 |
+
"n": 10,
|
| 16 |
+
"correct": 0,
|
| 17 |
+
"format": 0
|
| 18 |
+
},
|
| 19 |
+
"json": {
|
| 20 |
+
"n": 10,
|
| 21 |
+
"correct": 0,
|
| 22 |
+
"format": 0
|
| 23 |
+
}
|
| 24 |
+
},
|
| 25 |
+
"backend": "stub"
|
| 26 |
+
},
|
| 27 |
+
"cot (stub)": {
|
| 28 |
+
"n": 30,
|
| 29 |
+
"correct": 0,
|
| 30 |
+
"format": 30,
|
| 31 |
+
"mean_reward": 0.1,
|
| 32 |
+
"by_type": {
|
| 33 |
+
"math": {
|
| 34 |
+
"n": 10,
|
| 35 |
+
"correct": 0,
|
| 36 |
+
"format": 10
|
| 37 |
+
},
|
| 38 |
+
"code": {
|
| 39 |
+
"n": 10,
|
| 40 |
+
"correct": 0,
|
| 41 |
+
"format": 10
|
| 42 |
+
},
|
| 43 |
+
"json": {
|
| 44 |
+
"n": 10,
|
| 45 |
+
"correct": 0,
|
| 46 |
+
"format": 10
|
| 47 |
+
}
|
| 48 |
+
},
|
| 49 |
+
"backend": "stub"
|
| 50 |
+
},
|
| 51 |
+
"zero_shot (real LLM)": {
|
| 52 |
+
"n": 6,
|
| 53 |
+
"correct": 4,
|
| 54 |
+
"format": 3,
|
| 55 |
+
"mean_reward": 0.7166666666666668,
|
| 56 |
+
"by_type": {
|
| 57 |
+
"math": {
|
| 58 |
+
"n": 2,
|
| 59 |
+
"correct": 1,
|
| 60 |
+
"format": 0
|
| 61 |
+
},
|
| 62 |
+
"code": {
|
| 63 |
+
"n": 2,
|
| 64 |
+
"correct": 1,
|
| 65 |
+
"format": 1
|
| 66 |
+
},
|
| 67 |
+
"json": {
|
| 68 |
+
"n": 2,
|
| 69 |
+
"correct": 2,
|
| 70 |
+
"format": 2
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
"backend": "transformers"
|
| 74 |
+
},
|
| 75 |
+
"cot (real LLM)": {
|
| 76 |
+
"n": 6,
|
| 77 |
+
"correct": 4,
|
| 78 |
+
"format": 6,
|
| 79 |
+
"mean_reward": 0.7666666666666667,
|
| 80 |
+
"by_type": {
|
| 81 |
+
"math": {
|
| 82 |
+
"n": 2,
|
| 83 |
+
"correct": 0,
|
| 84 |
+
"format": 2
|
| 85 |
+
},
|
| 86 |
+
"code": {
|
| 87 |
+
"n": 2,
|
| 88 |
+
"correct": 2,
|
| 89 |
+
"format": 2
|
| 90 |
+
},
|
| 91 |
+
"json": {
|
| 92 |
+
"n": 2,
|
| 93 |
+
"correct": 2,
|
| 94 |
+
"format": 2
|
| 95 |
+
}
|
| 96 |
+
},
|
| 97 |
+
"backend": "transformers"
|
| 98 |
+
}
|
| 99 |
+
},
|
| 100 |
+
"ranking_by_mean_reward": [
|
| 101 |
+
[
|
| 102 |
+
"cot (real LLM)",
|
| 103 |
+
{
|
| 104 |
+
"n": 6,
|
| 105 |
+
"correct": 4,
|
| 106 |
+
"format": 6,
|
| 107 |
+
"mean_reward": 0.7666666666666667,
|
| 108 |
+
"by_type": {
|
| 109 |
+
"math": {
|
| 110 |
+
"n": 2,
|
| 111 |
+
"correct": 0,
|
| 112 |
+
"format": 2
|
| 113 |
+
},
|
| 114 |
+
"code": {
|
| 115 |
+
"n": 2,
|
| 116 |
+
"correct": 2,
|
| 117 |
+
"format": 2
|
| 118 |
+
},
|
| 119 |
+
"json": {
|
| 120 |
+
"n": 2,
|
| 121 |
+
"correct": 2,
|
| 122 |
+
"format": 2
|
| 123 |
+
}
|
| 124 |
+
},
|
| 125 |
+
"backend": "transformers"
|
| 126 |
+
}
|
| 127 |
+
],
|
| 128 |
+
[
|
| 129 |
+
"zero_shot (real LLM)",
|
| 130 |
+
{
|
| 131 |
+
"n": 6,
|
| 132 |
+
"correct": 4,
|
| 133 |
+
"format": 3,
|
| 134 |
+
"mean_reward": 0.7166666666666668,
|
| 135 |
+
"by_type": {
|
| 136 |
+
"math": {
|
| 137 |
+
"n": 2,
|
| 138 |
+
"correct": 1,
|
| 139 |
+
"format": 0
|
| 140 |
+
},
|
| 141 |
+
"code": {
|
| 142 |
+
"n": 2,
|
| 143 |
+
"correct": 1,
|
| 144 |
+
"format": 1
|
| 145 |
+
},
|
| 146 |
+
"json": {
|
| 147 |
+
"n": 2,
|
| 148 |
+
"correct": 2,
|
| 149 |
+
"format": 2
|
| 150 |
+
}
|
| 151 |
+
},
|
| 152 |
+
"backend": "transformers"
|
| 153 |
+
}
|
| 154 |
+
],
|
| 155 |
+
[
|
| 156 |
+
"cot (stub)",
|
| 157 |
+
{
|
| 158 |
+
"n": 30,
|
| 159 |
+
"correct": 0,
|
| 160 |
+
"format": 30,
|
| 161 |
+
"mean_reward": 0.1,
|
| 162 |
+
"by_type": {
|
| 163 |
+
"math": {
|
| 164 |
+
"n": 10,
|
| 165 |
+
"correct": 0,
|
| 166 |
+
"format": 10
|
| 167 |
+
},
|
| 168 |
+
"code": {
|
| 169 |
+
"n": 10,
|
| 170 |
+
"correct": 0,
|
| 171 |
+
"format": 10
|
| 172 |
+
},
|
| 173 |
+
"json": {
|
| 174 |
+
"n": 10,
|
| 175 |
+
"correct": 0,
|
| 176 |
+
"format": 10
|
| 177 |
+
}
|
| 178 |
+
},
|
| 179 |
+
"backend": "stub"
|
| 180 |
+
}
|
| 181 |
+
],
|
| 182 |
+
[
|
| 183 |
+
"zero_shot (stub)",
|
| 184 |
+
{
|
| 185 |
+
"n": 30,
|
| 186 |
+
"correct": 0,
|
| 187 |
+
"format": 0,
|
| 188 |
+
"mean_reward": 0.0,
|
| 189 |
+
"by_type": {
|
| 190 |
+
"math": {
|
| 191 |
+
"n": 10,
|
| 192 |
+
"correct": 0,
|
| 193 |
+
"format": 0
|
| 194 |
+
},
|
| 195 |
+
"code": {
|
| 196 |
+
"n": 10,
|
| 197 |
+
"correct": 0,
|
| 198 |
+
"format": 0
|
| 199 |
+
},
|
| 200 |
+
"json": {
|
| 201 |
+
"n": 10,
|
| 202 |
+
"correct": 0,
|
| 203 |
+
"format": 0
|
| 204 |
+
}
|
| 205 |
+
},
|
| 206 |
+
"backend": "stub"
|
| 207 |
+
}
|
| 208 |
+
]
|
| 209 |
+
]
|
| 210 |
+
}
|
scripts/eval_trained.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Phase 6: Evaluate the GRPO-trained agent on the test split.
|
| 3 |
+
|
| 4 |
+
Loads:
|
| 5 |
+
- base agent: Qwen/Qwen2.5-1.5B-Instruct (frozen weights)
|
| 6 |
+
- LoRA adapter: from --adapter (local dir or HF model repo id)
|
| 7 |
+
|
| 8 |
+
For each test task:
|
| 9 |
+
1. build agent input (same as training)
|
| 10 |
+
2. agent generates a candidate system prompt
|
| 11 |
+
3. env runs LLM-under-test with that prompt; verify; reward
|
| 12 |
+
4. up to --max-turns retries with the previous attempt visible
|
| 13 |
+
|
| 14 |
+
Outputs results/trained_agent.json in the same shape as run_baseline.py.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
import time
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Any, Dict, List
|
| 26 |
+
|
| 27 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 28 |
+
|
| 29 |
+
from src.envs.promptops_arena.server.environment import PromptOpsArenaEnvironment
|
| 30 |
+
from src.envs.promptops_arena.tasks import load_tasks
|
| 31 |
+
from src.envs.promptops_arena import llm_under_test
|
| 32 |
+
from scripts.train_grpo import build_agent_input # reuse the exact prompt template
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _load_agent(base_model: str, adapter: str | None):
|
| 36 |
+
import torch # type: ignore
|
| 37 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer # type: ignore
|
| 38 |
+
|
| 39 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 40 |
+
dtype = torch.bfloat16 if device == "cuda" else torch.float32
|
| 41 |
+
|
| 42 |
+
tok = AutoTokenizer.from_pretrained(base_model)
|
| 43 |
+
if tok.pad_token is None:
|
| 44 |
+
tok.pad_token = tok.eos_token
|
| 45 |
+
|
| 46 |
+
mdl = AutoModelForCausalLM.from_pretrained(
|
| 47 |
+
base_model, torch_dtype=dtype, device_map=device,
|
| 48 |
+
)
|
| 49 |
+
if adapter:
|
| 50 |
+
from peft import PeftModel # type: ignore
|
| 51 |
+
mdl = PeftModel.from_pretrained(mdl, adapter)
|
| 52 |
+
mdl.eval()
|
| 53 |
+
|
| 54 |
+
def gen(text: str, max_new_tokens: int = 300) -> str:
|
| 55 |
+
msgs = [
|
| 56 |
+
{"role": "system", "content": "You are a helpful prompt engineer."},
|
| 57 |
+
{"role": "user", "content": text},
|
| 58 |
+
]
|
| 59 |
+
encoded = tok.apply_chat_template(
|
| 60 |
+
msgs, add_generation_prompt=True, return_tensors="pt",
|
| 61 |
+
)
|
| 62 |
+
if hasattr(encoded, "input_ids"):
|
| 63 |
+
ids = encoded.input_ids
|
| 64 |
+
elif isinstance(encoded, dict):
|
| 65 |
+
ids = encoded["input_ids"]
|
| 66 |
+
else:
|
| 67 |
+
ids = encoded
|
| 68 |
+
ids = ids.to(device)
|
| 69 |
+
with torch.no_grad():
|
| 70 |
+
out = mdl.generate(
|
| 71 |
+
input_ids=ids, max_new_tokens=max_new_tokens,
|
| 72 |
+
do_sample=False, pad_token_id=tok.eos_token_id,
|
| 73 |
+
)
|
| 74 |
+
return tok.decode(out[0][ids.shape[1]:], skip_special_tokens=True).strip()
|
| 75 |
+
|
| 76 |
+
return gen
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _build_followup_input(task: dict, history: List[dict]) -> str:
|
| 80 |
+
"""Like build_agent_input but with prior attempts visible (refinement turn)."""
|
| 81 |
+
base = build_agent_input(task)
|
| 82 |
+
if not history:
|
| 83 |
+
return base
|
| 84 |
+
extra = ["", "PRIOR ATTEMPTS (yours, with what the small model produced):"]
|
| 85 |
+
for i, h in enumerate(history, 1):
|
| 86 |
+
extra.append(f"--- attempt {i} (reward={h['reward']:.2f}, correct={h['correct']}) ---")
|
| 87 |
+
extra.append(f"YOUR PROMPT: {h['prompt'][:400]}")
|
| 88 |
+
extra.append(f"MODEL OUTPUT: {h['completion'][:200]}")
|
| 89 |
+
extra.append("")
|
| 90 |
+
extra.append("Improve the system prompt. Output ONLY the new system prompt, no preamble.")
|
| 91 |
+
return base + "\n" + "\n".join(extra)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def evaluate_trained(env, task, agent_gen, max_turns: int = 3) -> Dict[str, Any]:
|
| 95 |
+
history: List[dict] = []
|
| 96 |
+
best_reward = -1.0
|
| 97 |
+
best_components: Dict[str, float] = {}
|
| 98 |
+
correct = False
|
| 99 |
+
edit_turns = 0
|
| 100 |
+
|
| 101 |
+
for turn in range(max_turns):
|
| 102 |
+
edit_turns = turn + 1
|
| 103 |
+
ai = build_agent_input(task) if turn == 0 else _build_followup_input(task, history)
|
| 104 |
+
sp = agent_gen(ai).strip() or "Solve this:"
|
| 105 |
+
res = env.execute_prompt(task, sp)
|
| 106 |
+
components = res["reward"]
|
| 107 |
+
total = components["total"]
|
| 108 |
+
is_correct = components["correctness"] >= 1.0
|
| 109 |
+
|
| 110 |
+
history.append({
|
| 111 |
+
"prompt": sp,
|
| 112 |
+
"completion": res["completion"],
|
| 113 |
+
"reward": total,
|
| 114 |
+
"correct": is_correct,
|
| 115 |
+
})
|
| 116 |
+
|
| 117 |
+
if total > best_reward:
|
| 118 |
+
best_reward = total
|
| 119 |
+
best_components = components
|
| 120 |
+
|
| 121 |
+
if is_correct:
|
| 122 |
+
correct = True
|
| 123 |
+
break
|
| 124 |
+
|
| 125 |
+
return {
|
| 126 |
+
"task_id": task["id"],
|
| 127 |
+
"task_type": task["type"],
|
| 128 |
+
"policy": "trained_agent",
|
| 129 |
+
"edit_turns": edit_turns,
|
| 130 |
+
"final_reward": best_reward,
|
| 131 |
+
"correct": correct,
|
| 132 |
+
"format_ok": best_components.get("format", 0.0) >= 1.0,
|
| 133 |
+
"components": best_components,
|
| 134 |
+
"trace": history,
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def main():
|
| 139 |
+
p = argparse.ArgumentParser()
|
| 140 |
+
p.add_argument("--adapter", default=None,
|
| 141 |
+
help="Local dir or HF repo id of the LoRA adapter.")
|
| 142 |
+
p.add_argument("--base", default="Qwen/Qwen2.5-1.5B-Instruct")
|
| 143 |
+
p.add_argument("--split", default="test")
|
| 144 |
+
p.add_argument("--out", default="results/trained_agent.json")
|
| 145 |
+
p.add_argument("--limit", type=int, default=None)
|
| 146 |
+
p.add_argument("--per-type", type=int, default=None)
|
| 147 |
+
p.add_argument("--max-turns", type=int, default=3)
|
| 148 |
+
args = p.parse_args()
|
| 149 |
+
|
| 150 |
+
os.environ.setdefault("PROMPTOPS_LLM_BACKEND", "transformers")
|
| 151 |
+
|
| 152 |
+
tasks = load_tasks(split=args.split)
|
| 153 |
+
if args.per_type:
|
| 154 |
+
bucketed: Dict[str, List[dict]] = {}
|
| 155 |
+
for t in tasks:
|
| 156 |
+
bucketed.setdefault(t["type"], []).append(t)
|
| 157 |
+
sampled: List[dict] = []
|
| 158 |
+
for tt, lst in bucketed.items():
|
| 159 |
+
sampled.extend(lst[: args.per_type])
|
| 160 |
+
tasks = sampled
|
| 161 |
+
if args.limit:
|
| 162 |
+
tasks = tasks[: args.limit]
|
| 163 |
+
|
| 164 |
+
print(f"[eval_trained] adapter={args.adapter} base={args.base} "
|
| 165 |
+
f"split={args.split} n_tasks={len(tasks)} "
|
| 166 |
+
f"llm_backend={llm_under_test.backend_name()}")
|
| 167 |
+
|
| 168 |
+
env = PromptOpsArenaEnvironment(split=args.split, seed=0)
|
| 169 |
+
agent_gen = _load_agent(args.base, args.adapter)
|
| 170 |
+
|
| 171 |
+
rows: List[Dict[str, Any]] = []
|
| 172 |
+
t0 = time.time()
|
| 173 |
+
for i, task in enumerate(tasks):
|
| 174 |
+
row = evaluate_trained(env, task, agent_gen, max_turns=args.max_turns)
|
| 175 |
+
rows.append(row)
|
| 176 |
+
n_correct = sum(1 for r in rows if r["correct"])
|
| 177 |
+
print(f" [{i+1}/{len(tasks)}] {task['type']:5s} "
|
| 178 |
+
f"correct={n_correct}/{i+1} "
|
| 179 |
+
f"r={row['final_reward']:+.3f} elapsed={time.time()-t0:.1f}s")
|
| 180 |
+
|
| 181 |
+
by_type: Dict[str, Dict[str, int]] = {}
|
| 182 |
+
for r in rows:
|
| 183 |
+
d = by_type.setdefault(r["task_type"], {"n": 0, "correct": 0, "format": 0})
|
| 184 |
+
d["n"] += 1
|
| 185 |
+
d["correct"] += int(r["correct"])
|
| 186 |
+
d["format"] += int(r["format_ok"])
|
| 187 |
+
|
| 188 |
+
overall = {
|
| 189 |
+
"n": len(rows),
|
| 190 |
+
"correct": sum(1 for r in rows if r["correct"]),
|
| 191 |
+
"format": sum(1 for r in rows if r["format_ok"]),
|
| 192 |
+
"mean_reward": sum(r["final_reward"] for r in rows) / max(1, len(rows)),
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
out = {
|
| 196 |
+
"policy": "trained_agent",
|
| 197 |
+
"adapter": args.adapter,
|
| 198 |
+
"base_model": args.base,
|
| 199 |
+
"split": args.split,
|
| 200 |
+
"llm_backend": llm_under_test.backend_name(),
|
| 201 |
+
"by_type": by_type,
|
| 202 |
+
"overall": overall,
|
| 203 |
+
"rows": rows,
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
out_path = Path(args.out)
|
| 207 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 208 |
+
out_path.write_text(json.dumps(out, indent=2), encoding="utf-8")
|
| 209 |
+
print(f"\n[eval_trained] wrote {out_path}")
|
| 210 |
+
print(f" overall: {overall['correct']}/{overall['n']} correct, "
|
| 211 |
+
f"mean_reward={overall['mean_reward']:.3f}")
|
| 212 |
+
for tt, d in by_type.items():
|
| 213 |
+
print(f" {tt:5s}: {d['correct']}/{d['n']} correct, format {d['format']}/{d['n']}")
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
main()
|
scripts/hf_job_entry.sh
CHANGED
|
@@ -1,82 +1,82 @@
|
|
| 1 |
-
#!/usr/bin/env bash
|
| 2 |
-
# Entrypoint executed inside the HF Jobs container.
|
| 3 |
-
# Expects:
|
| 4 |
-
# /code -> RO mount of dataset Dar3devil/promptops-arena-src
|
| 5 |
-
# $HF_TOKEN -> secret, for pushing the trained adapter
|
| 6 |
-
# $HF_USERNAME -> user namespace for the model repo (default: Dar3devil)
|
| 7 |
-
# $STEPS, $BATCH, $NUM_GENS (optional overrides)
|
| 8 |
-
|
| 9 |
-
set -euo pipefail
|
| 10 |
-
|
| 11 |
-
HF_USERNAME="${HF_USERNAME:-Dar3devil}"
|
| 12 |
-
STEPS="${STEPS:-200}"
|
| 13 |
-
BATCH="${BATCH:-4}"
|
| 14 |
-
NUM_GENS="${NUM_GENS:-4}"
|
| 15 |
-
LOG_LEVEL="${LOG_LEVEL:-info}"
|
| 16 |
-
MODEL_REPO="${HF_USERNAME}/promptops-arena-agent"
|
| 17 |
-
|
| 18 |
-
echo "[entry] HF_USERNAME=${HF_USERNAME} STEPS=${STEPS} BATCH=${BATCH} NUM_GENS=${NUM_GENS}"
|
| 19 |
-
echo "[entry] copying source from /code -> /workspace"
|
| 20 |
-
mkdir -p /workspace
|
| 21 |
-
cp -r /code/. /workspace/
|
| 22 |
-
cd /workspace
|
| 23 |
-
|
| 24 |
-
echo "[entry] python: $(python --version)"
|
| 25 |
-
echo "[entry] gpu:"
|
| 26 |
-
nvidia-smi || echo "no nvidia-smi"
|
| 27 |
-
|
| 28 |
-
echo "[entry] installing deps"
|
| 29 |
-
pip install --no-cache-dir --quiet --upgrade pip
|
| 30 |
-
pip install --no-cache-dir --quiet \
|
| 31 |
-
"torch>=2.4.0" \
|
| 32 |
-
"transformers>=4.45.0" \
|
| 33 |
-
"trl>=1.2.0" \
|
| 34 |
-
"peft>=0.13.0" \
|
| 35 |
-
"accelerate>=1.0.0" \
|
| 36 |
-
"datasets>=2.20.0" \
|
| 37 |
-
"huggingface_hub>=0.25.0" \
|
| 38 |
-
"jsonschema>=4.20.0" \
|
| 39 |
-
"openenv-core>=0.1.0" \
|
| 40 |
-
"fastapi>=0.110.0" \
|
| 41 |
-
"uvicorn>=0.27.0" \
|
| 42 |
-
"pydantic>=2.0.0"
|
| 43 |
-
|
| 44 |
-
export PROMPTOPS_LLM_BACKEND=transformers
|
| 45 |
-
export PYTHONUTF8=1
|
| 46 |
-
export TOKENIZERS_PARALLELISM=false
|
| 47 |
-
|
| 48 |
-
echo "[entry] launching GRPO training"
|
| 49 |
-
python scripts/train_grpo.py \
|
| 50 |
-
--steps "${STEPS}" \
|
| 51 |
-
--batch "${BATCH}" \
|
| 52 |
-
--num-generations "${NUM_GENS}" \
|
| 53 |
-
--out outputs/grpo-lora \
|
| 54 |
-
--log results/training_log.jsonl
|
| 55 |
-
|
| 56 |
-
echo "[entry] training done. uploading adapter + log to ${MODEL_REPO}"
|
| 57 |
-
python - <<'PY'
|
| 58 |
-
import os
|
| 59 |
-
from huggingface_hub import HfApi, create_repo
|
| 60 |
-
|
| 61 |
-
api = HfApi()
|
| 62 |
-
repo_id = f"{os.environ['HF_USERNAME']}/promptops-arena-agent"
|
| 63 |
-
create_repo(repo_id, repo_type="model", exist_ok=True, private=False)
|
| 64 |
-
|
| 65 |
-
api.upload_folder(
|
| 66 |
-
folder_path="outputs/grpo-lora",
|
| 67 |
-
repo_id=repo_id,
|
| 68 |
-
repo_type="model",
|
| 69 |
-
commit_message="GRPO-trained LoRA adapter",
|
| 70 |
-
)
|
| 71 |
-
# also upload training log so we can plot reward curves locally
|
| 72 |
-
api.upload_file(
|
| 73 |
-
path_or_fileobj="results/training_log.jsonl",
|
| 74 |
-
path_in_repo="training_log.jsonl",
|
| 75 |
-
repo_id=repo_id,
|
| 76 |
-
repo_type="model",
|
| 77 |
-
commit_message="training reward log",
|
| 78 |
-
)
|
| 79 |
-
print(f"[entry] uploaded to https://huggingface.co/{repo_id}")
|
| 80 |
-
PY
|
| 81 |
-
|
| 82 |
-
echo "[entry] all done."
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Entrypoint executed inside the HF Jobs container.
|
| 3 |
+
# Expects:
|
| 4 |
+
# /code -> RO mount of dataset Dar3devil/promptops-arena-src
|
| 5 |
+
# $HF_TOKEN -> secret, for pushing the trained adapter
|
| 6 |
+
# $HF_USERNAME -> user namespace for the model repo (default: Dar3devil)
|
| 7 |
+
# $STEPS, $BATCH, $NUM_GENS (optional overrides)
|
| 8 |
+
|
| 9 |
+
set -euo pipefail
|
| 10 |
+
|
| 11 |
+
HF_USERNAME="${HF_USERNAME:-Dar3devil}"
|
| 12 |
+
STEPS="${STEPS:-200}"
|
| 13 |
+
BATCH="${BATCH:-4}"
|
| 14 |
+
NUM_GENS="${NUM_GENS:-4}"
|
| 15 |
+
LOG_LEVEL="${LOG_LEVEL:-info}"
|
| 16 |
+
MODEL_REPO="${HF_USERNAME}/promptops-arena-agent"
|
| 17 |
+
|
| 18 |
+
echo "[entry] HF_USERNAME=${HF_USERNAME} STEPS=${STEPS} BATCH=${BATCH} NUM_GENS=${NUM_GENS}"
|
| 19 |
+
echo "[entry] copying source from /code -> /workspace"
|
| 20 |
+
mkdir -p /workspace
|
| 21 |
+
cp -r /code/. /workspace/
|
| 22 |
+
cd /workspace
|
| 23 |
+
|
| 24 |
+
echo "[entry] python: $(python --version)"
|
| 25 |
+
echo "[entry] gpu:"
|
| 26 |
+
nvidia-smi || echo "no nvidia-smi"
|
| 27 |
+
|
| 28 |
+
echo "[entry] installing deps"
|
| 29 |
+
pip install --no-cache-dir --quiet --upgrade pip
|
| 30 |
+
pip install --no-cache-dir --quiet \
|
| 31 |
+
"torch>=2.4.0" \
|
| 32 |
+
"transformers>=4.45.0" \
|
| 33 |
+
"trl>=1.2.0" \
|
| 34 |
+
"peft>=0.13.0" \
|
| 35 |
+
"accelerate>=1.0.0" \
|
| 36 |
+
"datasets>=2.20.0" \
|
| 37 |
+
"huggingface_hub>=0.25.0" \
|
| 38 |
+
"jsonschema>=4.20.0" \
|
| 39 |
+
"openenv-core>=0.1.0" \
|
| 40 |
+
"fastapi>=0.110.0" \
|
| 41 |
+
"uvicorn>=0.27.0" \
|
| 42 |
+
"pydantic>=2.0.0"
|
| 43 |
+
|
| 44 |
+
export PROMPTOPS_LLM_BACKEND=transformers
|
| 45 |
+
export PYTHONUTF8=1
|
| 46 |
+
export TOKENIZERS_PARALLELISM=false
|
| 47 |
+
|
| 48 |
+
echo "[entry] launching GRPO training"
|
| 49 |
+
python scripts/train_grpo.py \
|
| 50 |
+
--steps "${STEPS}" \
|
| 51 |
+
--batch "${BATCH}" \
|
| 52 |
+
--num-generations "${NUM_GENS}" \
|
| 53 |
+
--out outputs/grpo-lora \
|
| 54 |
+
--log results/training_log.jsonl
|
| 55 |
+
|
| 56 |
+
echo "[entry] training done. uploading adapter + log to ${MODEL_REPO}"
|
| 57 |
+
python - <<'PY'
|
| 58 |
+
import os
|
| 59 |
+
from huggingface_hub import HfApi, create_repo
|
| 60 |
+
|
| 61 |
+
api = HfApi()
|
| 62 |
+
repo_id = f"{os.environ['HF_USERNAME']}/promptops-arena-agent"
|
| 63 |
+
create_repo(repo_id, repo_type="model", exist_ok=True, private=False)
|
| 64 |
+
|
| 65 |
+
api.upload_folder(
|
| 66 |
+
folder_path="outputs/grpo-lora",
|
| 67 |
+
repo_id=repo_id,
|
| 68 |
+
repo_type="model",
|
| 69 |
+
commit_message="GRPO-trained LoRA adapter",
|
| 70 |
+
)
|
| 71 |
+
# also upload training log so we can plot reward curves locally
|
| 72 |
+
api.upload_file(
|
| 73 |
+
path_or_fileobj="results/training_log.jsonl",
|
| 74 |
+
path_in_repo="training_log.jsonl",
|
| 75 |
+
repo_id=repo_id,
|
| 76 |
+
repo_type="model",
|
| 77 |
+
commit_message="training reward log",
|
| 78 |
+
)
|
| 79 |
+
print(f"[entry] uploaded to https://huggingface.co/{repo_id}")
|
| 80 |
+
PY
|
| 81 |
+
|
| 82 |
+
echo "[entry] all done."
|
scripts/plot_results.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Phase 7: Build reward-curve plot + comparison artifact.
|
| 3 |
+
|
| 4 |
+
Inputs (any subset that exists):
|
| 5 |
+
results/training_log.jsonl # per-step rewards from GRPO
|
| 6 |
+
results/baseline_zero_shot_real_subset.json
|
| 7 |
+
results/baseline_cot_real_subset.json
|
| 8 |
+
results/baseline_zero_shot_stub.json
|
| 9 |
+
results/baseline_cot_stub.json
|
| 10 |
+
results/trained_agent.json # eval of the trained agent (Phase 6)
|
| 11 |
+
|
| 12 |
+
Outputs:
|
| 13 |
+
results/comparison.json
|
| 14 |
+
docs/reward_curve.png
|
| 15 |
+
docs/baseline_comparison.png
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Any, Dict, List
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load_json(p: Path) -> dict | None:
|
| 27 |
+
if not p.exists():
|
| 28 |
+
return None
|
| 29 |
+
try:
|
| 30 |
+
return json.loads(p.read_text(encoding="utf-8"))
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"[plot] WARN failed to load {p}: {e}")
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_jsonl(p: Path) -> List[dict]:
|
| 37 |
+
if not p.exists():
|
| 38 |
+
return []
|
| 39 |
+
rows: List[dict] = []
|
| 40 |
+
for line in p.read_text(encoding="utf-8").splitlines():
|
| 41 |
+
line = line.strip()
|
| 42 |
+
if not line:
|
| 43 |
+
continue
|
| 44 |
+
try:
|
| 45 |
+
rows.append(json.loads(line))
|
| 46 |
+
except Exception:
|
| 47 |
+
pass
|
| 48 |
+
return rows
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def smooth(values: List[float], window: int = 10) -> List[float]:
|
| 52 |
+
out: List[float] = []
|
| 53 |
+
for i in range(len(values)):
|
| 54 |
+
lo = max(0, i - window + 1)
|
| 55 |
+
out.append(sum(values[lo:i + 1]) / max(1, i + 1 - lo))
|
| 56 |
+
return out
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def main():
|
| 60 |
+
p = argparse.ArgumentParser()
|
| 61 |
+
p.add_argument("--results-dir", default="results")
|
| 62 |
+
p.add_argument("--docs-dir", default="docs")
|
| 63 |
+
args = p.parse_args()
|
| 64 |
+
|
| 65 |
+
res = Path(args.results_dir)
|
| 66 |
+
docs = Path(args.docs_dir)
|
| 67 |
+
docs.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
|
| 69 |
+
import matplotlib
|
| 70 |
+
matplotlib.use("Agg")
|
| 71 |
+
import matplotlib.pyplot as plt
|
| 72 |
+
|
| 73 |
+
# ---- 1. reward curve ----
|
| 74 |
+
log_rows = load_jsonl(res / "training_log.jsonl")
|
| 75 |
+
if log_rows:
|
| 76 |
+
rewards = [r["reward"]["total"] for r in log_rows if "reward" in r]
|
| 77 |
+
smoothed = smooth(rewards, window=20)
|
| 78 |
+
fig, ax = plt.subplots(figsize=(8, 4.5))
|
| 79 |
+
ax.plot(rewards, alpha=0.25, label="raw reward")
|
| 80 |
+
ax.plot(smoothed, linewidth=2, label="rolling avg (20)")
|
| 81 |
+
ax.set_xlabel("training rollout #")
|
| 82 |
+
ax.set_ylabel("reward")
|
| 83 |
+
ax.set_title("GRPO training reward curve · PromptOps Arena")
|
| 84 |
+
ax.grid(alpha=0.3)
|
| 85 |
+
ax.legend()
|
| 86 |
+
fig.tight_layout()
|
| 87 |
+
out = docs / "reward_curve.png"
|
| 88 |
+
fig.savefig(out, dpi=140)
|
| 89 |
+
plt.close(fig)
|
| 90 |
+
print(f"[plot] wrote {out} ({len(rewards)} points)")
|
| 91 |
+
else:
|
| 92 |
+
print("[plot] no training_log.jsonl yet -> skip reward curve")
|
| 93 |
+
|
| 94 |
+
# ---- 2. baseline comparison ----
|
| 95 |
+
files = {
|
| 96 |
+
"zero_shot (stub)": res / "baseline_zero_shot_stub.json",
|
| 97 |
+
"cot (stub)": res / "baseline_cot_stub.json",
|
| 98 |
+
"zero_shot (real LLM)": res / "baseline_zero_shot_real_subset.json",
|
| 99 |
+
"cot (real LLM)": res / "baseline_cot_real_subset.json",
|
| 100 |
+
"trained agent (real LLM)": res / "trained_agent.json",
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
rows: Dict[str, Dict[str, Any]] = {}
|
| 104 |
+
for label, path in files.items():
|
| 105 |
+
d = load_json(path)
|
| 106 |
+
if d is None:
|
| 107 |
+
continue
|
| 108 |
+
ov = d.get("overall", {})
|
| 109 |
+
rows[label] = {
|
| 110 |
+
"n": ov.get("n", 0),
|
| 111 |
+
"correct": ov.get("correct", 0),
|
| 112 |
+
"format": ov.get("format", 0),
|
| 113 |
+
"mean_reward": ov.get("mean_reward", 0.0),
|
| 114 |
+
"by_type": d.get("by_type", {}),
|
| 115 |
+
"backend": d.get("llm_backend", "unknown"),
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
comparison = {
|
| 119 |
+
"policies": rows,
|
| 120 |
+
"ranking_by_mean_reward": sorted(
|
| 121 |
+
rows.items(),
|
| 122 |
+
key=lambda kv: kv[1]["mean_reward"],
|
| 123 |
+
reverse=True,
|
| 124 |
+
),
|
| 125 |
+
}
|
| 126 |
+
(res / "comparison.json").write_text(
|
| 127 |
+
json.dumps(comparison, indent=2), encoding="utf-8"
|
| 128 |
+
)
|
| 129 |
+
print(f"[plot] wrote {res/'comparison.json'}")
|
| 130 |
+
|
| 131 |
+
# ---- 3. comparison bar chart ----
|
| 132 |
+
if rows:
|
| 133 |
+
labels = list(rows.keys())
|
| 134 |
+
means = [rows[l]["mean_reward"] for l in labels]
|
| 135 |
+
accs = [rows[l]["correct"] / max(1, rows[l]["n"]) for l in labels]
|
| 136 |
+
|
| 137 |
+
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
|
| 138 |
+
axes[0].barh(labels, means, color="#4c72b0")
|
| 139 |
+
axes[0].set_xlabel("mean reward")
|
| 140 |
+
axes[0].set_title("Mean reward by policy")
|
| 141 |
+
axes[0].grid(axis="x", alpha=0.3)
|
| 142 |
+
axes[0].invert_yaxis()
|
| 143 |
+
|
| 144 |
+
axes[1].barh(labels, accs, color="#55a868")
|
| 145 |
+
axes[1].set_xlabel("fraction correct")
|
| 146 |
+
axes[1].set_title("Correctness by policy")
|
| 147 |
+
axes[1].set_xlim(0, 1)
|
| 148 |
+
axes[1].grid(axis="x", alpha=0.3)
|
| 149 |
+
axes[1].invert_yaxis()
|
| 150 |
+
|
| 151 |
+
fig.tight_layout()
|
| 152 |
+
out = docs / "baseline_comparison.png"
|
| 153 |
+
fig.savefig(out, dpi=140)
|
| 154 |
+
plt.close(fig)
|
| 155 |
+
print(f"[plot] wrote {out}")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
if __name__ == "__main__":
|
| 159 |
+
main()
|