Datasets:
Tasks:
Text Generation
Languages:
English
Size:
n<1K
Tags:
code
notebooks
training-scripts
dataset:Nanthasit/sakthai-kaggle-notebooks
license-mit
dataset-card
License:
Upload scripts/eval_sakthai_15b_v2_fixed.py with huggingface_hub
Browse files
scripts/eval_sakthai_15b_v2_fixed.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# /// script
|
| 3 |
+
# dependencies = ["torch", "transformers", "accelerate"]
|
| 4 |
+
# ///
|
| 5 |
+
"""Evaluate sakthai-context-1.5b-merged-v2 on sakthai-bench-v2.
|
| 6 |
+
|
| 7 |
+
Loads raw test.jsonl directly (bypasses Hub metadata bug).
|
| 8 |
+
No Dataset/Arrow — works on raw list of dicts.
|
| 9 |
+
"""
|
| 10 |
+
import os, json, re, gc, time, collections, urllib.request, sys
|
| 11 |
+
from collections import Counter
|
| 12 |
+
import torch
|
| 13 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 14 |
+
|
| 15 |
+
MODEL = "Nanthasit/sakthai-context-1.5b-merged-v2"
|
| 16 |
+
BATCH = 4 # small for CPU
|
| 17 |
+
DUMP = 0
|
| 18 |
+
|
| 19 |
+
# ── Load raw JSONL (list of dicts, no Dataset) ────────────────
|
| 20 |
+
URL = "https://huggingface.co/datasets/Nanthasit/sakthai-bench-v2/resolve/main/data/test.jsonl"
|
| 21 |
+
print(f"Loading {URL} ...")
|
| 22 |
+
with urllib.request.urlopen(URL) as f:
|
| 23 |
+
TEST = [json.loads(line) for line in f.read().decode().strip().splitlines()]
|
| 24 |
+
print(f"Loaded {len(TEST)} test rows")
|
| 25 |
+
|
| 26 |
+
# ── Renderer ──────────────────────────────────────────────────
|
| 27 |
+
def _text(c):
|
| 28 |
+
return "" if c is None else (c if isinstance(c, str) else json.dumps(c, ensure_ascii=False))
|
| 29 |
+
|
| 30 |
+
def _tools_block(tools):
|
| 31 |
+
if not tools: return ""
|
| 32 |
+
sigs = "\n".join(json.dumps(t, ensure_ascii=False) for t in tools)
|
| 33 |
+
return ("\n\n# Tools\n\nYou may call one or more functions. Signatures are within "
|
| 34 |
+
"<tools></tools>:\n<tools>\n" + sigs + "\n</tools>\n\nFor each call return:\n"
|
| 35 |
+
"<tool_call>\n{\"name\": <name>, \"arguments\": <json>}\n</tool_call>")
|
| 36 |
+
|
| 37 |
+
def _assistant_body(m):
|
| 38 |
+
body = _text(m.get("content"))
|
| 39 |
+
for tc in (m.get("tool_calls") or []):
|
| 40 |
+
fn = tc.get("function", tc); a = fn.get("arguments", "{}")
|
| 41 |
+
if not isinstance(a, str): a = json.dumps(a, ensure_ascii=False)
|
| 42 |
+
body += ("\n" if body else "") + '<tool_call>\n{"name": "%s", "arguments": %s}\n</tool_call>' % (fn.get("name", ""), a)
|
| 43 |
+
return body
|
| 44 |
+
|
| 45 |
+
def _render_msg(m, tools_sys):
|
| 46 |
+
r = m.get("role")
|
| 47 |
+
if r == "system": return "<|im_start|>system\n" + _text(m.get("content")) + _tools_block(tools_sys) + "<|im_end|>\n"
|
| 48 |
+
if r == "user": return "<|im_start|>user\n" + _text(m.get("content")) + "<|im_end|>\n"
|
| 49 |
+
if r == "tool": return "<|im_start|>user\n<tool_response>\n" + _text(m.get("content")) + "\n</tool_response><|im_end|>\n"
|
| 50 |
+
if r == "assistant": return "<|im_start|>assistant\n" + _assistant_body(m) + "<|im_end|>\n"
|
| 51 |
+
return ""
|
| 52 |
+
|
| 53 |
+
def render_prompt(row):
|
| 54 |
+
tools = row.get("tools", [])
|
| 55 |
+
msgs = row.get("messages", [])
|
| 56 |
+
prompt = ""
|
| 57 |
+
for i, m in enumerate(msgs):
|
| 58 |
+
prompt += _render_msg(m, tools if i == 0 else [])
|
| 59 |
+
prompt += "<|im_start|>assistant\n"
|
| 60 |
+
return prompt
|
| 61 |
+
|
| 62 |
+
# ── Scorer ────────────────────────────────────────────────────
|
| 63 |
+
def parse_tool_calls(text):
|
| 64 |
+
calls = []
|
| 65 |
+
for m in re.finditer(r'<tool_call>\s*\{(.*?)\}\s*</tool_call>', text, re.DOTALL):
|
| 66 |
+
try:
|
| 67 |
+
obj = json.loads("{" + m.group(1) + "}")
|
| 68 |
+
calls.append({"name": obj.get("name", ""), "arguments": obj.get("arguments", {})})
|
| 69 |
+
except json.JSONDecodeError:
|
| 70 |
+
pass
|
| 71 |
+
return calls
|
| 72 |
+
|
| 73 |
+
def norm_args(a):
|
| 74 |
+
if isinstance(a, str):
|
| 75 |
+
try: a = json.loads(a)
|
| 76 |
+
except json.JSONDecodeError: return str(a)
|
| 77 |
+
if isinstance(a, dict):
|
| 78 |
+
return {k: norm_args(v) for k, v in sorted(a.items()) if v is not None}
|
| 79 |
+
return a
|
| 80 |
+
|
| 81 |
+
def norm_call(c):
|
| 82 |
+
return {"name": c.get("name", ""), "arguments": norm_args(c.get("arguments", {}))}
|
| 83 |
+
|
| 84 |
+
def match_score(gold_calls, pred_calls):
|
| 85 |
+
gs = {json.dumps(norm_call(c), sort_keys=True) for c in gold_calls}
|
| 86 |
+
ps = {json.dumps(norm_call(c), sort_keys=True) for c in pred_calls}
|
| 87 |
+
if not gs and not ps: return True, True
|
| 88 |
+
correct = gs == ps
|
| 89 |
+
args_ok = all(any(g["name"] == p["name"] and g["arguments"] == p["arguments"]
|
| 90 |
+
for p in pred_calls) for g in gold_calls) if pred_calls else False
|
| 91 |
+
return correct, args_ok
|
| 92 |
+
|
| 93 |
+
# ── Main ──────────────────────────────────────────────────────
|
| 94 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 95 |
+
print(f"Device: {device}")
|
| 96 |
+
|
| 97 |
+
print(f"Loading tokenizer {MODEL} ...")
|
| 98 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL)
|
| 99 |
+
if tokenizer.pad_token is None:
|
| 100 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 101 |
+
tokenizer.padding_side = "left"
|
| 102 |
+
|
| 103 |
+
print(f"Loading model {MODEL} ...")
|
| 104 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 105 |
+
MODEL,
|
| 106 |
+
torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32,
|
| 107 |
+
device_map="auto" if device == "cuda" else None,
|
| 108 |
+
).to(device)
|
| 109 |
+
model.eval()
|
| 110 |
+
print("Model loaded")
|
| 111 |
+
|
| 112 |
+
results = collections.defaultdict(lambda: {"sel": [], "args": [], "strict": []})
|
| 113 |
+
held_results = collections.defaultdict(lambda: {"sel": [], "args": [], "strict": []})
|
| 114 |
+
|
| 115 |
+
t0 = time.time()
|
| 116 |
+
for i in range(0, len(TEST), BATCH):
|
| 117 |
+
batch = TEST[i:i + BATCH]
|
| 118 |
+
prompts = [render_prompt(row) for row in batch]
|
| 119 |
+
|
| 120 |
+
inputs = tokenizer(prompts, return_tensors="pt", padding=True, truncation=True, max_length=4096).to(device)
|
| 121 |
+
with torch.no_grad():
|
| 122 |
+
outputs = model.generate(
|
| 123 |
+
**inputs,
|
| 124 |
+
max_new_tokens=512,
|
| 125 |
+
temperature=0.0,
|
| 126 |
+
do_sample=False,
|
| 127 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
for j, row in enumerate(batch):
|
| 131 |
+
input_len = inputs["input_ids"].shape[1]
|
| 132 |
+
gen = tokenizer.decode(outputs[j][input_len:], skip_special_tokens=True)
|
| 133 |
+
pred_calls = parse_tool_calls(gen)
|
| 134 |
+
gold_calls = row.get("gold_calls", [])
|
| 135 |
+
category = row.get("category", "unknown")
|
| 136 |
+
held = row.get("held_out_tool", False)
|
| 137 |
+
|
| 138 |
+
correct, args_ok = match_score(gold_calls, pred_calls)
|
| 139 |
+
target = held_results if held else results
|
| 140 |
+
target[category]["sel"].append(correct)
|
| 141 |
+
target[category]["args"].append(args_ok)
|
| 142 |
+
target[category]["strict"].append(correct and args_ok)
|
| 143 |
+
|
| 144 |
+
if DUMP and j < DUMP:
|
| 145 |
+
print(f"\n--- Row {i + j} ({category}) ---")
|
| 146 |
+
print(f"GOLD: {gold_calls}")
|
| 147 |
+
print(f"PRED: {pred_calls}")
|
| 148 |
+
print(f"CORRECT: {correct}")
|
| 149 |
+
|
| 150 |
+
elapsed = time.time() - t0
|
| 151 |
+
pct = (i + len(batch)) / len(TEST) * 100
|
| 152 |
+
rate = (i + len(batch)) / elapsed if elapsed > 0 else 0
|
| 153 |
+
print(f" [{i + len(batch)}/{len(TEST)}] {pct:.0f}% {rate:.2f} rows/s {elapsed:.0f}s elapsed", end="\r")
|
| 154 |
+
|
| 155 |
+
print("\n" + "=" * 60)
|
| 156 |
+
print("STANDARD (non-held-out) RESULTS")
|
| 157 |
+
print("=" * 60)
|
| 158 |
+
all_sel, all_args, all_strict = [], [], []
|
| 159 |
+
for cat in sorted(results):
|
| 160 |
+
r = results[cat]
|
| 161 |
+
n = len(r["sel"])
|
| 162 |
+
sel = sum(r["sel"]) / n * 100 if n else 0
|
| 163 |
+
args = sum(r["args"]) / n * 100 if n else 0
|
| 164 |
+
strict = sum(r["strict"]) / n * 100 if n else 0
|
| 165 |
+
all_sel.extend(r["sel"]); all_args.extend(r["args"]); all_strict.extend(r["strict"])
|
| 166 |
+
print(f" {cat:20s} selection={sel:.1f} arguments={args:.1f} strict={strict:.1f} n={n}")
|
| 167 |
+
|
| 168 |
+
n = len(all_sel)
|
| 169 |
+
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}")
|
| 170 |
+
|
| 171 |
+
print("\n" + "=" * 60)
|
| 172 |
+
print("HELD-OUT TOOL RESULTS")
|
| 173 |
+
print("=" * 60)
|
| 174 |
+
hs, ha, hst = [], [], []
|
| 175 |
+
for cat in sorted(held_results):
|
| 176 |
+
r = held_results[cat]
|
| 177 |
+
n = len(r["sel"])
|
| 178 |
+
sel = sum(r["sel"]) / n * 100 if n else 0
|
| 179 |
+
args = sum(r["args"]) / n * 100 if n else 0
|
| 180 |
+
strict = sum(r["strict"]) / n * 100 if n else 0
|
| 181 |
+
hs.extend(r["sel"]); ha.extend(r["args"]); hst.extend(r["strict"])
|
| 182 |
+
print(f" {cat:20s} selection={sel:.1f} arguments={args:.1f} strict={strict:.1f} n={n}")
|
| 183 |
+
|
| 184 |
+
if hs:
|
| 185 |
+
n = len(hs)
|
| 186 |
+
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}")
|
| 187 |
+
|
| 188 |
+
print(f"\nTotal time: {time.time() - t0:.0f}s")
|