Spaces:
Sleeping

xzhou10 commited on
Commit
37a1a73
·
0 Parent(s):

Init RobustBench-TC leaderboard MVP with 18 seeded models

Browse files
Files changed (7) hide show
  1. DEPLOY.md +36 -0
  2. README.md +73 -0
  3. app.py +253 -0
  4. leaderboard.csv +19 -0
  5. requirements.txt +3 -0
  6. scoring/eval_results.py +487 -0
  7. seed_with_18_models.py +74 -0
DEPLOY.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deploy the leaderboard to HuggingFace Spaces
2
+
3
+ Three commands. Run them in `/u/xzhou10/sim2real/leaderboard/`.
4
+
5
+ ```bash
6
+ # 1. Auth (one-time): paste a HF write-access token from
7
+ # https://huggingface.co/settings/tokens
8
+ hf auth login
9
+
10
+ # 2. Create the Space (one-time):
11
+ hf repo create robustbench-tc-leaderboard --type space --space_sdk gradio
12
+
13
+ # 3. Commit + push (every time you update):
14
+ git commit -m "Init MVP with 18 seeded models" --allow-empty
15
+ git remote add space https://huggingface.co/spaces/$(hf auth whoami | head -1)/robustbench-tc-leaderboard 2>/dev/null || true
16
+ git push -u space main
17
+ ```
18
+
19
+ The Space will install `requirements.txt`, run `app.py`, and the
20
+ leaderboard tab will immediately show our 18 seeded entries from
21
+ `leaderboard.csv`. New submissions append to the same CSV (and we will
22
+ later sync to a HF Dataset for cross-restart persistence).
23
+
24
+ To run **locally** before deploying:
25
+
26
+ ```bash
27
+ pip install -r requirements.txt
28
+ python app.py # opens http://localhost:7860
29
+ ```
30
+
31
+ If `hf` is not on your PATH yet:
32
+
33
+ ```bash
34
+ pip install --user huggingface_hub
35
+ hash -r
36
+ ```
README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RobustBench-TC Leaderboard (MVP)
2
+
3
+ > A BFCL-style live leaderboard for tool-use sim-to-real robustness, deployed as a HuggingFace Space.
4
+
5
+ ## Architecture
6
+
7
+ ```
8
+ ┌─────────────────────┐ ┌──────────────────────┐
9
+ │ User submits │ POST │ Gradio backend (HF │
10
+ │ predictions JSON ├────────►│ Space, Python) │
11
+ │ (via UI or CLI) │ │ • Validates schema │
12
+ └─────────────────────┘ │ • Runs eval_results │
13
+ │ in subprocess │
14
+ │ • Computes per-MDP │
15
+ │ accuracy + drop │
16
+ │ • Persists to HF │
17
+ │ Dataset hub │
18
+ └──────────┬───────────┘
19
+ │
20
+ ┌───────────────────┴───────────────────┐
21
+ │ │
22
+ ▼ ▼
23
+ ┌───────────────────┐ ┌──────────────────────┐
24
+ │ HF Dataset: │ │ Public leaderboard │
25
+ │ submissions log │ │ table, refreshed on │
26
+ │ (append-only) │ │ each submission │
27
+ └───────────────────┘ └──────────────────────┘
28
+ ```
29
+
30
+ ## Submission schema
31
+
32
+ A valid submission is a JSON file with this shape:
33
+
34
+ ```json
35
+ {
36
+ "model_name": "MyTeam/MyModel-7B",
37
+ "model_type": "open" | "closed-api" | "fine-tuned",
38
+ "contact": "user@example.com",
39
+ "results": [
40
+ {
41
+ "sample_id": "bfcl_v3__BFCL_v3_simple__1",
42
+ "perturbation": "Typo",
43
+ "tool_calls": [{"name": "...", "parameters": {"...": "..."}}]
44
+ },
45
+ ...
46
+ ]
47
+ }
48
+ ```
49
+
50
+ The expected `sample_id` and `perturbation` values are documented in our HF dataset `Justin1233/RobustBench-TC`.
51
+
52
+ ## Local-eval CLI
53
+
54
+ We provide a CLI that runs the same scorer locally so users can validate before submitting:
55
+
56
+ ```bash
57
+ pip install robustbench-tc
58
+ robustbench-tc score --predictions my_predictions.json --output scores.json
59
+ ```
60
+
61
+ The CLI is a thin wrapper around `scripts/eval_results.py`.
62
+
63
+ ## Status
64
+
65
+ - [ ] M1: Gradio app skeleton (this directory)
66
+ - [ ] M2: Submission validator (schema + sample-ID coverage check)
67
+ - [ ] M3: Hosted scorer reusing `scripts/eval_results.py`
68
+ - [ ] M4: Persistence to HF Dataset
69
+ - [ ] M5: Leaderboard rendering (sorted by overall acc, with per-MDP-component drop columns)
70
+ - [ ] M6: Deployed on HF Space `Justin1233/robustbench-tc-leaderboard`
71
+ - [ ] M7: Documentation + first submission with our 18 evaluated models
72
+
73
+ ETA for M1--M5: 1 week eng. M6 + M7 another 2 days.
app.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RobustBench-TC live leaderboard (HuggingFace Space MVP).
2
+
3
+ Run locally:
4
+ pip install -r requirements.txt
5
+ python app.py
6
+
7
+ Deploy on HF Spaces:
8
+ huggingface-cli login
9
+ huggingface-cli repo create robustbench-tc-leaderboard --type space --space_sdk gradio
10
+ git remote add space https://huggingface.co/spaces/Justin1233/robustbench-tc-leaderboard
11
+ git add . && git commit -m "init" && git push space main
12
+
13
+ Submission flow (BFCL-style):
14
+ 1. User downloads the api_eval dataset from
15
+ https://huggingface.co/datasets/Justin1233/RobustBench-TC
16
+ 2. User runs their model **on their own GPU** to produce predictions
17
+ (we provide scripts/run_eval.py).
18
+ 3. User uploads predictions JSON to this Space.
19
+ 4. The Space scores it server-side with eval_results.py and updates
20
+ the leaderboard.
21
+
22
+ We deliberately do NOT run inference on HF Space hardware: 32B models
23
+ exceed Space ZeroGPU limits, and BFCL/Gorilla and most leaderboards
24
+ follow this same submit-predictions pattern.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import os
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ import gradio as gr
37
+ import pandas as pd
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Constants
41
+ # ---------------------------------------------------------------------------
42
+
43
+ ROOT = Path(__file__).resolve().parent
44
+ SCORER = ROOT / "scoring" / "eval_results.py"
45
+ LEADERBOARD_PATH = ROOT / "leaderboard.csv"
46
+
47
+ PERTURBATION_DISPLAY_NAMES = (
48
+ "clean",
49
+ "Typo", "QueryPara", "ToolPara", "ParamPara",
50
+ "Dup-NoDesc", "Dup-Desc", "Dup-WrongP", "Dup-DescWP", "Dup-SwapDP",
51
+ "RedunTool",
52
+ "MisDesc", "TimeDesc", "MisDesc-N", "TimeDesc-N",
53
+ "MisDesc-Abbr", "TimeDesc-Abbr",
54
+ "Timeout", "RateLim", "AuthErr", "5xxErr", "Malform", "SchemaD",
55
+ )
56
+
57
+ DISPLAY_TO_CODE = {
58
+ "clean": "clean",
59
+ "Typo": "realistic_typos", "QueryPara": "query_paraphrase",
60
+ "ToolPara": "paraphrase_tool_description",
61
+ "ParamPara": "paraphrase_parameter_description",
62
+ "Dup-NoDesc": "same_name_A", "Dup-Desc": "same_name_B",
63
+ "Dup-WrongP": "same_name_C", "Dup-DescWP": "same_name_D",
64
+ "Dup-SwapDP": "same_name_E", "RedunTool": "redundant",
65
+ "MisDesc": "CD", "TimeDesc": "TD",
66
+ "MisDesc-N": "CD_NT", "TimeDesc-N": "TD_NT",
67
+ "MisDesc-Abbr": "CD_AB", "TimeDesc-Abbr": "TD_AB",
68
+ "Timeout": "transient_timeout", "RateLim": "transient_rate_limit",
69
+ "AuthErr": "transient_auth_error", "5xxErr": "transient_server_error",
70
+ "Malform": "transient_malformed_response",
71
+ "SchemaD": "transient_schema_drift",
72
+ }
73
+
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Submission validation
77
+ # ---------------------------------------------------------------------------
78
+
79
+ def validate(payload: dict[str, Any]) -> tuple[bool, str]:
80
+ for k in ("model_name", "model_type", "contact", "results"):
81
+ if k not in payload:
82
+ return False, f"missing required field: {k!r}"
83
+ if payload["model_type"] not in ("open", "closed-api", "fine-tuned"):
84
+ return False, "model_type must be one of {open, closed-api, fine-tuned}"
85
+ if not isinstance(payload["results"], list) or not payload["results"]:
86
+ return False, "results must be a non-empty list"
87
+ seen = {r.get("perturbation") for r in payload["results"]}
88
+ unknown = seen - set(PERTURBATION_DISPLAY_NAMES)
89
+ if unknown:
90
+ return False, f"unknown perturbation names: {sorted(unknown)}"
91
+ for r in payload["results"][:5]:
92
+ for fld in ("sample_id", "perturbation", "tool_calls"):
93
+ if fld not in r:
94
+ return False, f"each result needs sample_id/perturbation/tool_calls; missing {fld!r}"
95
+ return True, "ok"
96
+
97
+
98
+ # ---------------------------------------------------------------------------
99
+ # Scoring (REAL — no longer a stub)
100
+ # ---------------------------------------------------------------------------
101
+
102
+ def score_submission(payload: dict[str, Any]) -> dict[str, Any]:
103
+ """Convert the submission into the format eval_results.py expects, run the
104
+ scorer, return a summary dict ready for the leaderboard CSV.
105
+ """
106
+ by_perturbation: dict[str, list[dict[str, Any]]] = {}
107
+ for r in payload["results"]:
108
+ code = DISPLAY_TO_CODE.get(r["perturbation"], r["perturbation"])
109
+ by_perturbation.setdefault(code, []).append({
110
+ "id": r["sample_id"],
111
+ "benchmark": r.get("benchmark", "unknown"),
112
+ "category": r.get("category"),
113
+ "perturbation": code,
114
+ "prediction": {
115
+ "raw_output": r.get("raw_output", ""),
116
+ "tool_calls": r["tool_calls"],
117
+ },
118
+ # Ground-truth fields are filled by the scorer from the dataset
119
+ "golden_answers": r.get("golden_answers"),
120
+ "tools": r.get("tools"),
121
+ "eval_config": r.get("eval_config"),
122
+ })
123
+
124
+ with tempfile.TemporaryDirectory() as td:
125
+ tmp = Path(td)
126
+ for code, recs in by_perturbation.items():
127
+ f = tmp / f"{code}.predictions.jsonl"
128
+ with f.open("w") as out:
129
+ for rec in recs:
130
+ out.write(json.dumps(rec) + "\n")
131
+
132
+ out_json = tmp / "scores.json"
133
+ cmd = [
134
+ sys.executable, str(SCORER),
135
+ "--predictions", str(tmp),
136
+ "--output", str(out_json),
137
+ ]
138
+ try:
139
+ subprocess.run(cmd, check=True, capture_output=True, timeout=600)
140
+ except subprocess.CalledProcessError as e:
141
+ return {"error": f"scorer failed: {e.stderr.decode()[-400:]}"}
142
+ scores = json.loads(out_json.read_text())
143
+
144
+ ov = scores["overall"]["overall"]
145
+ by_mdp = scores["overall"]["by_mdp_category"]
146
+ return {
147
+ "overall_acc": ov["accuracy"],
148
+ "n_samples": ov["n"],
149
+ "by_mdp": {k: v["accuracy"] for k, v in by_mdp.items()},
150
+ }
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Leaderboard CSV (Space-local; we will sync to HF Dataset hub in M4)
155
+ # ---------------------------------------------------------------------------
156
+
157
+ LEADERBOARD_COLUMNS = [
158
+ "Model", "Type", "n", "Overall Acc.",
159
+ "Clean", "Obs Acc.", "Action Acc.", "Reward Acc.", "Transition Acc.",
160
+ "Submitted",
161
+ ]
162
+
163
+
164
+ def append_entry(model_name: str, model_type: str,
165
+ summary: dict[str, Any]) -> None:
166
+ by_mdp = summary.get("by_mdp", {})
167
+ row = {
168
+ "Model": model_name,
169
+ "Type": model_type,
170
+ "n": summary.get("n_samples"),
171
+ "Overall Acc.": round(summary.get("overall_acc", 0), 4),
172
+ "Clean": round(by_mdp.get("clean", 0), 4),
173
+ "Obs Acc.": round(by_mdp.get("observation",0), 4),
174
+ "Action Acc.": round(by_mdp.get("action", 0), 4),
175
+ "Reward Acc.": round(by_mdp.get("reward", 0), 4),
176
+ "Transition Acc.": round(by_mdp.get("transition", 0), 4),
177
+ "Submitted": pd.Timestamp.utcnow().isoformat(timespec="seconds"),
178
+ }
179
+ if LEADERBOARD_PATH.exists():
180
+ df = pd.read_csv(LEADERBOARD_PATH)
181
+ df = pd.concat([df, pd.DataFrame([row])], ignore_index=True)
182
+ else:
183
+ df = pd.DataFrame([row])[LEADERBOARD_COLUMNS]
184
+ df.to_csv(LEADERBOARD_PATH, index=False)
185
+
186
+
187
+ def load_leaderboard() -> pd.DataFrame:
188
+ if LEADERBOARD_PATH.exists():
189
+ df = pd.read_csv(LEADERBOARD_PATH)
190
+ if "Overall Acc." in df.columns and df["Overall Acc."].notna().any():
191
+ df = df.sort_values("Overall Acc.", ascending=False)
192
+ return df
193
+ return pd.DataFrame(columns=LEADERBOARD_COLUMNS)
194
+
195
+
196
+ # ---------------------------------------------------------------------------
197
+ # UI
198
+ # ---------------------------------------------------------------------------
199
+
200
+ def submit(file) -> tuple[str, pd.DataFrame]:
201
+ if file is None:
202
+ return "❌ no file selected", load_leaderboard()
203
+ try:
204
+ payload = json.loads(Path(file.name).read_text())
205
+ except json.JSONDecodeError as e:
206
+ return f"❌ JSON parse error: {e}", load_leaderboard()
207
+ ok, msg = validate(payload)
208
+ if not ok:
209
+ return f"❌ {msg}", load_leaderboard()
210
+ summary = score_submission(payload)
211
+ if "error" in summary:
212
+ return f"❌ {summary['error']}", load_leaderboard()
213
+ append_entry(payload["model_name"], payload["model_type"], summary)
214
+ return (
215
+ f"✅ accepted: {payload['model_name']} — "
216
+ f"overall acc {summary['overall_acc']:.4f} on {summary['n_samples']} samples",
217
+ load_leaderboard(),
218
+ )
219
+
220
+
221
+ with gr.Blocks(title="RobustBench-TC Leaderboard") as demo:
222
+ gr.Markdown("# RobustBench-TC Leaderboard")
223
+ gr.Markdown(
224
+ "A sim-to-real robustness leaderboard for tool-use language agents. "
225
+ "**Run inference on your own hardware**, upload the predictions JSON, "
226
+ "and we score it server-side. See the schema in the *Submit* tab.\n\n"
227
+ "Dataset: [Justin1233/RobustBench-TC]"
228
+ "(https://huggingface.co/datasets/Justin1233/RobustBench-TC). "
229
+ "Inference helper: `scripts/run_eval.py` in the project repo."
230
+ )
231
+ with gr.Tab("Leaderboard"):
232
+ leaderboard = gr.Dataframe(
233
+ value=load_leaderboard(), interactive=False, wrap=True,
234
+ )
235
+ with gr.Tab("Submit"):
236
+ gr.Markdown("Upload `predictions.json` produced by `scripts/run_eval.py`.")
237
+ file = gr.File(label="predictions.json", file_types=[".json"])
238
+ out_msg = gr.Markdown()
239
+ out_table = gr.Dataframe(label="leaderboard (refreshed)", interactive=False)
240
+ gr.Button("Submit").click(submit, inputs=file,
241
+ outputs=[out_msg, out_table])
242
+ with gr.Tab("About"):
243
+ gr.Markdown(
244
+ "**Why server-side scoring only?** RobustBench-TC includes 32B-scale "
245
+ "models which exceed HuggingFace Space free-tier hardware limits. "
246
+ "Following the BFCL leaderboard pattern, contributors run their model "
247
+ "locally and submit a predictions JSON. We re-run only the deterministic "
248
+ "rule-based scorer (no GPT judge) on the Space."
249
+ )
250
+
251
+
252
+ if __name__ == "__main__":
253
+ demo.launch()
leaderboard.csv ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Model,Type,n,Overall Acc.,Clean,Obs Acc.,Action Acc.,Reward Acc.,Transition Acc.,Submitted
2
+ Qwen3-32B (non-thinking),open,2726,0.6009,0.7538,0.7299,0.6495,0.3879,0.4724,2026-04 (seeded)
3
+ LoopTool-32B,fine-tuned,2726,0.5851,0.7789,0.745,0.6591,0.2701,0.5427,2026-04 (seeded)
4
+ Qwen3-14B (non-thinking),open,3721,0.541,0.7487,0.7098,0.6053,0.2845,0.4983,2026-04 (seeded)
5
+ MUA-RL-32B,fine-tuned,3721,0.5356,0.6834,0.6558,0.6938,0.2859,0.4657,2026-04 (seeded)
6
+ MUA-RL-8B,fine-tuned,3721,0.4899,0.6784,0.6558,0.5227,0.2773,0.4489,2026-04 (seeded)
7
+ LoopTool-8B,fine-tuned,3721,0.4891,0.7136,0.6646,0.5407,0.2845,0.4179,2026-04 (seeded)
8
+ MUA-RL-14B,fine-tuned,3721,0.4784,0.6281,0.6168,0.5383,0.2945,0.4263,2026-04 (seeded)
9
+ Qwen3-8B (non-thinking),open,3721,0.4604,0.6734,0.6545,0.5024,0.2644,0.3802,2026-04 (seeded)
10
+ DeepSeek-R1-Distill-Qwen-14B,open,3721,0.4518,0.6181,0.6055,0.4581,0.3003,0.4054,2026-04 (seeded)
11
+ Qwen3.5-9B,open,3721,0.4515,0.7085,0.6683,0.5407,0.2974,0.2915,2026-04 (seeded)
12
+ ToolRL-Qwen2.5-1.5B,fine-tuned,3721,0.4461,0.7035,0.6709,0.5299,0.2227,0.325,2026-04 (seeded)
13
+ TL-CodeLLaMA-2,fine-tuned,3721,0.4184,0.6533,0.6294,0.4868,0.1968,0.3199,2026-04 (seeded)
14
+ ToolRL-Qwen2.5-3B,fine-tuned,3721,0.4166,0.6382,0.6181,0.4952,0.1882,0.3233,2026-04 (seeded)
15
+ ToolRL-Llama3.2-3B,fine-tuned,3721,0.4026,0.6281,0.603,0.4569,0.1652,0.3317,2026-04 (seeded)
16
+ Qwen2.5-3B-Instruct,open,3721,0.4018,0.608,0.5942,0.4127,0.1624,0.371,2026-04 (seeded)
17
+ Qwen2.5-1.5B-Instruct,open,3721,0.3779,0.5729,0.5327,0.3732,0.1681,0.3677,2026-04 (seeded)
18
+ Llama-3.2-3B-Instruct,open,3721,0.3504,0.5176,0.5088,0.3409,0.1451,0.3434,2026-04 (seeded)
19
+ SFT-Clean-4k-Qwen2.5-3B (ours),fine-tuned,3721,0.2846,0.598,0.5791,0.4139,0.1552,0.0209,2026-04 (seeded)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio==4.44.0
2
+ pandas>=2.1
3
+ huggingface_hub>=0.24
scoring/eval_results.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ RobustBench-TC results evaluator.
4
+
5
+ Consumes the `.predictions.jsonl` files produced by `run_eval.py`, dispatches
6
+ scoring by `sample.eval_config.method`, and aggregates metrics by
7
+ (benchmark, perturbation_type, mdp_category).
8
+
9
+ Scoring is fully deterministic — no external LLM judge is used:
10
+ - exact_match -> BFCL-style name + numeric-tolerant parameter equality
11
+ - rule_based -> RoTBench TS / PI / CF sub-metrics
12
+ - gpt_judge -> replaced deterministically:
13
+ metric="relevance" -> name-only match (ToolEyes)
14
+ metric="complete_accuracy" -> exact_match (ToolAlpaca)
15
+
16
+ Usage:
17
+ python scripts/eval_results.py \
18
+ --predictions results/my-model \
19
+ --output results/my-model/scores.json
20
+
21
+ # Score a subset:
22
+ python scripts/eval_results.py \
23
+ --predictions results/my-model \
24
+ --files clean.predictions.jsonl realistic_typos.predictions.jsonl \
25
+ --output results/my-model/scores.json
26
+ """
27
+
28
+ import argparse
29
+ import json
30
+ import sys
31
+ from collections import defaultdict
32
+ from pathlib import Path
33
+ from typing import Any, Dict, List, Optional
34
+
35
+
36
+ # ────────────────────────────────────────────────────────────────
37
+ # Exact match (bfcl_v3, apibank)
38
+ # ────────────────────────────────────────────────────────────────
39
+
40
+ def _normalize_params(params: Any) -> Dict[str, Any]:
41
+ """Canonicalize parameter dicts for comparison."""
42
+ if isinstance(params, dict):
43
+ out: Dict[str, Any] = {}
44
+ for k, v in params.items():
45
+ if isinstance(v, str):
46
+ out[k] = v.strip()
47
+ elif isinstance(v, list):
48
+ # Represent lists in a comparable way; keep elements coerced
49
+ out[k] = [x.strip() if isinstance(x, str) else x for x in v]
50
+ else:
51
+ out[k] = v
52
+ return out
53
+ return {}
54
+
55
+
56
+ def _try_number(x: Any) -> Optional[float]:
57
+ if isinstance(x, bool):
58
+ return None
59
+ if isinstance(x, (int, float)):
60
+ return float(x)
61
+ if isinstance(x, str):
62
+ try:
63
+ return float(x.strip())
64
+ except (ValueError, TypeError):
65
+ return None
66
+ return None
67
+
68
+
69
+ def _is_empty_default(value: Any) -> bool:
70
+ """Return True if `value` represents a BFCL 'optional/omittable' default.
71
+
72
+ BFCL ground-truth lists (e.g. ``"unit": [""]``) are collapsed to scalars
73
+ by the unified-sample builder, so a GT of ``""`` or ``None`` signals
74
+ 'this param is optional and may be omitted by the model'. Empty
75
+ containers count too.
76
+ """
77
+ if value is None:
78
+ return True
79
+ if isinstance(value, str) and value.strip() == "":
80
+ return True
81
+ if isinstance(value, (list, tuple, dict)) and len(value) == 0:
82
+ return True
83
+ return False
84
+
85
+
86
+ def _params_equal(a: Any, b: Any) -> bool:
87
+ """Compare parameter dicts with BFCL-compatible tolerance.
88
+
89
+ Rules:
90
+ - Numeric-tolerant: '1500', '1500.0', 1500, 1500.0 all equal.
91
+ - Optional-param omission: keys present in one side with an
92
+ "empty default" value (``""``, ``None``, ``[]``, ``{}``) may be
93
+ absent from the other side. Matches BFCL's ground-truth convention
94
+ of listing ``""`` as an acceptable omission for optional params.
95
+
96
+ ``a`` is the predicted dict, ``b`` is the ground-truth dict.
97
+ """
98
+ na = _normalize_params(a)
99
+ nb = _normalize_params(b)
100
+
101
+ # Key union, but drop keys whose value is an empty-default on either side
102
+ # when the other side doesn't have that key.
103
+ all_keys = set(na) | set(nb)
104
+ for k in all_keys:
105
+ if k in na and k in nb:
106
+ va, vb = na[k], nb[k]
107
+ nva = _try_number(va)
108
+ nvb = _try_number(vb)
109
+ if nva is not None and nvb is not None:
110
+ if nva != nvb:
111
+ return False
112
+ continue
113
+ if va != vb:
114
+ # Allow matching an empty-default on one side to an absent
115
+ # key on the other — but if both are present and unequal,
116
+ # and at least one is empty-default, we treat that as
117
+ # "GT says optional and model provided a value", accept it.
118
+ if _is_empty_default(va) or _is_empty_default(vb):
119
+ continue
120
+ return False
121
+ else:
122
+ # Key only in one side. Allowed iff its value is an empty default.
123
+ only_val = na.get(k, nb.get(k))
124
+ if not _is_empty_default(only_val):
125
+ return False
126
+ return True
127
+
128
+
129
+ def _ga_name(ga: Dict[str, Any]) -> str:
130
+ return ga.get("name") or ga.get("Action") or ""
131
+
132
+
133
+ def _ga_params(ga: Dict[str, Any]) -> Dict[str, Any]:
134
+ return ga.get("parameters") or ga.get("arguments") or ga.get("Action_Input") or {}
135
+
136
+
137
+ def _params_equal_bfcl(pred_params: Dict[str, Any],
138
+ gt_params: Dict[str, Any]) -> bool:
139
+ """BFCL-flavored param comparison.
140
+
141
+ BFCL's native ground-truth lists alternatives per param
142
+ (``"unit": ["metric", ""]`` = "either 'metric' or omit it entirely").
143
+ The unified HF schema collapses those lists to a single scalar, so
144
+ we can no longer distinguish "mandatory" from "optional with default".
145
+ To match BFCL's official checker's leniency, allow the prediction to
146
+ OMIT any key that GT has. For keys present in both, require numeric-
147
+ tolerant equality (same as the strict matcher).
148
+ """
149
+ nref = _normalize_params(gt_params)
150
+ nprd = _normalize_params(pred_params)
151
+ for k, vp in nprd.items():
152
+ if k not in nref:
153
+ return False # pred hallucinated an arg
154
+ vg = nref[k]
155
+ nvp = _try_number(vp)
156
+ nvg = _try_number(vg)
157
+ if nvp is not None and nvg is not None:
158
+ if nvp != nvg:
159
+ return False
160
+ continue
161
+ if vp != vg:
162
+ return False
163
+ return True
164
+
165
+
166
+ def score_exact_match(pred_calls: List[Dict[str, Any]],
167
+ golden_answers: List[Dict[str, Any]],
168
+ benchmark: str = "") -> Dict[str, Any]:
169
+ """A prediction is correct if for every GA, at least one predicted call
170
+ matches both name and parameters.
171
+
172
+ For BFCL single-turn 'multiple': GA list has one entry; at least one pred
173
+ must match it. For longer GA lists: every GA must be covered.
174
+
175
+ ``benchmark="bfcl_v3"`` triggers BFCL-lenient param matching (allow
176
+ omitting GT keys, per BFCL's optional-param convention); otherwise
177
+ strict matching with empty-default leniency only.
178
+ """
179
+ if not golden_answers:
180
+ correct = (len(pred_calls) == 0)
181
+ return {"correct": correct, "score": 1.0 if correct else 0.0,
182
+ "method": "exact_match", "matched": 0, "expected": 0}
183
+
184
+ eq = _params_equal_bfcl if benchmark == "bfcl_v3" else _params_equal
185
+
186
+ matched = 0
187
+ for ga in golden_answers:
188
+ gname = _ga_name(ga)
189
+ gparams = _ga_params(ga)
190
+ hit = False
191
+ for pc in pred_calls:
192
+ pname = pc.get("name", "")
193
+ pparams = pc.get("parameters") or pc.get("arguments") or {}
194
+ if pname == gname and eq(pparams, gparams):
195
+ hit = True
196
+ break
197
+ if hit:
198
+ matched += 1
199
+
200
+ total = len(golden_answers)
201
+ correct = (matched == total)
202
+ return {
203
+ "correct": correct,
204
+ "score": matched / total if total else 0.0,
205
+ "method": "exact_match",
206
+ "matched": matched,
207
+ "expected": total,
208
+ }
209
+
210
+
211
+ # ────────────────────────────────────────────────────────────────
212
+ # Rule-based (rotbench: TS/PI/CF)
213
+ # ────────────────────────────────────────────────────────────────
214
+
215
+ def score_rule_based(pred_calls: List[Dict[str, Any]],
216
+ golden_answers: List[Dict[str, Any]]) -> Dict[str, Any]:
217
+ """RoTBench TS/PI/CF metrics, evaluated against first GA."""
218
+ if not golden_answers:
219
+ no_calls = (len(pred_calls) == 0)
220
+ return {"correct": no_calls, "score": 1.0 if no_calls else 0.0,
221
+ "method": "rule_based",
222
+ "tool_selection": no_calls,
223
+ "parameter_identification": no_calls,
224
+ "content_filling": no_calls}
225
+
226
+ ga = golden_answers[0]
227
+ gname = _ga_name(ga)
228
+ gparams = _ga_params(ga)
229
+
230
+ ts = False
231
+ pi = False
232
+ cf = False
233
+ for pc in pred_calls:
234
+ pname = pc.get("name", "")
235
+ pparams = pc.get("parameters") or pc.get("arguments") or {}
236
+ if pname == gname:
237
+ ts = True
238
+ if set((pparams or {}).keys()) == set((gparams or {}).keys()):
239
+ pi = True
240
+ if _params_equal(pparams, gparams):
241
+ cf = True
242
+ # Don't break — different pred call might satisfy more sub-metrics
243
+ score = (int(ts) + int(pi) + int(cf)) / 3.0
244
+ return {
245
+ "correct": cf,
246
+ "score": score,
247
+ "method": "rule_based",
248
+ "tool_selection": ts,
249
+ "parameter_identification": pi,
250
+ "content_filling": cf,
251
+ }
252
+
253
+
254
+ # ────────────────────────────────────────────────────────────────
255
+ # Name-only relevance (ToolEyes) — replaces GPT judge deterministically
256
+ # ────────────────────────────────────────────────────────────────
257
+
258
+ def score_relevance(pred_calls: List[Dict[str, Any]],
259
+ golden_answers: List[Dict[str, Any]]) -> Dict[str, Any]:
260
+ """Name-only match for the ToolEyes 'relevance' metric.
261
+
262
+ ToolEyes GAs typically carry empty params (the benchmark only asks
263
+ whether the model picked an appropriate tool). Anything name-equal to a
264
+ GA is considered correct.
265
+ """
266
+ if not golden_answers:
267
+ correct = (len(pred_calls) == 0)
268
+ return {"correct": correct, "score": 1.0 if correct else 0.0,
269
+ "method": "name_match"}
270
+ gt_names = {_ga_name(ga) for ga in golden_answers}
271
+ pred_names = {pc.get("name", "") for pc in pred_calls}
272
+ hit = bool(gt_names & pred_names)
273
+ return {"correct": hit, "score": 1.0 if hit else 0.0,
274
+ "method": "name_match"}
275
+
276
+
277
+ # ────────────────────────────────────────────────────────────────
278
+ # Score one prediction record
279
+ # ────────────────────────────────────────────────────────────────
280
+
281
+ def score_record(record: Dict[str, Any]) -> Dict[str, Any]:
282
+ """Dispatch by sample eval_config. All branches deterministic.
283
+
284
+ Samples whose original eval_config.method is "gpt_judge" are scored
285
+ without an LLM:
286
+ - metric == "relevance" -> name-only match (ToolEyes)
287
+ - metric == "complete_accuracy" -> exact match (ToolAlpaca)
288
+ """
289
+ eval_cfg = record.get("eval_config") or {}
290
+ method = eval_cfg.get("method", "exact_match")
291
+ metrics = eval_cfg.get("metrics") or ["complete_accuracy"]
292
+ metric = metrics[0] if metrics else "complete_accuracy"
293
+
294
+ pred = record.get("prediction") or {}
295
+ pred_calls = pred.get("tool_calls") or []
296
+ gas = record.get("golden_answers") or []
297
+
298
+ if method == "exact_match":
299
+ return score_exact_match(pred_calls, gas, benchmark=record.get("benchmark", ""))
300
+
301
+ if method == "rule_based":
302
+ return score_rule_based(pred_calls, gas)
303
+
304
+ if method == "gpt_judge":
305
+ if metric == "relevance":
306
+ return score_relevance(pred_calls, gas)
307
+ return score_exact_match(pred_calls, gas)
308
+
309
+ # Unknown method → exact match as safest default
310
+ return score_exact_match(pred_calls, gas)
311
+
312
+
313
+ # ────────────────────────────────────────────────────────────────
314
+ # File- and corpus-level scoring + aggregation
315
+ # ────────────────────────────────────────────────────────────────
316
+
317
+ def score_file(path: Path) -> List[Dict[str, Any]]:
318
+ records = []
319
+ with open(path, "r", encoding="utf-8") as f:
320
+ for line in f:
321
+ line = line.strip()
322
+ if not line:
323
+ continue
324
+ records.append(json.loads(line))
325
+
326
+ out = []
327
+ for rec in records:
328
+ sc = score_record(rec)
329
+ out.append({
330
+ "id": rec.get("id"),
331
+ "benchmark": rec.get("benchmark"),
332
+ "category": rec.get("category"),
333
+ "perturbation": rec.get("perturbation"),
334
+ "score": sc,
335
+ })
336
+ return out
337
+
338
+
339
+ def aggregate(scored_records: List[Dict[str, Any]]) -> Dict[str, Any]:
340
+ """Aggregate into (benchmark, perturbation.type, mdp_category) buckets."""
341
+ # Per-bucket running totals
342
+ def _mk():
343
+ return {"n": 0, "correct": 0, "score_sum": 0.0}
344
+
345
+ overall = _mk()
346
+ by_benchmark = defaultdict(_mk)
347
+ by_perturbation = defaultdict(_mk) # keyed by perturbation.type (or "clean")
348
+ by_mdp = defaultdict(_mk)
349
+ by_bench_pert = defaultdict(_mk) # (benchmark, perturbation.type)
350
+
351
+ for rec in scored_records:
352
+ sc = rec["score"]
353
+ n = 1
354
+ c = 1 if sc.get("correct") else 0
355
+ s = float(sc.get("score", 0.0))
356
+
357
+ overall["n"] += n
358
+ overall["correct"] += c
359
+ overall["score_sum"] += s
360
+
361
+ b = rec.get("benchmark", "?")
362
+ by_benchmark[b]["n"] += n
363
+ by_benchmark[b]["correct"] += c
364
+ by_benchmark[b]["score_sum"] += s
365
+
366
+ pinfo = rec.get("perturbation") or {}
367
+ ptype = pinfo.get("type") or "clean"
368
+ mdp = pinfo.get("mdp_category") or "clean"
369
+
370
+ by_perturbation[ptype]["n"] += n
371
+ by_perturbation[ptype]["correct"] += c
372
+ by_perturbation[ptype]["score_sum"] += s
373
+
374
+ by_mdp[mdp]["n"] += n
375
+ by_mdp[mdp]["correct"] += c
376
+ by_mdp[mdp]["score_sum"] += s
377
+
378
+ k = f"{b}::{ptype}"
379
+ by_bench_pert[k]["n"] += n
380
+ by_bench_pert[k]["correct"] += c
381
+ by_bench_pert[k]["score_sum"] += s
382
+
383
+ def _finalize(d):
384
+ out = {}
385
+ for k, v in d.items():
386
+ n = v["n"]
387
+ out[k] = {
388
+ "n": n,
389
+ "correct": v["correct"],
390
+ "accuracy": v["correct"] / n if n else 0.0,
391
+ "mean_score": v["score_sum"] / n if n else 0.0,
392
+ }
393
+ return out
394
+
395
+ return {
396
+ "overall": {
397
+ "n": overall["n"],
398
+ "correct": overall["correct"],
399
+ "accuracy": (overall["correct"] / overall["n"])
400
+ if overall["n"] else 0.0,
401
+ "mean_score": (overall["score_sum"] / overall["n"])
402
+ if overall["n"] else 0.0,
403
+ },
404
+ "by_benchmark": _finalize(by_benchmark),
405
+ "by_perturbation": _finalize(by_perturbation),
406
+ "by_mdp_category": _finalize(by_mdp),
407
+ "by_benchmark_x_perturbation": _finalize(by_bench_pert),
408
+ }
409
+
410
+
411
+ # ────────────────────────────────────────────────────────────────
412
+ # CLI
413
+ # ────────────────────────────────────────────────────────────────
414
+
415
+ def main():
416
+ parser = argparse.ArgumentParser(description="RobustBench-TC scorer.")
417
+ parser.add_argument("--predictions", required=True,
418
+ help="Directory containing *.predictions.jsonl files.")
419
+ parser.add_argument("--files", nargs="*", default=None,
420
+ help="Subset of predictions filenames to score.")
421
+ parser.add_argument("--output", required=True,
422
+ help="Path for aggregated scores JSON.")
423
+ parser.add_argument("--per-sample-output", default=None,
424
+ help="Optional: path for per-sample scored records jsonl.")
425
+ args = parser.parse_args()
426
+
427
+ pred_dir = Path(args.predictions)
428
+ if args.files:
429
+ files = [pred_dir / f for f in args.files]
430
+ else:
431
+ # Recursive so transition_{type}/ subdirectories are included.
432
+ files = sorted(pred_dir.rglob("*.predictions.jsonl"))
433
+
434
+ if not files:
435
+ print(f"ERROR: no *.predictions.jsonl files in {pred_dir}",
436
+ file=sys.stderr)
437
+ sys.exit(1)
438
+
439
+ all_scored: List[Dict[str, Any]] = []
440
+ per_file_agg: Dict[str, Any] = {}
441
+ for f in files:
442
+ if not f.exists():
443
+ print(f"WARN: missing {f}, skipping", file=sys.stderr)
444
+ continue
445
+ scored = score_file(f)
446
+ all_scored.extend(scored)
447
+ per_file_agg[f.name] = aggregate(scored)
448
+
449
+ overall = aggregate(all_scored)
450
+ summary = {
451
+ "overall": overall,
452
+ "per_file": per_file_agg,
453
+ }
454
+
455
+ out_path = Path(args.output)
456
+ out_path.parent.mkdir(parents=True, exist_ok=True)
457
+ out_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False),
458
+ encoding="utf-8")
459
+
460
+ if args.per_sample_output:
461
+ psp = Path(args.per_sample_output)
462
+ psp.parent.mkdir(parents=True, exist_ok=True)
463
+ with open(psp, "w", encoding="utf-8") as f:
464
+ for rec in all_scored:
465
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
466
+
467
+ # Console summary
468
+ ov = overall["overall"]
469
+ print(f"\n=== eval_results.py summary ===")
470
+ print(f"n={ov['n']} accuracy={ov['accuracy']:.4f} "
471
+ f"mean_score={ov['mean_score']:.4f}")
472
+ print("\nBy benchmark:")
473
+ for k, v in sorted(overall["by_benchmark"].items()):
474
+ print(f" {k:12s} n={v['n']:4d} acc={v['accuracy']:.4f} "
475
+ f"score={v['mean_score']:.4f}")
476
+ print("\nBy MDP category:")
477
+ for k, v in sorted(overall["by_mdp_category"].items()):
478
+ print(f" {k:12s} n={v['n']:4d} acc={v['accuracy']:.4f} "
479
+ f"score={v['mean_score']:.4f}")
480
+ print("\nBy perturbation type:")
481
+ for k, v in sorted(overall["by_perturbation"].items()):
482
+ print(f" {k:32s} n={v['n']:4d} acc={v['accuracy']:.4f} "
483
+ f"score={v['mean_score']:.4f}")
484
+
485
+
486
+ if __name__ == "__main__":
487
+ main()
seed_with_18_models.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Seed the leaderboard CSV with our 18 evaluated models.
2
+
3
+ Reads /projects/bfdz/xzhou10/robustbench/results/<model>/scores.json for each,
4
+ extracts the overall + by-MDP-component accuracy numbers, writes one row per
5
+ model to leaderboard.csv. Run once before the first deployment.
6
+
7
+ Usage:
8
+ python seed_with_18_models.py
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+
15
+ import pandas as pd
16
+
17
+ RESULTS = Path("/projects/bfdz/xzhou10/robustbench/results")
18
+ OUT = Path(__file__).resolve().parent / "leaderboard.csv"
19
+
20
+ # Display name -> result-directory basename
21
+ MODELS = {
22
+ # Family, Type, Result dir
23
+ "ToolRL-Qwen2.5-1.5B": ("fine-tuned", "chengq9__ToolRL-Qwen2.5-1.5B"),
24
+ "ToolRL-Qwen2.5-3B": ("fine-tuned", "chengq9__ToolRL-Qwen2.5-3B"),
25
+ "ToolRL-Llama3.2-3B": ("fine-tuned", "chengq9__ToolRL-Llama3.2-3B"),
26
+ "TL-CodeLLaMA-2": ("fine-tuned", "Junjie-Ye__TL-CodeLLaMA-2"),
27
+ "LoopTool-8B": ("fine-tuned", "zhuiguang-ning__LoopTool-8B"),
28
+ "LoopTool-32B": ("fine-tuned", "zhuiguang-ning__LoopTool-32B"),
29
+ "MUA-RL-8B": ("fine-tuned", "zzwkk__MUA-RL-8B"),
30
+ "MUA-RL-14B": ("fine-tuned", "zzwkk__MUA-RL-14B"),
31
+ "MUA-RL-32B": ("fine-tuned", "zzwkk__MUA-RL-32B"),
32
+ "Qwen2.5-1.5B-Instruct": ("open", "Qwen__Qwen2.5-1.5B-Instruct"),
33
+ "Qwen2.5-3B-Instruct": ("open", "Qwen__Qwen2.5-3B-Instruct"),
34
+ "Llama-3.2-3B-Instruct": ("open", "meta-llama__Llama-3.2-3B-Instruct"),
35
+ "Qwen3-8B (non-thinking)": ("open", "Qwen__Qwen3-8B"),
36
+ "Qwen3-14B (non-thinking)": ("open", "Qwen__Qwen3-14B"),
37
+ "Qwen3-32B (non-thinking)": ("open", "Qwen__Qwen3-32B"),
38
+ "Qwen3.5-9B": ("open", "Qwen__Qwen3.5-9B"),
39
+ "DeepSeek-R1-Distill-Qwen-14B": ("open", "deepseek-ai__DeepSeek-R1-Distill-Qwen-14B"),
40
+ "SFT-Clean-4k-Qwen2.5-3B (ours)": ("fine-tuned", "__projects__bfdz__xzhou10__robustbench__sft_models__SFT-Clean-4k-Qwen2.5-3B-Instruct"),
41
+ }
42
+
43
+
44
+ def main() -> None:
45
+ rows = []
46
+ for model_name, (mtype, dirname) in MODELS.items():
47
+ scores_path = RESULTS / dirname / "scores.json"
48
+ if not scores_path.exists():
49
+ print(f" SKIP {model_name}: no scores.json at {scores_path}")
50
+ continue
51
+ data = json.loads(scores_path.read_text())
52
+ ov = data["overall"]["overall"]
53
+ by_mdp = data["overall"]["by_mdp_category"]
54
+ rows.append({
55
+ "Model": model_name,
56
+ "Type": mtype,
57
+ "n": ov["n"],
58
+ "Overall Acc.": round(ov["accuracy"], 4),
59
+ "Clean": round(by_mdp.get("clean", {}).get("accuracy", 0), 4),
60
+ "Obs Acc.": round(by_mdp.get("observation",{}).get("accuracy", 0), 4),
61
+ "Action Acc.": round(by_mdp.get("action", {}).get("accuracy", 0), 4),
62
+ "Reward Acc.": round(by_mdp.get("reward", {}).get("accuracy", 0), 4),
63
+ "Transition Acc.": round(by_mdp.get("transition", {}).get("accuracy", 0), 4),
64
+ "Submitted": "2026-04 (seeded)",
65
+ })
66
+ print(f" ✓ {model_name}: overall={rows[-1]['Overall Acc.']}")
67
+
68
+ df = pd.DataFrame(rows).sort_values("Overall Acc.", ascending=False)
69
+ df.to_csv(OUT, index=False)
70
+ print(f"\nWrote {len(df)} rows to {OUT}")
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()