Repository navigation
Expand file tree
/
Copy pathbenchmark_models.py
More file actions
268 lines (235 loc) · 9.95 KB
/
Copy pathbenchmark_models.py
File metadata and controls
268 lines (235 loc) · 9.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python3
"""Benchmark Mario the Plumber across splits and baseline policies."""
from __future__ import annotations
import argparse
import csv
import json
from pathlib import Path
import random
from statistics import mean, pstdev
from typing import Any
from benchmark.catalog import MAX_STEPS, TASK_THRESHOLDS
from benchmark.runtime import runtime_summary
from inference import run_baseline
from models import PipelineDoctorAction
from server.pipeline_doctor_environment import PipelineDoctorEnvironment
def run_random_baseline(seed: int, *, split: str = "train") -> dict[str, Any]:
rng = random.Random(seed)
results: list[dict[str, Any]] = []
for task_id in sorted(TASK_THRESHOLDS):
env = PipelineDoctorEnvironment()
observation = env.reset(seed=seed, task_id=task_id, split=split)
for _ in range(MAX_STEPS[task_id]):
if env.state.done:
break
action = _random_action(env, observation, rng)
try:
observation = env.step(action)
except (ValueError, KeyError):
# Random actions can trigger invalid orchestration paths;
# treat as a no-op and continue.
pass
if env.state.done:
break
if not env.state.done:
observation = env.step(PipelineDoctorAction(action_id=15))
results.append(
{
"task_id": task_id,
"score": round(observation.current_score, 4),
"steps": env.state.step_count,
"success": bool(env.state.success),
"scenario_profile": observation.scenario_profile,
"heldout_profile_family": bool(observation.heldout_profile_family),
}
)
return {
"status": "complete",
"policy_mode": "random",
"scenario_split": split,
"results": results,
"average_score": round(mean(float(item["score"]) for item in results), 4),
}
def _random_action(
env: PipelineDoctorEnvironment,
observation: Any,
rng: random.Random,
) -> PipelineDoctorAction:
action_id = rng.randint(0, 19)
current_columns = list(env._current_frame().columns) # noqa: SLF001
if action_id in {3, 4, 5, 6, 7, 8, 9, 11, 12} and current_columns:
target_column = rng.choice(current_columns)
elif action_id == 0:
if env.state.task_id == 3 and env.state.active_table in {"orders", "customers"}:
target_column = "customers" if env.state.active_table == "orders" else "products"
elif env.state.task_id == 4 and env.state.active_table in {"orders", "products"}:
target_column = "products" if env.state.active_table == "orders" else "daily_summary"
elif env.state.task_id == 5 and env.state.active_table in {"source_orders", "catalog"}:
target_column = "catalog" if env.state.active_table == "source_orders" else "hourly_rollup"
else:
target_column = None
else:
target_column = None
new_name = None
if action_id == 12 and target_column:
new_name = f"{target_column}_v{rng.randint(1, 3)}"
column_order = None
if action_id == 13:
column_order = current_columns[:]
rng.shuffle(column_order)
return PipelineDoctorAction(
action_id=action_id,
target_column=target_column,
new_name=new_name,
column_order=column_order,
)
def summarize_runs(runs: list[dict[str, Any]]) -> dict[str, Any]:
summary: dict[str, Any] = {
"average_score_mean": round(mean(run["average_score"] for run in runs), 4),
"average_score_std": round(pstdev(run["average_score"] for run in runs), 4)
if len(runs) > 1
else 0.0,
"task_means": {},
"task_stds": {},
}
for task_id in sorted(TASK_THRESHOLDS):
scores = [
next(item["score"] for item in run["results"] if item["task_id"] == task_id)
for run in runs
]
summary["task_means"][f"task_{task_id}"] = round(mean(scores), 4)
summary["task_stds"][f"task_{task_id}"] = round(pstdev(scores), 4) if len(scores) > 1 else 0.0
return summary
def to_markdown(report: dict[str, Any]) -> str:
task_ids = sorted(TASK_THRESHOLDS)
task_headers = " | ".join(f"Task {task_id}" for task_id in task_ids)
lines = [
f"| Policy | Split | Avg Score | {task_headers} |",
"|---|---:|---:|" + "---:|" * len(task_ids),
]
for row in report["rows"]:
task_values = " | ".join(f"{row[f'task_{task_id}']:.4f}" for task_id in task_ids)
lines.append(
f"| {row['policy']} | {row['split']} | {row['average_score_mean']:.4f} | {task_values} |"
)
return "\n".join(lines)
def write_csv(report: dict[str, Any], path: str) -> None:
fieldnames = ["policy", "split", "average_score_mean", "average_score_std"]
for task_id in sorted(TASK_THRESHOLDS):
fieldnames.extend([f"task_{task_id}", f"task_{task_id}_std"])
with open(path, "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(report["rows"])
def summarize_profiles(raw_runs: dict[str, Any]) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for key, runs in raw_runs.items():
policy, split = key.split(":")
buckets: dict[tuple[int, str], list[float]] = {}
heldout_flags: dict[tuple[int, str], bool] = {}
for run in runs:
for result in run["results"]:
bucket_key = (int(result["task_id"]), str(result.get("scenario_profile", "baseline")))
buckets.setdefault(bucket_key, []).append(float(result["score"]))
heldout_flags[bucket_key] = bool(result.get("heldout_profile_family", False))
for (task_id, profile), scores in sorted(buckets.items()):
rows.append(
{
"policy": policy,
"split": split,
"task_id": task_id,
"scenario_profile": profile,
"heldout_profile_family": heldout_flags[(task_id, profile)],
"score_mean": round(mean(scores), 4),
"score_std": round(pstdev(scores), 4) if len(scores) > 1 else 0.0,
}
)
return rows
def generalization_gaps(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
gaps: list[dict[str, Any]] = []
task_ids = sorted(TASK_THRESHOLDS)
for policy in sorted({row["policy"] for row in rows}):
for task_id in task_ids:
train_row = next((row for row in rows if row["policy"] == policy and row["split"] == "train"), None)
eval_row = next((row for row in rows if row["policy"] == policy and row["split"] == "eval"), None)
if not train_row or not eval_row:
continue
train_score = float(train_row[f"task_{task_id}"])
eval_score = float(eval_row[f"task_{task_id}"])
gaps.append(
{
"policy": policy,
"task_id": task_id,
"train_score": round(train_score, 4),
"eval_score": round(eval_score, 4),
"gap": round(train_score - eval_score, 4),
}
)
return gaps
def main() -> None:
parser = argparse.ArgumentParser(description="Benchmark Mario the Plumber baselines.")
parser.add_argument("--seeds", nargs="+", type=int, default=[1, 2, 3, 4, 5])
parser.add_argument("--splits", nargs="+", default=["train", "eval"])
parser.add_argument(
"--policies",
nargs="+",
default=["random", "heuristic", "trained", "hybrid"],
choices=["random", "heuristic", "trained", "hybrid", "pure-llm"],
)
parser.add_argument("--model-name", default=None)
parser.add_argument("--format", choices=["json", "markdown"], default="markdown")
parser.add_argument("--json-out", default=None)
parser.add_argument("--csv-out", default=None)
args = parser.parse_args()
rows: list[dict[str, Any]] = []
raw_runs: dict[str, Any] = {}
runtime_meta = runtime_summary()
for split in args.splits:
for policy in args.policies:
runs = []
for seed in args.seeds:
if policy == "random":
run = run_random_baseline(seed, split=split)
else:
run = run_baseline(
seed=seed,
split=split,
policy_mode=policy,
model_name=args.model_name,
)
runs.append(run)
summary = summarize_runs(runs)
rows.append(
{
"policy": policy,
"split": split,
"average_score_mean": summary["average_score_mean"],
"average_score_std": summary["average_score_std"],
**{
key: value
for task_id in sorted(TASK_THRESHOLDS)
for key, value in (
(f"task_{task_id}", summary["task_means"][f"task_{task_id}"]),
(f"task_{task_id}_std", summary["task_stds"][f"task_{task_id}"]),
)
},
}
)
raw_runs[f"{policy}:{split}"] = runs
report = {
"rows": rows,
"runs": raw_runs,
"profile_rows": summarize_profiles(raw_runs),
"generalization_gaps": generalization_gaps(rows),
}
report["runtime"] = runtime_meta
if args.json_out:
Path(args.json_out).write_text(json.dumps(report, indent=2), encoding="utf-8")
if args.csv_out:
write_csv(report, args.csv_out)
if args.format == "json":
print(json.dumps(report, indent=2))
else:
print(to_markdown(report))
if __name__ == "__main__":
main()