File size: 12,899 Bytes
5e21013
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run the full benchmark matrix for one (base_model, adapter) cell.

Inputs:
  --base       HuggingFace model id (e.g. HuggingFaceTB/SmolLM2-360M-Instruct)
  --adapter    optional HF repo + branch (e.g. cuilabs/bee-cell:cybersecurity-2026-04-28-1221)
               If omitted, runs on the base model alone.
  --output-dir where to write the per-cell JSON (default: data/eval_reports/matrix/)
  --limit      cap questions per domain (smoke testing; default: all 12)

Outputs:
  data/eval_reports/matrix/<base_short>__<adapter_short>.json
    {
      "model": {...},
      "device": "...",
      "per_domain_eval": {
        "overall_score": 0.xx,
        "by_domain": {...},
        "judgments": [...]
      },
      "throughput": {"tok_per_s": ...},
      "started_at": "...",
      "completed_at": "...",
      "total_time_s": ...
    }

Why local-first instead of lighteval (for now): the per-domain eval is
the unique-value part of the Bee benchmark, lighteval doesn't have it,
and getting the local runner working end-to-end is the fastest path to
the matrix. The standard SmolLM-card-aligned suite (MMLU, HumanEval,
etc.) is queued as a follow-up — runs separately via lighteval, results
merge into the same matrix JSON.
"""
from __future__ import annotations

import argparse
import datetime
import json
import os
import sys
import time
from dataclasses import asdict
from pathlib import Path
from typing import Optional

REPO_ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(REPO_ROOT))

from scripts.eval.judge import (  # noqa: E402
    Judgment,
    aggregate_judgments,
    judge_one,
)


def _load_env_keys() -> dict[str, str]:
    env_path = REPO_ROOT / ".env"
    if not env_path.exists():
        return {}
    out: dict[str, str] = {}
    for line in env_path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, _, v = line.partition("=")
        out[k.strip()] = v.strip().strip('"').strip("'")
    return out


def _generate(model, tokenizer, prompt: str, max_new_tokens: int, device: str) -> str:
    """Generate one response. Uses chat template if available."""
    import torch  # noqa: E402

    if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template:
        chat = [{"role": "user", "content": prompt}]
        text = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
        inputs = tokenizer(text, return_tensors="pt").to(device)
    else:
        inputs = tokenizer(prompt, return_tensors="pt").to(device)

    with torch.no_grad():
        out = model.generate(
            **inputs,
            max_new_tokens=max_new_tokens,
            do_sample=False,                 # greedy for determinism
            pad_token_id=tokenizer.pad_token_id,
            eos_token_id=tokenizer.eos_token_id,
        )

    gen = out[0][inputs["input_ids"].shape[1]:]
    return tokenizer.decode(gen, skip_special_tokens=True).strip()


def _measure_throughput(model, tokenizer, device: str) -> dict:
    """5 prompts × 100 new tokens each, return aggregate tok/s.

    Mirrors data/eval_reports/2026-04-29_throughput_mps.json so all
    matrix cells have a comparable throughput number.
    """
    import torch  # noqa: E402

    prompts = [
        "Explain machine learning in one paragraph.",
        "Describe how a quantum computer works.",
        "What is a smart contract?",
        "How does gradient descent optimize a model?",
        "Summarize the basics of public-key cryptography.",
    ]

    # Warmup
    chat = [{"role": "user", "content": prompts[0]}]
    text = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
    ins = tokenizer(text, return_tensors="pt").to(device)
    with torch.no_grad():
        model.generate(**ins, max_new_tokens=8, do_sample=False, pad_token_id=tokenizer.pad_token_id)

    total_new = 0
    total_t = 0.0
    per_prompt = []
    for p in prompts:
        chat = [{"role": "user", "content": p}]
        text = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
        ins = tokenizer(text, return_tensors="pt").to(device)
        t0 = time.perf_counter()
        with torch.no_grad():
            o = model.generate(
                **ins, max_new_tokens=100, do_sample=False,
                pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id,
            )
        dt = time.perf_counter() - t0
        n = o.shape[1] - ins["input_ids"].shape[1]
        total_new += n
        total_t += dt
        per_prompt.append({"new_tokens": n, "seconds": round(dt, 3), "tok_per_s": round(n / dt, 1)})

    return {
        "max_new_tokens_per_prompt": 100,
        "decoding": "greedy",
        "per_prompt": per_prompt,
        "aggregate": {
            "total_new_tokens": total_new,
            "total_seconds": round(total_t, 3),
            "tok_per_s": round(total_new / max(total_t, 1e-6), 1),
        },
    }


def _load_model(base: str, adapter: Optional[str], device: str):
    """Load base model + optional LoRA adapter from cuilabs/bee-cell:branch.

    `adapter` format: "cuilabs/bee-cell:cybersecurity-2026-04-28-1221"
    (repo_id:branch). If None, returns base model alone.
    """
    import torch  # noqa: E402
    from transformers import AutoModelForCausalLM, AutoTokenizer  # noqa: E402

    tokenizer = AutoTokenizer.from_pretrained(base, trust_remote_code=True)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token

    dtype = torch.float16 if device == "mps" else None
    model = AutoModelForCausalLM.from_pretrained(
        base, trust_remote_code=True, torch_dtype=dtype,
    ).to(device)

    adapter_info = None
    if adapter:
        from peft import PeftModel  # noqa: E402
        if ":" in adapter:
            adapter_repo, adapter_branch = adapter.split(":", 1)
        else:
            adapter_repo, adapter_branch = adapter, None
        token = os.environ.get("HF_TOKEN") or _load_env_keys().get("HF_TOKEN")
        model = PeftModel.from_pretrained(
            model, adapter_repo,
            revision=adapter_branch,
            token=token,
        )
        adapter_info = {"repo": adapter_repo, "branch": adapter_branch}

    model.eval()
    n_params = sum(p.numel() for p in model.parameters()) / 1e6
    return model, tokenizer, {
        "base": base,
        "adapter": adapter_info,
        "params_m": round(n_params, 1),
    }


def run_per_domain_eval(
    model, tokenizer, device: str,
    eval_set: dict, judge_key: str,
    limit_per_domain: Optional[int] = None,
    judge_provider: str = "deepseek",
    judge_base_url: str = "https://api.deepseek.com/v1",
    judge_model: str = "deepseek-v4-pro",
) -> dict:
    """Run every question in eval_set, judge each answer, return aggregate.

    The judge_* trio is pinned for the entire batch so every judgment is
    apples-to-apples (no mid-batch grader switch). Caller passes the
    resolver-resolved primary in.
    """
    judgments: list[Judgment] = []
    raw_answers: list[dict] = []

    for domain, blob in eval_set["domains"].items():
        questions = blob["questions"]
        if limit_per_domain is not None:
            questions = questions[:limit_per_domain]
        for q in questions:
            prompt = q["prompt"]
            t0 = time.perf_counter()
            answer = _generate(model, tokenizer, prompt, max_new_tokens=512, device=device)
            gen_s = time.perf_counter() - t0

            j = judge_one(
                question_id=q["id"],
                domain=domain,
                prompt=prompt,
                rubric=q["rubric"],
                citation=q["citation"],
                model_answer=answer,
                api_key=judge_key,
                provider=judge_provider,
                base_url=judge_base_url,
                model=judge_model,
            )
            judgments.append(j)
            raw_answers.append({
                "id": q["id"],
                "domain": domain,
                "difficulty": q.get("difficulty"),
                "prompt": prompt,
                "answer": answer,
                "judge_label": j.label,
                "judge_reasoning": j.reasoning,
                "gen_s": round(gen_s, 2),
            })
            print(
                f"  [{q['id']:<22}] {j.label:<8} ({gen_s:.1f}s gen)  {q['prompt'][:60]}",
                flush=True,
            )

    agg = aggregate_judgments(judgments)
    return {
        "overall_score": agg["overall_score"],
        "n_total": agg["n_total"],
        "by_domain": agg["by_domain"],
        "answers": raw_answers,
    }


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("--base", required=True,
                   help="HF base model id, e.g. HuggingFaceTB/SmolLM2-360M-Instruct")
    p.add_argument("--adapter", default=None,
                   help="optional adapter as repo_id:branch, e.g. cuilabs/bee-cell:cybersecurity-2026-04-28-1221")
    p.add_argument("--device", default=None,
                   help="device override; default = mps if available, else cpu")
    p.add_argument("--output-dir", default=None,
                   help="default: data/eval_reports/matrix/")
    p.add_argument("--limit", type=int, default=None,
                   help="cap questions per domain (smoke testing)")
    args = p.parse_args()

    import torch  # noqa: E402

    device = args.device or ("mps" if torch.backends.mps.is_available() else "cpu")
    output_dir = Path(args.output_dir or REPO_ROOT / "data/eval_reports/matrix")
    output_dir.mkdir(parents=True, exist_ok=True)

    env = _load_env_keys()
    # Hydrate so resolve_judge() picks up keys from .env in fresh shells.
    for k, v in env.items():
        os.environ.setdefault(k, v)
    from judge import resolve_judge  # type: ignore[import-not-found]
    judge_provider, judge_base_url, judge_model, judge_key = resolve_judge()
    print(f"  judge: {judge_provider}:{judge_model} via {judge_base_url}")
    hf_token = env.get("HF_TOKEN") or os.environ.get("HF_TOKEN", "")
    if hf_token:
        os.environ["HF_TOKEN"] = hf_token
        os.environ["HUGGINGFACE_HUB_TOKEN"] = hf_token

    eval_set = json.loads(
        (REPO_ROOT / "scripts/eval/per_domain_eval_set.json").read_text(encoding="utf-8")
    )

    started = datetime.datetime.now(datetime.timezone.utc).isoformat()
    t_start = time.perf_counter()

    print(f"=== loading {args.base}" + (f" + {args.adapter}" if args.adapter else "") + f" on {device}")
    model, tokenizer, model_info = _load_model(args.base, args.adapter, device)
    print(f"  {model_info['params_m']:.1f}M params")

    print(f"\n=== throughput ({device})")
    throughput = _measure_throughput(model, tokenizer, device)
    print(f"  {throughput['aggregate']['tok_per_s']:.1f} tok/s aggregate")

    print(f"\n=== per-domain eval ({sum(len(b['questions']) for b in eval_set['domains'].values())} questions)")
    pd = run_per_domain_eval(
        model, tokenizer, device, eval_set, judge_key,
        limit_per_domain=args.limit,
        judge_provider=judge_provider,
        judge_base_url=judge_base_url,
        judge_model=judge_model,
    )

    completed = datetime.datetime.now(datetime.timezone.utc).isoformat()
    total = round(time.perf_counter() - t_start, 1)

    # Filename: <base-short>__<adapter-short>.json
    base_short = args.base.split("/")[-1]
    if args.adapter:
        adapter_short = args.adapter.replace(":", "__").split("/")[-1]
        out_name = f"{base_short}__{adapter_short}.json"
    else:
        out_name = f"{base_short}__base.json"
    out_path = output_dir / out_name

    report = {
        "model": model_info,
        "device": device,
        "started_at": started,
        "completed_at": completed,
        "total_time_s": total,
        "throughput": throughput,
        "per_domain_eval": {
            "judge_provider": judge_provider,
            "judge_model": judge_model,
            "overall_score": pd["overall_score"],
            "n_total": pd["n_total"],
            "by_domain": pd["by_domain"],
            "answers": pd["answers"],
        },
    }
    out_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")

    print(f"\n=== DONE in {total}s")
    print(f"  per-domain overall: {pd['overall_score']:.3f} ({pd['n_total']} questions)")
    print(f"  by domain:")
    for dom, d in sorted(pd["by_domain"].items()):
        print(f"    {dom:<18} {d['score']:.3f}  ({d['labels']['correct']}/{d['labels']['partial']}/{d['labels']['wrong']}/{d['labels']['refused']})")
    print(f"  throughput:         {throughput['aggregate']['tok_per_s']:.1f} tok/s")
    print(f"  saved:              {out_path}")


if __name__ == "__main__":
    main()