forked from EulerFrog/mpn-rl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_experiments.py
More file actions
350 lines (299 loc) · 11.3 KB
/
Copy pathquery_experiments.py
File metadata and controls
350 lines (299 loc) · 11.3 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""
Each experiment writes its own metrics.jsonl (one JSON line per eval step)
and config.json. This script uses an in-memory DuckDB to glob all those
files on demand, so queries always reflect the current state of running
experiments with no locking or concurrency issues.
Usage:
# Live summary — works while jobs are running
python query_experiments.py list
python query_experiments.py best --env GoNogo-v0
python query_experiments.py compare --model-type mpn
python query_experiments.py sql "SELECT ..."
"""
import argparse
import json
from datetime import datetime
from pathlib import Path
import duckdb
import pandas as pd
from mpn_rl.experiment import find_experiment_files
# ---------------------------------------------------------------------------
# Live DuckDB connection (reads files directly, always up-to-date)
# ---------------------------------------------------------------------------
def _sql_list(files: list[Path]) -> str:
return "[" + ", ".join("'" + str(f) + "'" for f in files) + "]"
def _live_con(experiments_dir: Path | None) -> duckdb.DuckDBPyConnection:
"""Return an in-memory DuckDB with views over live experiment files.
Scans config.json/metrics.jsonl for every experiment — ad-hoc experiments
under experiments/ and sweep experiments under results/<name>/experiments/ —
or a single flat experiments_dir when one is given.
"""
con = duckdb.connect()
metrics_files = find_experiment_files("metrics.jsonl", experiments_dir)
config_files = find_experiment_files("config.json", experiments_dir)
if metrics_files:
con.execute(f"""
CREATE VIEW training_history AS
SELECT experiment_name, frame, reward, length, loss,
oracle_reward, pct_oracle
FROM read_ndjson(
{_sql_list(metrics_files)},
columns = {{
experiment_name: 'VARCHAR',
frame: 'INTEGER',
reward: 'DOUBLE',
length: 'INTEGER',
loss: 'DOUBLE',
oracle_reward: 'DOUBLE',
pct_oracle: 'DOUBLE'
}},
ignore_errors = true
)
""")
else:
con.execute("""
CREATE VIEW training_history AS
SELECT NULL::VARCHAR as experiment_name, NULL::INTEGER as frame,
NULL::DOUBLE as reward, NULL::INTEGER as length,
NULL::DOUBLE as loss,
NULL::DOUBLE as oracle_reward, NULL::DOUBLE as pct_oracle
WHERE false
""")
if config_files:
con.execute(f"""
CREATE VIEW experiments AS
SELECT *
FROM read_json_auto(
{_sql_list(config_files)},
ignore_errors = true
)
""")
else:
con.execute("""
CREATE VIEW experiments AS
SELECT NULL::VARCHAR as experiment_name WHERE false
""")
return con
def _query(sql: str, experiments_dir: Path | None) -> pd.DataFrame:
con = _live_con(experiments_dir)
return con.execute(sql).fetchdf()
# ---------------------------------------------------------------------------
# Query commands (all use live DuckDB file scanning)
# ---------------------------------------------------------------------------
def cmd_list(args):
df = _query(
"""
SELECT
e.experiment_name,
COALESCE(e.algorithm, 'dqn') AS algorithm,
e.model_type,
e.env_name,
e.learning_rate AS lr,
MAX(h.frame) AS latest_frame,
ROUND(MAX(h.reward), 2) AS best_reward
FROM experiments e
LEFT JOIN training_history h USING (experiment_name)
GROUP BY e.experiment_name, e.algorithm, e.model_type, e.env_name, e.learning_rate
ORDER BY MAX(h.frame) DESC NULLS LAST
""",
args.experiments_dir,
)
print(df.to_string(index=False))
def cmd_best(args):
filters = []
if args.env:
filters.append(f"e.env_name = '{args.env}'")
if args.algorithm:
filters.append(f"COALESCE(e.algorithm, 'dqn') = '{args.algorithm}'")
where = ("WHERE " + " AND ".join(filters)) if filters else ""
df = _query(
f"""
SELECT
e.experiment_name,
COALESCE(e.algorithm, 'dqn') AS algorithm,
e.model_type,
e.env_name,
e.learning_rate AS lr,
ROUND(MAX(h.reward), 4) AS best_reward,
ROUND(AVG(h.reward), 4) AS avg_reward
FROM experiments e
JOIN training_history h USING (experiment_name)
{where}
GROUP BY e.experiment_name, e.algorithm, e.model_type, e.env_name, e.learning_rate
ORDER BY best_reward DESC
LIMIT {args.limit}
""",
args.experiments_dir,
)
print(df.to_string(index=False))
def cmd_compare(args):
filters = []
if args.env:
filters.append(f"e.env_name = '{args.env}'")
if args.model_type:
filters.append(f"e.model_type = '{args.model_type}'")
if args.algorithm:
filters.append(f"COALESCE(e.algorithm, 'dqn') = '{args.algorithm}'")
where = ("WHERE " + " AND ".join(filters)) if filters else ""
df = _query(
f"""
SELECT
COALESCE(e.algorithm, 'dqn') AS algorithm,
e.model_type,
e.env_name,
e.learning_rate AS lr,
e.hidden_dim,
COUNT(DISTINCT e.experiment_name) AS num_experiments,
ROUND(AVG(h.reward), 4) AS avg_reward,
ROUND(STDDEV(h.reward), 4) AS std_reward
FROM experiments e
JOIN training_history h USING (experiment_name)
{where}
GROUP BY e.algorithm, e.model_type, e.env_name, e.learning_rate, e.hidden_dim
ORDER BY e.env_name, avg_reward DESC
""",
args.experiments_dir,
)
print(df.to_string(index=False))
def cmd_today(args):
today = datetime.now().strftime("%Y-%m-%d")
rows = []
for config_path in sorted(
find_experiment_files("config.json", args.experiments_dir)
):
with open(config_path) as f:
config = json.load(f)
created_at = config.get("created_at", "")
if not created_at.startswith(today):
continue
exp_name = config.get("experiment_name", config_path.parent.name)
algorithm = config.get("algorithm", "dqn")
model_type = config.get("model_type", "?")
utd = config.get("utd", "?")
lr = config.get("learning_rate", "?")
hidden_dim = config.get("hidden_dim", "?")
num_layers = config.get("num_layers", "?")
metrics_path = config_path.parent / "metrics.jsonl"
if not metrics_path.exists():
rows.append(
dict(
experiment_name=exp_name,
algorithm=algorithm,
model_type=model_type,
utd=utd,
lr=lr,
hidden_dim=hidden_dim,
num_layers=num_layers,
latest_frame=None,
last3_avg_reward=None,
last10_avg_reward=None,
total_avg_reward=None,
best_reward=None,
)
)
continue
rewards, frames = [], []
with open(metrics_path) as f:
for line in f:
line = line.strip()
if not line:
continue
try:
entry = json.loads(line)
rewards.append(entry["reward"])
frames.append(entry["frame"])
except (json.JSONDecodeError, KeyError):
continue
if not rewards:
rows.append(
dict(
experiment_name=exp_name,
algorithm=algorithm,
model_type=model_type,
utd=utd,
lr=lr,
hidden_dim=hidden_dim,
num_layers=num_layers,
latest_frame=None,
last3_avg_reward=None,
last10_avg_reward=None,
total_avg_reward=None,
best_reward=None,
)
)
continue
last3 = rewards[-3:]
last10 = rewards[-10:]
rows.append(
dict(
experiment_name=exp_name,
algorithm=algorithm,
model_type=model_type,
utd=utd,
lr=lr,
hidden_dim=hidden_dim,
num_layers=num_layers,
latest_frame=frames[-1],
last3_avg_reward=round(sum(last3) / len(last3), 4),
last10_avg_reward=round(sum(last10) / len(last10), 4),
total_avg_reward=round(sum(rewards) / len(rewards), 4),
best_reward=round(max(rewards), 4),
)
)
if not rows:
print(f"No experiments found for today ({today}).")
return
df = pd.DataFrame(rows).sort_values(["algorithm", "model_type", "experiment_name"])
print(f"Experiments from {today}:\n")
print(df.to_string(index=False))
def cmd_sql(args):
df = _query(args.query, args.experiments_dir)
print(df.to_string(index=False))
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="Query MPN-RL experiments (live file scanning)"
)
parser.add_argument(
"--experiments-dir",
type=Path,
default=None,
help="Scan a single experiments dir; default scans "
"experiments/ and results/*/experiments/",
)
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser(
"list", help="List all experiments with latest frame and best reward"
)
p_best = sub.add_parser("best", help="Best reward per experiment")
p_best.add_argument("--env", default=None)
p_best.add_argument(
"--algorithm", default=None, help="Filter by algorithm: dqn or a2c"
)
p_best.add_argument("--limit", type=int, default=20)
p_compare = sub.add_parser(
"compare", help="Aggregate stats grouped by model/hyperparams"
)
p_compare.add_argument("--env", default=None)
p_compare.add_argument("--model-type", default=None)
p_compare.add_argument(
"--algorithm", default=None, help="Filter by algorithm: dqn or a2c"
)
sub.add_parser("today", help="Today's experiments: last-10 and total avg reward")
p_sql = sub.add_parser("sql", help="Run a raw SQL query against live files")
p_sql.add_argument("query")
args = parser.parse_args()
if args.command == "today":
cmd_today(args)
elif args.command == "list":
cmd_list(args)
elif args.command == "best":
cmd_best(args)
elif args.command == "compare":
cmd_compare(args)
elif args.command == "sql":
cmd_sql(args)
if __name__ == "__main__":
main()