File size: 19,553 Bytes
5118ad4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
"""Unified Head-to-Head Evaluation Suite for Family #9: Tamarillo/prompt-complexity-router.

Evaluates on identical A100 GPU & all 7 frozen suites:
  1. ood_mt_bench               (CC-BY-4.0, real human strong-vs-weak battles: ROC-AUC & RouteLLM APGR!)
  2. ood_arena_non_en           (Apache-2.0, ALL non-English Arena-55k human battles: ROC-AUC & APGR!)
  3. ood_length_inverted        (n=1,200, 100% dataset-disjoint: short hard vs long simple -> ROC-AUC, F1, TPR@5%FPR!)
  4. ood_multilingual_mgsm_aya  (n=500, MGSM test vs Aya eval -> ROC-AUC, F1, TPR@5%FPR)
  5. ood_long_multiturn_2k      (n=300, ~1,300-1,800 tok -> exposes 512/514-tok truncation cliff!)
  6. id_helpsteer2_val          (real human 0-4 complexity -> Spearman rho, Pearson r, High-vs-Low AUC)
  7. id_arena_en_test           (held-out English Arena-55k human battles -> ROC-AUC & APGR!)

Supports baselines:
  - routellm/bert_gpt4_augmented (161.7K dl/mo, exact BERTRouter formula: softmax[0])
  - nvidia/prompt-task-and-complexity-classifier (16.5K dl/mo, exact README CustomModel prompt_complexity_score)
  - MoritzLaurer/deberta-v3-base-zeroshot-v2.0 (zero-shot complexity baseline)
  - length-heuristic (len(prompt) anti-shortcut baseline!)
  - Tamarillo 3-class routers passed via --tamarillo-models name=path ...
"""

from __future__ import annotations

import argparse
import gc
import json
import math
import os
import statistics
import time
from pathlib import Path
from typing import Any

import numpy as np
import torch
import torch.nn as nn
from huggingface_hub import PyTorchModelHubMixin
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import f1_score, roc_auc_score, roc_curve
from transformers import AutoConfig, AutoModel, AutoModelForSequenceClassification, AutoTokenizer

NLI_HYPOTHESIS = "This user prompt is complex and requires an advanced frontier reasoning model rather than a small fast model."


def load_jsonl(p: Path) -> list[dict[str, Any]]:
    with p.open("r", encoding="utf-8") as f:
        return [json.loads(ln) for ln in f if ln.strip()]


def _tpr_at_fpr(y: np.ndarray, s: np.ndarray, target: float) -> float:
    fpr, tpr, _ = roc_curve(y, s)
    idxs = np.where(fpr <= target)[0]
    return float(tpr[idxs[-1]]) if len(idxs) else 0.0


def compute_apgr(labels: np.ndarray, scores: np.ndarray) -> dict[str, float]:
    """Compute exact RouteLLM Cost-Quality APGR (Average Performance Gain Ratio) on strong-vs-weak battles.
    For each strong-model call fraction c in {0.1, 0.2, ..., 0.9}:
      - Top c fraction of prompts (highest score) routed to Strong model: win_rate = 1 if label==0 else (0.5 if label==1 else 0)
      - Remaining (1-c) routed to Weak model: win_rate = 1 if label==2 else (0.5 if label==1 else 0)
      Actually standard RouteLLM battle utility: Strong achieves 1.0 on strong-wins/ties and weak achieves 1.0 on weak-wins/ties:
        strong_ok = (labels != 2).astype(float)  # strong wins or ties
        weak_ok   = (labels != 0).astype(float)  # weak wins or ties
      Random routing gain at budget c = weak_mean + c * (strong_mean - weak_mean).
      APGR = mean_c [ (routed_perf(c) - weak_mean) / (strong_mean - weak_mean) ] - 0.50 (gain over random 0.50!)
      We report raw normalized area under cost-quality curve (0.50 = random, 1.0 = oracle) AND APGR (area / oracle_area).
    """
    strong_ok = (labels != 2).astype(np.float64)
    weak_ok = (labels != 0).astype(np.float64)
    w_mean = float(weak_ok.mean())
    s_mean = float(strong_ok.mean())
    denom = max(1e-6, s_mean - w_mean)

    order = np.argsort(-scores)  # highest score -> strong model first
    n = len(labels)
    gains = []
    # Also compute oracle upper bound on these exact battles
    oracle_order = np.argsort(-(strong_ok - weak_ok))
    oracle_gains = []
    for c in np.linspace(0.1, 0.9, 9):
        k = int(round(c * n))
        # Router choice
        routed = weak_ok.copy()
        routed[order[:k]] = strong_ok[order[:k]]
        gains.append((float(routed.mean()) - w_mean) / denom)
        # Oracle choice
        orac = weak_ok.copy()
        orac[oracle_order[:k]] = strong_ok[oracle_order[:k]]
        oracle_gains.append((float(orac.mean()) - w_mean) / denom)

    avg_gain = float(np.mean(gains))
    avg_oracle = max(1e-6, float(np.mean(oracle_gains)))
    return {
        "apgr_vs_oracle": round(avg_gain / avg_oracle, 4),
        "avg_normalized_gain": round(avg_gain, 4),  # 0.50 = random routing
        "gain_over_random_pp": round((avg_gain - 0.5) * 100.0, 2),
        "perf_at_50pct_strong": round(gains[4], 4),
    }


def compute_autobench_apgr(rows: list[dict[str, Any]], scores: np.ndarray) -> dict[str, float]:
    """Compute exact 2026 Cost-Quality APGR on AutoBench/router-benchmark-2026-10 using real 10-judge scores!"""
    s_sc = np.array([float(r["strong_score"]) for r in rows], dtype=np.float64)
    w_sc = np.array([float(r["weak_score"]) for r in rows], dtype=np.float64)
    gap = s_sc - w_sc
    w_mean = float(w_sc.mean())
    s_mean = float(s_sc.mean())
    denom = max(1e-6, s_mean - w_mean)

    order = np.argsort(-scores)
    oracle_order = np.argsort(-gap)
    n = len(rows)
    gains, ogains = [], []
    for c in np.linspace(0.1, 0.9, 9):
        k = int(round(c * n))
        routed = w_sc.copy()
        routed[order[:k]] = s_sc[order[:k]]
        gains.append((float(routed.mean()) - w_mean) / denom)
        orac = w_sc.copy()
        orac[oracle_order[:k]] = s_sc[oracle_order[:k]]
        ogains.append((float(orac.mean()) - w_mean) / denom)
    avg_g = float(np.mean(gains))
    avg_o = max(1e-6, float(np.mean(ogains)))
    rho = float(spearmanr(scores, gap).statistic)
    if math.isnan(rho):
        rho = 0.0
    y_bin = np.array([1 if int(r["label"]) == 0 else 0 for r in rows], dtype=int)
    auc = float(roc_auc_score(y_bin, scores))
    return {
        "roc_auc": round(auc, 4),
        "spearman_rho_gap": round(rho, 4),
        "apgr_vs_oracle": round(avg_g / avg_o, 4),
        "avg_normalized_gain": round(avg_g, 4),
        "gain_over_random_pp": round((avg_g - 0.5) * 100.0, 2),
        "perf_at_50pct_strong": round(gains[4], 4),
    }


def score_suite(sname: str, rows: list[dict[str, Any]], scores: np.ndarray) -> dict[str, Any]:
    s = np.nan_to_num(scores.astype(np.float64), nan=0.5)
    labels = np.array([int(r["label"]) for r in rows], dtype=np.int64)
    out: dict[str, Any] = {"n": int(len(rows))}

    if sname == "ood_autobench_2026":
        out.update(compute_autobench_apgr(rows, s))
        return out

    if sname in ("heldout_arena140k_en", "heldout_arena140k_non_en"):
        csum = np.array([float(r["criteria_sum"]) for r in rows], dtype=np.float64)
        rho = float(spearmanr(s, csum).statistic)
        pr = float(pearsonr(s, csum).statistic)
        m02 = (labels == 0) | (labels == 2)
        auc_02 = float(roc_auc_score((labels[m02] == 0).astype(int), s[m02]))
        auc_s = float(roc_auc_score((labels == 0).astype(int), s))
        t5 = _tpr_at_fpr((labels[m02] == 0).astype(int), s[m02], 0.05)
        out.update({
            "roc_auc_hard_vs_easy": round(auc_02, 4),
            "roc_auc_hard_vs_rest": round(auc_s, 4),
            "spearman_rho_criteria": round(rho, 4),
            "pearson_r_criteria": round(pr, 4),
            "tpr_at_5fpr": round(t5, 4),
        })
        return out

    if sname == "id_helpsteer2_val":
        hc = np.array([float(r["human_complexity"]) for r in rows], dtype=np.float64)
        rho = float(spearmanr(s, hc).statistic)
        pr = float(pearsonr(s, hc).statistic)
        m_hl = (hc >= 2.5) | (hc <= 1.5)
        auc_hl = float(roc_auc_score((hc[m_hl] >= 2.5).astype(int), s[m_hl]))
        out.update({"spearman_rho": round(rho, 4), "pearson_r": round(pr, 4), "auc_high_vs_low": round(auc_hl, 4)})
        return out

    if sname in ("ood_mt_bench", "ood_arena_non_en", "id_arena_en_test", "heldout_arena55k_battles"):
        y_strong = (labels == 0).astype(int)
        m02 = (labels == 0) | (labels == 2)
        auc_s = float(roc_auc_score(y_strong, s))
        auc_02 = float(roc_auc_score((labels[m02] == 0).astype(int), s[m02]))
        apgr = compute_apgr(labels, s)
        out.update({"roc_auc_strong_vs_weak": round(auc_02, 4), "roc_auc_strong_vs_rest": round(auc_s, 4), **apgr})
        return out

    # Binary 0 (Complex/Strong) vs 2 (Simple/Weak) suites
    y = (labels == 0).astype(int)
    auc = float(roc_auc_score(y, s))
    t5 = _tpr_at_fpr(y, s, 0.05)
    pred = (s >= 0.5).astype(int)
    mf1 = float(f1_score(y, pred, average="macro", zero_division=0))
    out.update({"roc_auc": round(auc, 4), "macro_f1_at_050": round(mf1, 4), "tpr_at_5fpr": round(t5, 4)})
    return out


# Official NVIDIA Prompt Task and Complexity Classifier wrapper (copied from NVIDIA HF model card)
class _MeanPooling(nn.Module):
    def forward(self, last_hidden_state: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
        mask = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()
        return torch.sum(last_hidden_state * mask, 1) / torch.clamp(mask.sum(1), min=1e-9)


class _MulticlassHead(nn.Module):
    def __init__(self, input_size: int, num_classes: int) -> None:
        super().__init__()
        self.fc = nn.Linear(input_size, num_classes)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.fc(x)


class NvidiaNPCCModel(nn.Module, PyTorchModelHubMixin):
    def __init__(self, target_sizes, task_type_map, weights_map, divisor_map, **kwargs):
        super().__init__()
        self.backbone = AutoModel.from_pretrained("microsoft/DeBERTa-v3-base")
        self.target_sizes = list(target_sizes.values())
        self.task_type_map = task_type_map
        self.weights_map = weights_map
        self.divisor_map = divisor_map
        self.heads = [_MulticlassHead(self.backbone.config.hidden_size, sz) for sz in self.target_sizes]
        for i, head in enumerate(self.heads):
            self.add_module(f"head_{i}", head)
        self.pool = _MeanPooling()

    def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> list[torch.Tensor]:
        out = self.backbone(input_ids=input_ids, attention_mask=attention_mask)
        pooled = self.pool(out.last_hidden_state, attention_mask)
        return [head(pooled) for head in self.heads]

    def complexity_score(self, logits_list: list[torch.Tensor]) -> np.ndarray:
        # Exact official NVIDIA README formula:
        #   head_0=task_type, head_1=creativity_scope, head_2=reasoning, head_3=contextual_knowledge,
        #   head_4=number_of_few_shots, head_5=domain_knowledge, head_6=no_label_reason, head_7=constraint_ct
        head_map = {
            "creativity_scope": 1,
            "reasoning": 2,
            "contextual_knowledge": 3,
            "number_of_few_shots": 4,
            "domain_knowledge": 5,
            "constraint_ct": 7,
        }
        dims = {}
        for k, hidx in head_map.items():
            p = torch.softmax(logits_list[hidx].float(), dim=-1).cpu().numpy()
            w = np.array(self.weights_map[k], dtype=np.float64)
            sc = (p * w).sum(axis=-1) / float(self.divisor_map[k])
            if k == "number_of_few_shots":
                sc = np.where(sc >= 0.05, sc, 0.0)
            dims[k] = sc
        score = (
            0.35 * dims["creativity_scope"]
            + 0.25 * dims["reasoning"]
            + 0.15 * dims["constraint_ct"]
            + 0.15 * dims["domain_knowledge"]
            + 0.05 * dims["contextual_knowledge"]
            + 0.05 * dims["number_of_few_shots"]
        )
        return np.asarray(score, dtype=np.float32)


def bench_gpu(fn, n_runs: int = 20) -> float:
    with torch.no_grad():
        for _ in range(5):
            fn()
        torch.cuda.synchronize()
        ts = []
        for _ in range(n_runs):
            t0 = time.perf_counter()
            fn()
            torch.cuda.synchronize()
            ts.append((time.perf_counter() - t0) * 1000.0)
    return round(statistics.median(ts), 2)


def eval_hf_model(name: str, path_or_id: str, suites: dict[str, list[dict[str, Any]]]) -> dict[str, Any]:
    device = "cuda" if torch.cuda.is_available() else "cpu"
    low = path_or_id.lower()
    is_nvidia = "prompt-task-and-complexity-classifier" in low
    is_zs = "zeroshot" in low
    is_rllm = "routellm" in low

    if is_nvidia:
        cfg = AutoConfig.from_pretrained(path_or_id)
        tok = AutoTokenizer.from_pretrained(path_or_id)
        model = NvidiaNPCCModel.from_pretrained(
            path_or_id,
            target_sizes=cfg.target_sizes,
            task_type_map=cfg.task_type_map,
            weights_map=cfg.weights_map,
            divisor_map=cfg.divisor_map,
        ).to(device).eval()
        max_len = 512
        params_m = round(sum(p.numel() for p in model.parameters()) / 1e6, 2)
    else:
        cfg = AutoConfig.from_pretrained(path_or_id)
        if hasattr(cfg, "reference_compile"):
            cfg.reference_compile = False
        tok = AutoTokenizer.from_pretrained(path_or_id, use_fast=True)
        mtype = str(getattr(cfg, "model_type", "")).lower()
        kw = {"attn_implementation": "eager"} if "modernbert" in mtype else {}
        model = AutoModelForSequenceClassification.from_pretrained(path_or_id, config=cfg, torch_dtype=torch.float32, **kw).to(device).eval()
        mpe = int(getattr(cfg, "max_position_embeddings", 512) or 512)
        max_len = 512 if mpe in (512, 514) else 2048
        params_m = round(sum(p.numel() for p in model.parameters()) / 1e6, 2)

    print(f"\n================ {name} ({path_or_id}, {params_m}M, max_len={max_len}) ================", flush=True)
    res: dict[str, Any] = {"params_m": params_m, "max_len": max_len, "suites": {}}

    for sname, rows in suites.items():
        texts = [r["text"] for r in rows]
        bs = 8 if "long" in sname else 16
        scores = []
        for i in range(0, len(texts), bs):
            ch = texts[i : i + bs]
            if is_zs:
                enc = tok(ch, [NLI_HYPOTHESIS] * len(ch), padding=True, truncation=True, max_length=max_len, return_token_type_ids=False, return_tensors="pt")
            elif is_nvidia:
                # Official NVIDIA README format prepends "Prompt: "
                enc = tok([f"Prompt: {t}" for t in ch], padding=True, truncation=True, max_length=max_len, return_token_type_ids=False, return_tensors="pt")
            else:
                enc = tok(ch, padding=True, truncation=True, max_length=max_len, return_token_type_ids=False, return_tensors="pt")
            tin = {k: v.to(device) for k, v in enc.items() if k in ("input_ids", "attention_mask")}
            with torch.no_grad():
                if is_nvidia:
                    sc = model.complexity_score(model(**tin))
                else:
                    logits = model(**tin).logits.float()
                    probs = torch.softmax(logits, dim=-1).cpu().numpy()
                    if is_zs:
                        id2l = {int(k): str(v).lower() for k, v in (model.config.id2label or {}).items()}
                        idx = next((k for k, v in id2l.items() if "entail" in v and "not" not in v), 0)
                        sc = probs[:, idx]
                    elif is_rllm:
                        # Exact RouteLLM BERTRouter formula: 1 - (P[1] + P[2]) == P[0]
                        sc = 1.0 - (probs[:, 1] + probs[:, 2])
                    else:
                        # Tamarillo 3-class: exact RouteLLM P[0] on battle suites; continuous S = P[0] + 0.5*P[1] on complexity suites
                        if sname in ("ood_mt_bench", "ood_arena_non_en", "id_arena_en_test", "heldout_arena55k_battles"):
                            sc = probs[:, 0]
                        else:
                            sc = probs[:, 0] + 0.5 * probs[:, 1]
            scores.append(sc)
        all_s = np.concatenate(scores)
        met = score_suite(sname, rows, all_s)
        res["suites"][sname] = met
        print(f"  {sname:28s}: {met}", flush=True)

    # Latency benchmark on GPU
    if device == "cuda":
        for sl in (64, 512, 2048):
            eff = min(sl, max_len)
            txt = "Design a distributed consensus algorithm handling Byzantine faults across five asynchronous nodes. " * 60
            enc = tok([txt], [NLI_HYPOTHESIS], padding="max_length", truncation=True, max_length=eff, return_token_type_ids=False, return_tensors="pt") if is_zs else tok([txt], padding="max_length", truncation=True, max_length=eff, return_token_type_ids=False, return_tensors="pt")
            tin = {k: v.to(device) for k, v in enc.items() if k in ("input_ids", "attention_mask")}
            res[f"gpu_latency_{sl}"] = {"requested": sl, "effective": eff, "p50_ms": bench_gpu(lambda: model(**tin)), "gpu": torch.cuda.get_device_name(0)}

    del model
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    return res


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--eval-dir", type=str, required=True)
    parser.add_argument("--tamarillo-models", nargs="*", default=[])
    parser.add_argument("--include-baselines", action="store_true")
    parser.add_argument("--out-json", type=str, required=True)
    args = parser.parse_args()

    os.environ["HF_HOME"] = "/tmp/hf"
    os.environ["TORCH_COMPILE_DISABLE"] = "1"
    if hasattr(torch, "_dynamo"):
        torch._dynamo.config.disable = True

    edir = Path(args.eval_dir)
    suite_names = (
        "ood_length_inverted",
        "ood_autobench_2026",
        "ood_long_multiturn_2k",
        "ood_multilingual_mgsm_aya",
        "heldout_arena140k_en",
        "heldout_arena140k_non_en",
        "heldout_arena55k_battles",
        "ood_mt_bench",
        "ood_arena_non_en",
        "id_helpsteer2_val",
        "id_arena_en_test",
    )
    suites = {k: load_jsonl(edir / f"{k}.jsonl") for k in suite_names if (edir / f"{k}.jsonl").exists()}

    report: dict[str, Any] = {"models": {}}

    if args.include_baselines:
        # 0. Token-Length Heuristic baseline (anti-shortcut check!)
        lh: dict[str, Any] = {"params_m": 0.0, "max_len": 999999, "suites": {}}
        print("\n================ length-heuristic ================", flush=True)
        for sname, rows in suites.items():
            raw_l = np.array([len(r["text"]) for r in rows], dtype=np.float64)
            s_norm = raw_l / max(1.0, float(raw_l.max()))
            lh["suites"][sname] = score_suite(sname, rows, s_norm)
            print(f"  {sname:28s}: {lh['suites'][sname]}", flush=True)
        report["models"]["length-heuristic"] = lh

        for bname, repo in [
            ("routellm-bert-gpt4-aug", "routellm/bert_gpt4_augmented"),
            ("nvidia-prompt-complexity", "nvidia/prompt-task-and-complexity-classifier"),
            ("moritz-deberta-zeroshot", "MoritzLaurer/deberta-v3-base-zeroshot-v2.0"),
        ]:
            try:
                report["models"][bname] = eval_hf_model(bname, repo, suites)
            except Exception as e:
                print(f"[ERROR] {bname}: {e}", flush=True)
                report["models"][bname] = {"error": str(e)}

    for spec in args.tamarillo_models:
        k, v = spec.split("=", 1)
        report["models"][k] = eval_hf_model(k, v, suites)

    out = Path(args.out_json)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(f"\n[DONE] Saved {out}", flush=True)


if __name__ == "__main__":
    main()