Pranjal Parashar commited on
Commit
1c25e79
·
unverified ·
1 Parent(s): 91aacc4

training w grpo

Browse files
Files changed (3) hide show
  1. README.md +355 -1
  2. flowos_grpo_kaggle.ipynb +236 -0
  3. plot_rewards.py +132 -0
README.md CHANGED
@@ -7,4 +7,358 @@ sdk: docker
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  pinned: false
8
  ---
9
 
10
+ # FlowOS V2
11
+
12
+ FlowOS V2 is an OpenEnv environment for training LLM agents to build and repair realistic data-platform workflows. Instead of solving a toy grid world, the agent has to read workspace files, inspect schemas, write pipeline YAML and SQL, run validators, interpret runtime failures, and submit a working warehouse report.
13
+
14
+ - Hugging Face Space: [praanjal-flowos-v2.hf.space](https://praanjal-flowos-v2.hf.space)
15
+ - OpenEnv manifest: [openenv.yaml](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/openenv.yaml)
16
+ - Training scripts:
17
+ - [collect_traces.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/collect_traces.py)
18
+ - [train_sft.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/train_sft.py)
19
+ - [train.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/train.py)
20
+ - [eval.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/eval.py)
21
+ - Plotting script: [plot_metrics.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/plot_metrics.py)
22
+ - Blog / writeup: `ADD_HF_BLOG_LINK_HERE`
23
+ - Video / slides: `ADD_VIDEO_OR_SLIDES_LINK_HERE`
24
+
25
+ ## Problem
26
+
27
+ LLM agents still struggle with one of the most common production engineering loops:
28
+
29
+ 1. understand a partially specified data task,
30
+ 2. create the right pipeline artifacts,
31
+ 3. run the workflow,
32
+ 4. interpret runtime failures,
33
+ 5. repair the broken pieces without violating downstream contracts.
34
+
35
+ Most existing agent benchmarks either stop at code generation or use abstract environments with low-stakes actions. FlowOS instead targets a concrete capability gap: can an LLM learn to behave like a junior-to-mid-level data platform engineer working in a shared production workspace?
36
+
37
+ We care about this because modern analytics teams constantly perform exactly this pattern:
38
+ - generate ingestion or reporting pipelines from imperfect specs,
39
+ - debug warehouse jobs and broken transforms,
40
+ - preserve schema contracts while fixing failures,
41
+ - coordinate between different responsibilities like “builder” and “fixer”.
42
+
43
+ ## Environment
44
+
45
+ FlowOS V2 is built on the latest OpenEnv stack and exposed as a remote environment on Hugging Face Spaces.
46
+
47
+ The current submission focuses on a simulation task family called `simulate_csv_report_workflow`. Each episode places the agent in a small but realistic workspace with:
48
+
49
+ - a source CSV,
50
+ - runtime instructions,
51
+ - schema files,
52
+ - editable pipeline targets:
53
+ - `pipelines/report_job.yaml`
54
+ - `sql/load_raw.sql`
55
+ - `sql/build_table.sql`
56
+ - `sql/report_view.sql`
57
+
58
+ The environment then runs those artifacts against a local DuckDB-backed execution runtime and returns:
59
+
60
+ - runtime success / failure,
61
+ - execution logs,
62
+ - output schema,
63
+ - preview rows,
64
+ - validator results.
65
+
66
+ ### What the agent sees
67
+
68
+ On each step, the agent receives:
69
+
70
+ - the developer request,
71
+ - workspace summary,
72
+ - known files,
73
+ - editable targets,
74
+ - visible schema assets,
75
+ - validator names,
76
+ - current role (`builder` or `fixer`),
77
+ - runtime feedback from prior edits.
78
+
79
+ ### What the agent can do
80
+
81
+ The agent can:
82
+
83
+ - `read_file`
84
+ - `inspect_schema`
85
+ - `edit_file`
86
+ - `run_validator`
87
+ - `submit_workspace`
88
+
89
+ ### What gets rewarded
90
+
91
+ The reward and grading logic combines:
92
+
93
+ - investigation quality,
94
+ - artifact completeness,
95
+ - runtime success,
96
+ - final schema correctness,
97
+ - summary quality,
98
+ - successful submission.
99
+
100
+ This is implemented through OpenEnv-compatible state, validator, and grader flows in:
101
+
102
+ - [tasks.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/tasks.py)
103
+ - [graders.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/graders.py)
104
+ - [runtime.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/runtime.py)
105
+ - [server/developer_control_room_environment.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/server/developer_control_room_environment.py)
106
+
107
+ ## Scenarios
108
+
109
+ The simulation task currently has 7 deterministic scenarios:
110
+
111
+ ### Pipeline generation
112
+
113
+ - `SIM-001`: build a customer daily sales report
114
+ - `SIM-002`: build a subscription daily report
115
+ - `SIM-003`: build an inventory movement report
116
+
117
+ ### Pipeline repair
118
+
119
+ - `SIM-004`: repair a broken customer-order build SQL
120
+ - `SIM-005`: repair a broken subscription report contract
121
+ - `SIM-006`: repair a broken inventory report schema
122
+ - `SIM-007`: fix a builder-created returns pipeline after runtime failure
123
+
124
+ This mix was chosen to test both:
125
+
126
+ - first-pass workflow construction,
127
+ - and second-pass repair under runtime feedback.
128
+
129
+ ## Why this environment is interesting
130
+
131
+ We think this environment is novel because it sits between code generation and full production ops:
132
+
133
+ - it is not just “write SQL”,
134
+ - it is not just “fix a syntax bug”,
135
+ - and it is not a toy planning problem.
136
+
137
+ The agent has to coordinate file creation, schema understanding, runtime-aware debugging, and role-aware behavior inside a shared workspace. That makes it a better fit for training practical engineering agents than many one-shot coding benchmarks.
138
+
139
+ ## Training pipeline
140
+
141
+ We currently support two training directions:
142
+
143
+ ### 1. Stable path: supervised fine-tuning
144
+
145
+ This is the main path we are using for reproducible training evidence.
146
+
147
+ 1. Collect teacher traces from the environment:
148
+
149
+ ```bash
150
+ python collect_traces.py \
151
+ --env-url https://praanjal-flowos-v2.hf.space \
152
+ --task-scope simulate_csv_report_workflow \
153
+ --dataset-size 28 \
154
+ --max-turns 12 \
155
+ --output-dir outputs/sft_traces_v2
156
+ ```
157
+
158
+ 2. Train a LoRA SFT policy:
159
+
160
+ ```bash
161
+ CUDA_VISIBLE_DEVICES=0 python train_sft.py \
162
+ --dataset-path outputs/sft_traces_v2/traces.jsonl \
163
+ --model-id Qwen/Qwen2.5-1.5B-Instruct \
164
+ --output-dir outputs/flowos-sft-v2 \
165
+ --num-epochs 2 \
166
+ --per-device-train-batch-size 1 \
167
+ --gradient-accumulation-steps 4 \
168
+ --max-seq-length 1024 \
169
+ --load-in-4bit \
170
+ --gradient-checkpointing
171
+ ```
172
+
173
+ ### 2. Experimental path: GRPO / TRL
174
+
175
+ We also have an RL-style training entrypoint in [train.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/train.py) for future work, but the current submission story is centered on the stable SFT path because it is the most reproducible on commodity GPUs.
176
+
177
+ ## Results
178
+
179
+ The main question for this environment is simple:
180
+
181
+ **Does a trained policy behave better than an untrained one?**
182
+
183
+ To answer that, we compare:
184
+
185
+ - the base model,
186
+ - the fine-tuned checkpoint,
187
+ - and optionally the same evaluation with fallback disabled for a stricter policy-only check.
188
+
189
+ ### Evaluation command
190
+
191
+ ```bash
192
+ python eval.py \
193
+ --model-id Qwen/Qwen2.5-1.5B-Instruct \
194
+ --checkpoint-path outputs/flowos-sft-v2 \
195
+ --env-url https://praanjal-flowos-v2.hf.space \
196
+ --task-scope simulate_csv_report_workflow \
197
+ --episodes 7 \
198
+ --max-turns 12 \
199
+ --results-dir outputs/eval_compare_v2
200
+ ```
201
+
202
+ ### Plot generation
203
+
204
+ ```bash
205
+ python plot_metrics.py \
206
+ --train-metrics outputs/flowos-sft-v2/training_metrics.csv \
207
+ --eval-metrics outputs/eval_compare_v2/eval_episode_metrics.csv \
208
+ --output-dir outputs/plots_v2
209
+ ```
210
+
211
+ ### Current evidence
212
+
213
+ The repository now saves:
214
+
215
+ - training loss curves,
216
+ - per-episode evaluation metrics,
217
+ - average reward / score / solved-rate comparisons,
218
+ - fallback-step and valid-model-step comparisons,
219
+ - generated pipeline artifacts for inspection.
220
+
221
+ Replace the placeholders below with the final PNGs from your latest run:
222
+
223
+ - `ADD_TRAINING_LOSS_PLOT_HERE`
224
+ - `ADD_EVAL_SCORE_PLOT_HERE`
225
+ - `ADD_EVAL_SOLVED_RATE_PLOT_HERE`
226
+ - `ADD_BASELINE_VS_TRAINED_TABLE_HERE`
227
+
228
+ Recommended final README embed format:
229
+
230
+ ```md
231
+ ![SFT training loss](assets/plots/sft_training_loss.png)
232
+ ![Average score by policy](assets/plots/eval_avg_score.png)
233
+ ![Solved rate by policy](assets/plots/eval_solved_rate.png)
234
+ ```
235
+
236
+ ## How to try the environment
237
+
238
+ ### Run the Space locally
239
+
240
+ ```bash
241
+ uv run server
242
+ ```
243
+
244
+ ### Run a quick environment check
245
+
246
+ ```bash
247
+ python -c "from developer_control_room.server.developer_control_room_environment import DeveloperControlRoomEnvironment as E; env=E(); obs=env.reset(task_id='simulate_csv_report_workflow', scenario_index=0); print(obs.scenario_id, obs.active_role, obs.known_files)"
248
+ ```
249
+
250
+ ### Run evaluation
251
+
252
+ ```bash
253
+ python eval.py \
254
+ --model-id Qwen/Qwen2.5-1.5B-Instruct \
255
+ --env-url https://praanjal-flowos-v2.hf.space \
256
+ --task-scope simulate_csv_report_workflow \
257
+ --episodes 1 \
258
+ --max-turns 12 \
259
+ --debug-actions
260
+ ```
261
+
262
+ ## Submission materials
263
+
264
+ Please link all final materials here before submission:
265
+
266
+ - Hugging Face Space: [https://praanjal-flowos-v2.hf.space](https://praanjal-flowos-v2.hf.space)
267
+ - Hugging Face blog: `ADD_HF_BLOG_LINK_HERE`
268
+ - Video / slides: `ADD_VIDEO_OR_SLIDES_LINK_HERE`
269
+ - Colab notebook: `ADD_COLAB_LINK_HERE`
270
+
271
+ ## Future multi-agent architecture
272
+
273
+ The current environment already has the beginnings of role-aware coordination through the `builder` / `fixer` split. If we extend this into a fuller multi-agent setup with specialized agents like:
274
+
275
+ - database agent,
276
+ - deployment agent,
277
+ - pipeline authoring agent,
278
+ - incident / fixer agent,
279
+
280
+ then the architecture should change in a few important ways.
281
+
282
+ ### 1. Role-specific observations and action spaces
283
+
284
+ Today, all roles see roughly the same workspace shape. In a fuller multi-agent system we would want:
285
+
286
+ - role-specific observations,
287
+ - role-specific allowed actions,
288
+ - role-specific reward components.
289
+
290
+ Example:
291
+ - database agent should inspect schemas, SQL, and warehouse outputs,
292
+ - deployment agent should inspect configs, schedules, and orchestrator state,
293
+ - fixer agent should receive richer runtime and incident logs.
294
+
295
+ ### 2. Shared workspace plus shared memory
296
+
297
+ We already have a shared workspace. A multi-agent version would also need explicit shared memory for:
298
+
299
+ - handoff notes,
300
+ - failure summaries,
301
+ - pending tasks,
302
+ - ownership / lock state for files or resources.
303
+
304
+ That prevents agents from overwriting one another blindly and makes coordination trainable.
305
+
306
+ ### 3. Agent routing / orchestration layer
307
+
308
+ We would need a coordinator that decides:
309
+
310
+ - which specialist acts next,
311
+ - whether the current role should continue,
312
+ - when to escalate from builder to fixer,
313
+ - when to stop and submit.
314
+
315
+ This could be:
316
+
317
+ - a learned scheduler,
318
+ - a rule-based router,
319
+ - or another LLM agent acting as a planner.
320
+
321
+ ### 4. Role-conditioned reward design
322
+
323
+ The reward function should separate:
324
+
325
+ - local role success,
326
+ - global workflow success,
327
+ - coordination quality.
328
+
329
+ For example:
330
+ - builder gets rewarded for producing a coherent first-pass pipeline,
331
+ - fixer gets rewarded for resolving runtime failures quickly,
332
+ - coordinator gets rewarded for minimizing unnecessary turns and handoffs.
333
+
334
+ ### 5. Runtime modularization
335
+
336
+ As specialized agents grow, the runtime should stop looking like a single flat executor and instead expose modular subsystems:
337
+
338
+ - warehouse / DuckDB runtime,
339
+ - deployment / orchestrator runtime,
340
+ - validator runtime,
341
+ - artifact registry.
342
+
343
+ That would let different specialist agents act on different subsystems while still contributing to a shared final score.
344
+
345
+ ### 6. Explicit communication channels
346
+
347
+ If we want the multi-agent behavior to be a real benchmark and not just sequential role labels, we should add:
348
+
349
+ - message passing or notes between agents,
350
+ - structured handoff actions,
351
+ - maybe role-specific submission or escalation actions.
352
+
353
+ That would make coordination itself part of what gets trained.
354
+
355
+ ## Why this matters
356
+
357
+ Production AI agents will not succeed only by writing one perfect file. They will need to:
358
+
359
+ - work in partially broken systems,
360
+ - preserve contracts under pressure,
361
+ - coordinate across roles,
362
+ - and improve through training rather than prompt tricks alone.
363
+
364
+ FlowOS V2 is our attempt to make that trainable in a compact but realistic OpenEnv environment.
flowos_grpo_kaggle.ipynb ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# FlowOS V2 — GRPO Training on Kaggle\n",
8
+ "\n",
9
+ "This notebook follows the same high-level pattern as the SF winner notebook:\n",
10
+ "\n",
11
+ "1. Install dependencies\n",
12
+ "2. Clone the repo\n",
13
+ "3. Smoke test the OpenEnv server on HF Space\n",
14
+ "4. Run GRPO training with `train.py`\n",
15
+ "5. Plot reward curves from `reward_log.csv`\n",
16
+ "6. Evaluate base vs trained policy\n",
17
+ "\n",
18
+ "Environment: [praanjal-flowos-v2.hf.space](https://praanjal-flowos-v2.hf.space)\n"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": null,
24
+ "metadata": {},
25
+ "outputs": [],
26
+ "source": [
27
+ "!pip install -q -U pip\n",
28
+ "!pip install -q \\\n",
29
+ " \"trl>=0.11.0\" \\\n",
30
+ " \"transformers>=4.45.0\" \\\n",
31
+ " \"datasets>=2.21.0\" \\\n",
32
+ " \"peft>=0.13.0\" \\\n",
33
+ " \"accelerate>=0.34.0\" \\\n",
34
+ " \"duckdb>=1.1.0\" \\\n",
35
+ " \"openenv-core[core]>=0.2.2\" \\\n",
36
+ " \"openai>=1.52.0\" \\\n",
37
+ " \"requests>=2.32.0\" \\\n",
38
+ " \"python-dotenv>=1.0.1\" \\\n",
39
+ " \"matplotlib\" \\\n",
40
+ " \"numpy\""
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "execution_count": null,
46
+ "metadata": {},
47
+ "outputs": [],
48
+ "source": [
49
+ "!git clone https://github.com/pranjalparashar/FlowOS_v2.git /kaggle/working/FlowOS_v2\n",
50
+ "%cd /kaggle/working/FlowOS_v2/developer_control_room\n",
51
+ "!git pull"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "execution_count": null,
57
+ "metadata": {},
58
+ "outputs": [],
59
+ "source": [
60
+ "ENV_URL = \"https://praanjal-flowos-v2.hf.space\"\n",
61
+ "MODEL_ID = \"Qwen/Qwen2.5-0.5B-Instruct\"\n",
62
+ "OUTPUT_DIR = \"outputs/flowos-grpo-kaggle\"\n",
63
+ "DATASET_SIZE = 8\n",
64
+ "NUM_GENERATIONS = 2\n",
65
+ "MAX_TURNS = 8\n",
66
+ "\n",
67
+ "print(\"ENV_URL:\", ENV_URL)\n",
68
+ "print(\"MODEL_ID:\", MODEL_ID)"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": null,
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "!python -c \"from client import DeveloperControlRoomEnv; import asyncio; \\\n",
78
+ "async def main(): \\\n",
79
+ " env=DeveloperControlRoomEnv(base_url='https://praanjal-flowos-v2.hf.space'); \\\n",
80
+ " await env.connect(); \\\n",
81
+ " result=await env.reset(task_id='simulate_csv_report_workflow', scenario_index=0); \\\n",
82
+ " print(result.observation.scenario_id, result.observation.active_role); \\\n",
83
+ " await env.close(); \\\n",
84
+ "asyncio.run(main())\""
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "markdown",
89
+ "metadata": {},
90
+ "source": [
91
+ "## GRPO Train\n",
92
+ "\n",
93
+ "This is the first conservative GRPO smoke test. Once this works, scale up to:\n",
94
+ "\n",
95
+ "- `MODEL_ID = \"Qwen/Qwen2.5-1.5B-Instruct\"`\n",
96
+ "- `DATASET_SIZE = 12`\n",
97
+ "- `MAX_TURNS = 10`\n"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": null,
103
+ "metadata": {},
104
+ "outputs": [],
105
+ "source": [
106
+ "!CUDA_VISIBLE_DEVICES=0 python train.py \\\n",
107
+ " --model-id {MODEL_ID} \\\n",
108
+ " --env-url {ENV_URL} \\\n",
109
+ " --task-scope simulate_csv_report_workflow \\\n",
110
+ " --dataset-size {DATASET_SIZE} \\\n",
111
+ " --num-generations {NUM_GENERATIONS} \\\n",
112
+ " --num-epochs 1 \\\n",
113
+ " --max-turns {MAX_TURNS} \\\n",
114
+ " --max-new-tokens 96 \\\n",
115
+ " --per-device-train-batch-size 1 \\\n",
116
+ " --gradient-accumulation-steps 4 \\\n",
117
+ " --save-steps 10 \\\n",
118
+ " --logging-steps 1 \\\n",
119
+ " --output-dir {OUTPUT_DIR} \\\n",
120
+ " --report-to none"
121
+ ]
122
+ },
123
+ {
124
+ "cell_type": "markdown",
125
+ "metadata": {},
126
+ "source": [
127
+ "## Reward Curves\n",
128
+ "\n",
129
+ "This mirrors the SF winner workflow: train writes `reward_log.csv`, then we plot it."
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "execution_count": null,
135
+ "metadata": {},
136
+ "outputs": [],
137
+ "source": [
138
+ "!python plot_rewards.py {OUTPUT_DIR}/reward_log.csv --out {OUTPUT_DIR}/reward_curve.png"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "execution_count": null,
144
+ "metadata": {},
145
+ "outputs": [],
146
+ "source": [
147
+ "import matplotlib.pyplot as plt\n",
148
+ "from matplotlib.image import imread\n",
149
+ "\n",
150
+ "img = imread(f\"{OUTPUT_DIR}/reward_curve.png\")\n",
151
+ "fig, ax = plt.subplots(figsize=(12, 6))\n",
152
+ "ax.imshow(img)\n",
153
+ "ax.axis(\"off\")\n",
154
+ "plt.show()"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "markdown",
159
+ "metadata": {},
160
+ "source": [
161
+ "## Evaluate Base vs Trained"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": null,
167
+ "metadata": {},
168
+ "outputs": [],
169
+ "source": [
170
+ "!python eval.py \\\n",
171
+ " --model-id {MODEL_ID} \\\n",
172
+ " --checkpoint-path /kaggle/working/FlowOS_v2/developer_control_room/{OUTPUT_DIR} \\\n",
173
+ " --env-url {ENV_URL} \\\n",
174
+ " --task-scope simulate_csv_report_workflow \\\n",
175
+ " --episodes 7 \\\n",
176
+ " --max-turns 12 \\\n",
177
+ " --results-dir outputs/eval_compare_grpo"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "execution_count": null,
183
+ "metadata": {},
184
+ "outputs": [],
185
+ "source": [
186
+ "!cat outputs/eval_compare_grpo/eval_summary.json"
187
+ ]
188
+ },
189
+ {
190
+ "cell_type": "markdown",
191
+ "metadata": {},
192
+ "source": [
193
+ "## Optional: Strict Eval Without Fallback"
194
+ ]
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "execution_count": null,
199
+ "metadata": {},
200
+ "outputs": [],
201
+ "source": [
202
+ "!python eval.py \\\n",
203
+ " --model-id {MODEL_ID} \\\n",
204
+ " --checkpoint-path /kaggle/working/FlowOS_v2/developer_control_room/{OUTPUT_DIR} \\\n",
205
+ " --env-url {ENV_URL} \\\n",
206
+ " --task-scope simulate_csv_report_workflow \\\n",
207
+ " --episodes 7 \\\n",
208
+ " --max-turns 12 \\\n",
209
+ " --disable-fallback \\\n",
210
+ " --results-dir outputs/eval_compare_grpo_nofallback"
211
+ ]
212
+ },
213
+ {
214
+ "cell_type": "code",
215
+ "execution_count": null,
216
+ "metadata": {},
217
+ "outputs": [],
218
+ "source": [
219
+ "!cat outputs/eval_compare_grpo_nofallback/eval_summary.json"
220
+ ]
221
+ }
222
+ ],
223
+ "metadata": {
224
+ "kernelspec": {
225
+ "display_name": "Python 3",
226
+ "language": "python",
227
+ "name": "python3"
228
+ },
229
+ "language_info": {
230
+ "name": "python",
231
+ "version": "3.12"
232
+ }
233
+ },
234
+ "nbformat": 4,
235
+ "nbformat_minor": 5
236
+ }
plot_rewards.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Plot GRPO training rewards from reward_log.csv in the SF winner style."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import sys
9
+ import time
10
+ from pathlib import Path
11
+
12
+
13
+ def find_latest_csv() -> Path | None:
14
+ csvs = sorted(Path("outputs").glob("*/reward_log.csv"), key=lambda p: p.stat().st_mtime, reverse=True)
15
+ if csvs:
16
+ return csvs[0]
17
+ if Path("reward_log.csv").exists():
18
+ return Path("reward_log.csv")
19
+ return None
20
+
21
+
22
+ def load_csv(path: Path) -> tuple[list[int], list[float], list[float], list[float]]:
23
+ episodes: list[int] = []
24
+ totals: list[float] = []
25
+ scores: list[float] = []
26
+ solved: list[float] = []
27
+ with path.open() as handle:
28
+ reader = csv.DictReader(handle)
29
+ for row in reader:
30
+ if not row.get("episode"):
31
+ continue
32
+ episodes.append(int(row["episode"]))
33
+ totals.append(float(row.get("total_reward", 0.0)))
34
+ scores.append(float(row.get("score", 0.0)))
35
+ solved.append(1.0 if str(row.get("solved", "")).lower() == "true" else 0.0)
36
+ return episodes, totals, scores, solved
37
+
38
+
39
+ def rolling_avg(values: list[float], window: int = 10) -> list[float]:
40
+ if not values:
41
+ return []
42
+ window = min(window, len(values))
43
+ return [sum(values[max(0, i - window + 1): i + 1]) / min(i + 1, window) for i in range(len(values))]
44
+
45
+
46
+ def plot(path: Path, save_path: Path | None = None) -> None:
47
+ import matplotlib
48
+
49
+ matplotlib.use("Agg")
50
+ import matplotlib.pyplot as plt
51
+
52
+ episodes, totals, scores, solved = load_csv(path)
53
+ if not episodes:
54
+ print("No data yet.")
55
+ return
56
+
57
+ window = min(10, len(episodes))
58
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), sharex=True)
59
+
60
+ ax1.plot(episodes, totals, alpha=0.25, color="blue", marker="o", markersize=3, label="Per episode reward")
61
+ ax1.plot(episodes, rolling_avg(totals, window), color="blue", linewidth=2.5, label=f"Rolling avg ({window})")
62
+ ax1.axhline(y=0, color="gray", linestyle="--", alpha=0.5)
63
+ ax1.set_ylabel("Total Reward")
64
+ ax1.set_title(f"FlowOS — GRPO Training Rewards ({len(episodes)} episodes)")
65
+ ax1.legend()
66
+ ax1.grid(True, alpha=0.3)
67
+
68
+ ax2.plot(episodes, rolling_avg(scores, window), color="orange", linewidth=2, label="Score (rolling)")
69
+ ax2.plot(episodes, rolling_avg(solved, window), color="green", linewidth=2, label="Solved rate (rolling)")
70
+ ax2.set_xlabel("Episode")
71
+ ax2.set_ylabel("Metric")
72
+ ax2.set_ylim(min(0.0, min(scores + solved, default=0.0)) - 0.05, 1.05)
73
+ ax2.legend()
74
+ ax2.grid(True, alpha=0.3)
75
+
76
+ plt.tight_layout()
77
+ out = save_path or path.with_suffix(".png")
78
+ plt.savefig(out, dpi=150)
79
+ plt.close()
80
+ print(f"Plot saved to {out}")
81
+ print(f"\nEpisodes: {len(episodes)}")
82
+ print(f"Latest reward: {totals[-1]:.2f}")
83
+ print(f"Avg (last 10): {sum(totals[-10:]) / min(10, len(totals)):.2f}")
84
+ print(f"Best reward: {max(totals):.2f}")
85
+ print(f"Worst reward: {min(totals):.2f}")
86
+
87
+
88
+ def print_table(path: Path) -> None:
89
+ episodes, totals, scores, solved = load_csv(path)
90
+ if not episodes:
91
+ print("No data yet.")
92
+ return
93
+
94
+ print(f"\n{'Ep':>4} | {'Reward':>8} | {'Score':>7} | {'Solved':>6} | {'Avg(10)':>8}")
95
+ print("-" * 47)
96
+ for i in range(len(episodes)):
97
+ avg10 = sum(totals[max(0, i - 9): i + 1]) / min(i + 1, 10)
98
+ marker = " *" if totals[i] == max(totals[: i + 1]) else ""
99
+ print(f"{episodes[i]:>4} | {totals[i]:>8.2f} | {scores[i]:>7.2f} | {solved[i]:>6.0f} | {avg10:>8.2f}{marker}")
100
+
101
+
102
+ def main() -> None:
103
+ parser = argparse.ArgumentParser(description="Plot FlowOS GRPO rewards")
104
+ parser.add_argument("csv_path", nargs="?", help="Path to reward_log.csv")
105
+ parser.add_argument("--live", action="store_true", help="Refresh every 30 seconds")
106
+ parser.add_argument("--table", action="store_true", help="Print ASCII table instead of plot")
107
+ parser.add_argument("--out", default=None, help="Output image path")
108
+ args = parser.parse_args()
109
+
110
+ path = Path(args.csv_path) if args.csv_path else find_latest_csv()
111
+ if not path or not path.exists():
112
+ print("No reward_log.csv found. Run training first or specify path.")
113
+ sys.exit(1)
114
+
115
+ print(f"Reading: {path}")
116
+ if args.table:
117
+ print_table(path)
118
+ return
119
+
120
+ if args.live:
121
+ while True:
122
+ try:
123
+ plot(path, Path(args.out) if args.out else None)
124
+ time.sleep(30)
125
+ except KeyboardInterrupt:
126
+ break
127
+ else:
128
+ plot(path, Path(args.out) if args.out else None)
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()