#!/usr/bin/env python3 """ BFCL-style eval for the SakThai 0.5B on the held-out combined-v6 `test` split (113). Measures the numbers that actually matter for this model: • simple — exactly 1 gold tool call -> did it call the right function? • parallel — >1 gold tool calls -> did it cover all of them? • irrelevance — 0 gold tool calls (direct) -> did it correctly NOT call a tool? This is a pragmatic BFCL-STYLE harness (function-name / abstention scoring), not the official Berkeley leaderboard. Run it on the OLD repo and the NEW one to get a before/after. Free — runs on a T4 (or CPU for the 0.5B, just slower). MODEL_ID=Nanthasit/sakthai-context-0.5b-merged python eval_bfcl_0.5b.py """ import os, re, json, collections import torch from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer MODEL_ID = os.environ.get("MODEL_ID", "Nanthasit/sakthai-context-0.5b-merged") MAX_NEW = 256 print(f"Model: {MODEL_ID}") tok = AutoTokenizer.from_pretrained(MODEL_ID) model = AutoModelForCausalLM.from_pretrained( MODEL_ID, torch_dtype=torch.bfloat16, device_map="auto" if torch.cuda.is_available() else None, ) model.eval() test = load_dataset("Nanthasit/sakthai-combined-v6", split="test") _TC = re.compile(r"\s*(\{.*?\})\s*", re.DOTALL) def gold_calls(msg): """Function names the gold assistant turn calls (OpenAI tool_calls or inline).""" names = [] for tc in (msg.get("tool_calls") or []): fn = (tc.get("function") or {}).get("name") if fn: names.append(fn) if not names: # some rows embed the call in content for m in _TC.findall(msg.get("content") or ""): try: names.append(json.loads(m).get("name")) except Exception: pass return [n for n in names if n] def pred_calls(text): """Function names the model emitted in its generated text.""" names = [] for m in _TC.findall(text): try: names.append(json.loads(m).get("name")) except Exception: pass return [n for n in names if n] def first_assistant_idx(msgs): for i, m in enumerate(msgs): if m.get("role") == "assistant": return i return None buckets = collections.defaultdict(lambda: [0, 0]) # category -> [correct, total] for ex in test: msgs = ex["messages"] tools = ex.get("tools") or None idx = first_assistant_idx(msgs) if idx is None or idx == 0: continue prompt_msgs, gold = msgs[:idx], msgs[idx] gold_names = gold_calls(gold) cat = "irrelevance" if not gold_names else ("simple" if len(gold_names) == 1 else "parallel") inputs = tok.apply_chat_template( prompt_msgs, tools=tools, add_generation_prompt=True, return_tensors="pt", ).to(model.device) with torch.no_grad(): out = model.generate(inputs, max_new_tokens=MAX_NEW, do_sample=False, pad_token_id=tok.eos_token_id) gen = tok.decode(out[0][inputs.shape[1]:], skip_special_tokens=True) pred_names = pred_calls(gen) if cat == "irrelevance": ok = len(pred_names) == 0 # correct = abstained elif cat == "simple": ok = gold_names[0] in pred_names # right function called else: # parallel ok = set(gold_names).issubset(set(pred_names)) # covered all gold calls buckets[cat][0] += int(ok) buckets[cat][1] += 1 print(f"\nBFCL-style results — {MODEL_ID}") print(f"{'category':<14}{'pass':>6}{'total':>7}{'acc':>8}") tc = tt = 0 for cat in ("simple", "parallel", "irrelevance"): c, t = buckets[cat] tc += c; tt += t acc = f"{100*c/t:5.1f}%" if t else " n/a" print(f"{cat:<14}{c:>6}{t:>7}{acc:>8}") print(f"{'OVERALL':<14}{tc:>6}{tt:>7}{(f'{100*tc/tt:5.1f}%' if tt else ' n/a'):>8}") print("\nNote: BFCL-STYLE (function-name / abstention scoring), not official BFCL.")