| |
| |
| |
| |
| """Proper eval of sakthai-plus models on sakthai-bench-v2. |
| |
| Uses tokenizer.apply_chat_template with tools= (identical to training rendering). |
| Env: MODEL, SAMPLE, BATCH, MAX_NEW, DUMP |
| """ |
| import os, json, re, time, collections, urllib.request |
| import torch |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
|
|
| MODEL = os.environ.get("MODEL", "Nanthasit/sakthai-plus-1.5b") |
| BATCH = int(os.environ.get("BATCH", "1")) |
| SAMPLE = int(os.environ.get("SAMPLE", "50")) |
| MAX_NEW = int(os.environ.get("MAX_NEW", "128")) |
| DUMP = int(os.environ.get("DUMP", "3")) |
|
|
| URL = "https://huggingface.co/datasets/Nanthasit/sakthai-bench-v2/resolve/main/data/test.jsonl" |
| print(f"Loading {URL} ...", flush=True) |
| with urllib.request.urlopen(URL) as f: |
| TEST = [json.loads(line) for line in f.read().decode().strip().splitlines()] |
| if SAMPLE: |
| import random |
| random.seed(42) |
| TEST = random.sample(TEST, min(SAMPLE, len(TEST))) |
| print(f"Loaded {len(TEST)} test rows", flush=True) |
|
|
| def parse_tool_calls(text): |
| calls = [] |
| for m in re.finditer(r'<tool_call>\s*(.*?)\s*</tool_call>', text, re.DOTALL): |
| try: |
| obj = json.loads(m.group(1)) |
| args = obj.get("arguments", {}) |
| if isinstance(args, str): |
| try: |
| args = json.loads(args) |
| except json.JSONDecodeError: |
| pass |
| calls.append({"name": obj.get("name", ""), "arguments": args}) |
| except json.JSONDecodeError: |
| pass |
| return calls |
|
|
| def norm_args(a): |
| if isinstance(a, str): |
| try: |
| a = json.loads(a) |
| except json.JSONDecodeError: |
| return str(a) |
| if isinstance(a, dict): |
| return {k: norm_args(v) for k, v in sorted(a.items()) if v is not None} |
| return a |
|
|
| def norm_call(c): |
| return {"name": c.get("name", ""), "arguments": norm_args(c.get("arguments", {}))} |
|
|
| def match_score(gold_calls, pred_calls): |
| gs = {json.dumps(norm_call(c), sort_keys=True) for c in gold_calls} |
| ps = {json.dumps(norm_call(c), sort_keys=True) for c in pred_calls} |
| if not gs and not ps: |
| return True, True |
| correct = gs == ps |
| args_ok = all(any(g["name"] == p["name"] and g["arguments"] == p["arguments"] |
| for p in pred_calls) for g in gold_calls) if pred_calls else False |
| return correct, args_ok |
|
|
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| print(f"Device: {device}", flush=True) |
|
|
| print(f"Loading tokenizer {MODEL} ...", flush=True) |
| tokenizer = AutoTokenizer.from_pretrained(MODEL) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
| tokenizer.padding_side = "left" |
|
|
| print(f"Loading model {MODEL} ...", flush=True) |
| model = AutoModelForCausalLM.from_pretrained( |
| MODEL, |
| torch_dtype=torch.float16, |
| device_map="auto" if device == "cuda" else None, |
| low_cpu_mem_usage=True, |
| ).to(device) |
| model.eval() |
| print("Model loaded", flush=True) |
|
|
| results = collections.defaultdict(lambda: {"sel": [], "args": [], "strict": []}) |
| held_results = collections.defaultdict(lambda: {"sel": [], "args": [], "strict": []}) |
|
|
| t0 = time.time() |
| for i in range(0, len(TEST), BATCH): |
| batch = TEST[i:i + BATCH] |
| prompts = [] |
| for row in batch: |
| msgs = list(row.get("messages", [])) |
| while msgs and msgs[-1].get("role") in ("assistant", "tool"): |
| msgs.pop() |
| prompts.append(tokenizer.apply_chat_template( |
| msgs, tools=row.get("tools") or None, |
| tokenize=False, add_generation_prompt=True, |
| )) |
|
|
| inputs = tokenizer(prompts, return_tensors="pt", padding=True, truncation=True, max_length=2048).to(device) |
| with torch.no_grad(): |
| outputs = model.generate( |
| **inputs, |
| max_new_tokens=MAX_NEW, |
| do_sample=False, |
| pad_token_id=tokenizer.pad_token_id, |
| ) |
|
|
| for j, row in enumerate(batch): |
| input_len = inputs["input_ids"].shape[1] |
| gen = tokenizer.decode(outputs[j][input_len:], skip_special_tokens=True) |
| pred_calls = parse_tool_calls(gen) |
| gold_calls = row.get("gold_calls", []) |
| category = row.get("category", "unknown") |
| held = row.get("held_out_tool", False) |
|
|
| correct, args_ok = match_score(gold_calls, pred_calls) |
| target = held_results if held else results |
| target[category]["sel"].append(correct) |
| target[category]["args"].append(args_ok) |
| target[category]["strict"].append(correct and args_ok) |
|
|
| if DUMP and j < DUMP: |
| print(f"\n--- Row {i + j} ({category}) ---", flush=True) |
| print(f"GOLD: {gold_calls}", flush=True) |
| print(f"PRED: {pred_calls}", flush=True) |
| print(f"RAW: {gen[:200]!r}", flush=True) |
| print(f"CORRECT: {correct}", flush=True) |
|
|
| elapsed = time.time() - t0 |
| print(f" [{i + len(batch)}/{len(TEST)}] {elapsed:.0f}s elapsed", flush=True) |
|
|
| print("\n" + "=" * 60) |
| print("RESULTS") |
| print("=" * 60) |
| all_sel, all_args, all_strict = [], [], [] |
| for cat in sorted(results): |
| r = results[cat] |
| n = len(r["sel"]) |
| sel = sum(r["sel"]) / n * 100 if n else 0 |
| args = sum(r["args"]) / n * 100 if n else 0 |
| strict = sum(r["strict"]) / n * 100 if n else 0 |
| all_sel.extend(r["sel"]); all_args.extend(r["args"]); all_strict.extend(r["strict"]) |
| print(f" {cat:20s} selection={sel:.1f} arguments={args:.1f} strict={strict:.1f} n={n}") |
|
|
| if all_sel: |
| n = len(all_sel) |
| print(f"\n {'AVERAGE':20s} selection={sum(all_sel)/n*100:.1f} arguments={sum(all_args)/n*100:.1f} strict={sum(all_strict)/n*100:.1f} n={n}") |
|
|
| hs, ha, hst = [], [], [] |
| for cat in sorted(held_results): |
| r = held_results[cat] |
| hs.extend(r["sel"]); ha.extend(r["args"]); hst.extend(r["strict"]) |
| if hs: |
| n = len(hs) |
| print(f"\n {'HELD AVG':20s} selection={sum(hs)/n*100:.1f} arguments={sum(ha)/n*100:.1f} strict={sum(hst)/n*100:.1f} n={n}") |
|
|
| print(f"\nTotal time: {time.time() - t0:.0f}s") |
|
|