File size: 9,981 Bytes
7f80620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93aedf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f80620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93aedf0
7f80620
93aedf0
 
 
 
 
 
42704f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93aedf0
7f80620
93aedf0
7f80620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246df60
 
0d77c20
 
 
 
246df60
0d77c20
 
 
 
 
 
7f80620
 
 
c4775f1
 
7f80620
 
 
881a579
 
 
 
 
 
7f80620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4775f1
 
7f80620
 
0d77c20
 
246df60
7f80620
 
 
 
 
 
246df60
7f80620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Baselines: zero-shot and 5-shot eval of untuned base models on the fixed test set.

Same system prompt the students will be trained with, greedy decoding.
Metrics per the project spec; results pushed to the dataset repo.

Usage:
  python eval_baselines.py --models Qwen/Qwen3.5-0.8B Qwen/Qwen3.5-2B
"""
import argparse
import json
import os
import sys

import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import validator as V  # noqa: E402

DATASET = "joemaddalone/ffmpeg-nl2cmd-clean"
SYSTEM = "Output exactly one ffmpeg command on a single line. No markdown, no explanation."

FEWSHOT_IDS = None  # filled after load: 5 train rows across categories


def pick_fewshot(ds):
    """5 deterministic train examples spanning categories."""
    by_cat = {}
    for r in ds:
        if r["split"] == "train" and r["label"] == "runs":
            by_cat.setdefault(r["category"], []).append(r)
    cats = ["conversion", "video filter", "audio filter", "trim", "concat"]
    picked = []
    for c in cats:
        if c in by_cat:
            picked.append(sorted(by_cat[c], key=lambda r: r["id"])[0])
    for r in sorted(ds, key=lambda x: x["id"]):
        if len(picked) >= 5:
            break
        if r["split"] == "train" and r["label"] == "runs" and r not in picked:
            picked.append(r)
    return picked[:5]


def build_messages(nl, fewshot):
    msgs = [{"role": "system", "content": SYSTEM}]
    for ex in fewshot:
        msgs.append({"role": "user", "content": ex["natural_language"]})
        msgs.append({"role": "assistant", "content": ex["ffmpeg_command"]})
    msgs.append({"role": "user", "content": nl})
    return msgs


def generate_batch(model, tok, msgs_list):
    texts = [tok.apply_chat_template(m, tokenize=False, add_generation_prompt=True,
                                     enable_thinking=False) for m in msgs_list]
    tok.padding_side = "left"
    ids = tok(texts, return_tensors="pt", padding=True).to(model.device)
    with torch.no_grad():
        out = model.generate(**ids, do_sample=False, max_new_tokens=128,
                             pad_token_id=tok.pad_token_id or tok.eos_token_id)
    outs = []
    for i in range(len(texts)):
        gen = out[i][ids["input_ids"].shape[1]:]
        s = tok.decode(gen, skip_special_tokens=True)
        s = s.split("\n")[0].strip()
        if s.startswith("```"):
            s = s.strip("`").strip()
            s = s.split("\n")[0].strip()
        outs.append(s)
    return outs


def generate(model, tok, msgs):
    text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True,
                                   enable_thinking=False)
    ids = tok(text, return_tensors="pt").to(model.device)
    with torch.no_grad():
        out = model.generate(**ids, do_sample=False, max_new_tokens=128,
                             pad_token_id=tok.pad_token_id or tok.eos_token_id)
    gen = out[0][ids["input_ids"].shape[1]:]
    s = tok.decode(gen, skip_special_tokens=True)
    # keep only the first line, strip markdown fences if the base model adds them
    s = s.split("\n")[0].strip()
    if s.startswith("```"):
        s = s.strip("`").strip()
        s = s.split("\n")[0].strip()
    return s


def score_rows(rows, model_name, mode, pool, fewshot, model, tok, batch_size=16):
    results = []
    for i in range(0, len(rows), batch_size):
        chunk = rows[i:i + batch_size]
        msgs_list = [build_messages(r["natural_language"], fewshot) for r in chunk]
        preds = generate_batch(model, tok, msgs_list)
        for row, pred in zip(chunk, preds):
            ref = row["ffmpeg_command"]
            val = V.run_command(pred, pool) if pred.strip() else {"mode": "none", "ok": False, "reason": "empty output"}
            sc = {
                "id": row["id"], "split": row["split"], "category": row["category"],
                "family": row["filter_family"], "label": row["label"], "seen": bool(row["seen"]),
                "nl": row["natural_language"], "ref": ref, "pred": pred,
                "executes": bool(val["ok"]) and val["mode"] == "run",
                "static_ok": bool(val["ok"]) and val["mode"] == "static",
                "valid": bool(val["ok"]),
                "validation_mode": val["mode"], "reason": val["reason"],
                "exact_match": V.normalize_cmd(pred) == V.normalize_cmd(ref),
                "token_f1": round(V.token_f1(V.normalize_cmd(ref), V.normalize_cmd(pred)), 4),
                "hallucinated": V.hallucinated_items(pred),
                "format_ok": V.format_ok(pred),
            }
            results.append(sc)
        if len(results) % 50 < batch_size:
            v = sum(r["valid"] for r in results) / len(results)
            print(f"  [{model_name}/{mode}] {len(results)}/{len(rows)} valid-rate so far {v:.3f}", flush=True)
    return results


def aggregate(results):
    n = len(results)
    if n == 0:
        return {}
    runs = [r for r in results if r["label"] == "runs"]
    static = [r for r in results if r["label"] == "static-only"]
    agg = {
        "n": n,
        "executes_runs": round(sum(r["executes"] for r in runs) / len(runs), 4) if runs else None,
        "static_valid": round(sum(r["static_ok"] for r in static) / len(static), 4) if static else None,
        "valid_all": round(sum(r["valid"] for r in results) / n, 4),
        "exact_match": round(sum(r["exact_match"] for r in results) / n, 4),
        "token_f1": round(sum(r["token_f1"] for r in results) / n, 4),
        "hallucination_rate": round(sum(1 for r in results if r["hallucinated"]) / n, 4),
        "format_ok": round(sum(r["format_ok"] for r in results) / n, 4),
    }
    by_cat = {}
    for r in results:
        by_cat.setdefault(r["category"], []).append(r)
    agg["by_category"] = {
        c: {"n": len(rs), "valid": round(sum(x["valid"] for x in rs) / len(rs), 4),
            "exact_match": round(sum(x["exact_match"] for x in rs) / len(rs), 4)}
        for c, rs in sorted(by_cat.items())}
    return agg


def push_results(all_results, out_dir, suffix=""):
    path = os.path.join(out_dir, f"baseline_results{suffix}.json")
    with open(path, "w") as f:
        json.dump(all_results, f, indent=1)
    try:
        from huggingface_hub import HfApi
        HfApi().upload_file(path_or_fileobj=path, path_in_repo=f"results/baseline_results{suffix}.json",
                            repo_id=DATASET, repo_type="dataset")
        print("pushed partial results", flush=True)
    except Exception as e:
        print(f"partial push failed: {e}", flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--models", nargs="+", default=["Qwen/Qwen3.5-0.8B", "Qwen/Qwen3.5-2B"])
    ap.add_argument("--modes", nargs="+", default=["zeroshot", "shot5"],
                    choices=["zeroshot", "shot5"])
    ap.add_argument("--out", default="results")
    args = ap.parse_args()

    # explicit CSV load: the repo has no parquet export yet, and auto-discovery
    # of a lone CSV at the repo root is unreliable
    ds = list(load_dataset("csv", data_files="hf://datasets/joemaddalone/ffmpeg-nl2cmd-clean/clean_dataset.csv")["train"])
    for r in ds:
        r["category"] = r["category"] or "conversion"
        r["filter_family"] = r["filter_family"] or "plain-conversion"
    test_rows = [r for r in ds if r["split"] in ("test", "test-robust")
                 and r["label"] in ("runs", "static-only")]
    train_families = {r["filter_family"] for r in ds if r["split"] == "train"}
    for r in test_rows:
        r["seen"] = r["filter_family"] in train_families
    fewshot = pick_fewshot(ds)
    print(f"test+robust rows: {len(test_rows)} | fewshot ids: {[e['id'] for e in fewshot]}", flush=True)

    V.load_options()
    os.makedirs(args.out, exist_ok=True)
    all_results = {}

    for model_name in args.models:
        short = model_name.split("/")[-1]
        tok = AutoTokenizer.from_pretrained(model_name)
        model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.bfloat16).cuda().eval()
        pool = V.MediaPool("/tmp/media_" + short)
        for mode, fs in (("zeroshot", []), ("shot5", fewshot)):
            if mode not in args.modes:
                continue
            print(f"=== {model_name} / {mode} on {len(test_rows)} rows ===", flush=True)
            res = score_rows(test_rows, short, mode, pool, fs, model, tok)
            # preserve raw generations before any aggregation can fail
            all_results[f"{short}/{mode}"] = {"rows": res}
            push_results(all_results, args.out, suffix="_" + short)
            agg = aggregate(res)
            seen = [r for r in res if r["seen"]]
            unseen = [r for r in res if not r["seen"]]
            agg["seen"] = aggregate(seen)
            agg["unseen"] = aggregate(unseen)
            all_results[f"{short}/{mode}"] = {"aggregate": agg, "rows": res}
            push_results(all_results, args.out, suffix="_" + short)
            print(json.dumps(agg, indent=1), flush=True)
            try:
                from trackio import init, log, finish
                init(project="ffmpeg-nl2cmd", space_id="joemaddalone/ffmpeg-nl2cmd-trackio",
                     run_name=f"baseline-{short}-{mode}")
                for k in ("valid_all", "executes_runs", "static_valid", "exact_match",
                          "token_f1", "hallucination_rate", "format_ok"):
                    if agg.get(k) is not None:
                        log({k: agg[k]}, step=0)
                finish()
            except Exception as e:
                print(f"trackio skipped: {e}", flush=True)
        del model
        torch.cuda.empty_cache()

    with open(os.path.join(args.out, "baseline_results.json"), "w") as f:
        json.dump(all_results, f, indent=1)
    print("DONE", flush=True)


if __name__ == "__main__":
    main()