OPUS-5.5-DATABASE / code /train /eval_tools.py
KeremTT's picture
Update code
73f7e6f verified
Raw History Blame Contribute Delete
6.16 kB
"""Agentic tool-use evaluation on the `tools` test split (OPUS-synth-tools, verified).
The model gets the tool definitions through its chat template, may call tools (executed for
real by opusdb.agent_tools), receives the results and must produce a final answer. Scored:
* call_accuracy – the first assistant turn calls the right tool (or correctly calls none)
* answer_accuracy – the final answer contains the verified result (or a refusal / "undefined"
explanation for out_of_scope / tool_error items)
python train/eval_tools.py --model Qwen/Qwen2.5-1.5B-Instruct --limit 200
"""
import argparse
import json
import os
import re
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from opusdb import agent_tools # noqa: E402
from opusdb.tool_formats import hermes_system_prompt, to_chat_template # noqa: E402
REFUSAL = ("can't", "cannot", "unable", "not able", "don't have access", "yapamıyorum", "erişimim yok", "mümkün değil")
UNDEFINED = ("undefined", "division by zero", "divide by zero", "tanımsız", "sıfıra bölme")
def expected_first_tool(msgs):
first = msgs[1] if len(msgs) > 1 else {}
calls = first.get("tool_calls") or []
return calls[0]["function"]["name"] if calls else None
def answer_ok(family, answer, text):
t = text.lower()
if family == "tools-out_of_scope":
return any(p in t for p in REFUSAL)
if family == "tools-tool_error":
return any(p in t for p in UNDEFINED)
if answer in ("DIRECT",):
return len(t.strip()) > 0
nums = re.findall(r"-?\d[\d,]*\.?\d*", answer)
if not nums:
return answer.lower() in t
got = [g.replace(",", "") for g in re.findall(r"-?\d[\d,]*\.?\d*", text)]
def close(a, b):
try:
a, b = float(a.replace(",", "")), float(b)
return abs(a - b) <= max(0.01, abs(a) * 1e-4)
except ValueError:
return False
return all(any(close(n, g) for g in got) for n in nums)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True)
ap.add_argument("--dataset", default="KeremTT/OPUS-5.5-DATABASE")
ap.add_argument("--data-files", default=None)
ap.add_argument("--limit", type=int, default=200)
ap.add_argument("--max-steps", type=int, default=4)
ap.add_argument("--max-new-tokens", type=int, default=256)
ap.add_argument("--out", default=None)
ap.add_argument("--format", choices=["native", "hermes"], default="native",
help="native: the model's chat template with tools=...; hermes: tools in the system prompt "
"(use for models trained with sft_trl.py --with-tools)")
a = ap.parse_args()
import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
ds = (load_dataset("parquet", data_files=a.data_files, split="train") if a.data_files
else load_dataset(a.dataset, "tools", split="test"))
ds = ds.shuffle(seed=0).select(range(min(a.limit, len(ds))))
tok = AutoTokenizer.from_pretrained(a.model)
model = AutoModelForCausalLM.from_pretrained(a.model, dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32)
model.to("cuda" if torch.cuda.is_available() else "cpu").eval()
rows = []
for item in ds:
ref_msgs, tools = to_chat_template(item)
family = item["domain"]
conv = [ref_msgs[0]]
if a.format == "hermes":
conv = [{"role": "system", "content": hermes_system_prompt(tools)}, ref_msgs[0]]
first_tool, final = "NONE", ""
for step in range(a.max_steps):
prompt = (tok.apply_chat_template(conv, tokenize=False, add_generation_prompt=True) if a.format == "hermes"
else tok.apply_chat_template(conv, tools=tools, tokenize=False, add_generation_prompt=True))
enc = tok(prompt, return_tensors="pt", add_special_tokens=False).to(model.device)
with torch.no_grad():
out = model.generate(**enc, max_new_tokens=a.max_new_tokens, do_sample=False)
text = tok.decode(out[0][enc["input_ids"].shape[1]:], skip_special_tokens=True)
calls = [c for c in agent_tools.parse_tool_calls(text) if c["name"] in agent_tools.TOOL_NAMES]
if step == 0:
first_tool = calls[0]["name"] if calls else None
if not calls:
final = text
break
results = [json.dumps(agent_tools.call_tool(c["name"], c["arguments"]), ensure_ascii=False) for c in calls]
if a.format == "hermes":
conv.append({"role": "assistant", "content": text})
conv.append({"role": "user", "content": "\n".join(f"<tool_response>\n{r}\n</tool_response>" for r in results)})
continue
conv.append({"role": "assistant", "content": "", "tool_calls": [
{"type": "function", "function": {"name": c["name"], "arguments": c["arguments"]}} for c in calls]})
for c, r in zip(calls, results):
conv.append({"role": "tool", "name": c["name"], "content": r})
ref_final = ref_msgs[-1]["content"]
ref_answer = " ".join(re.findall(r"\*\*(.*?)\*\*", ref_final)) or ref_final
rows.append({"id": item["id"], "family": family, "language": item["language"],
"call_ok": first_tool == expected_first_tool(ref_msgs),
"answer_ok": answer_ok(family, ref_answer, final), "final": final[-500:]})
n = len(rows)
print(f"{n}/{len(ds)} call={sum(r['call_ok'] for r in rows) / n:.3f} answer={sum(r['answer_ok'] for r in rows) / n:.3f}",
flush=True)
summary = {"model": a.model, "n": len(rows),
"call_accuracy": sum(r["call_ok"] for r in rows) / len(rows),
"answer_accuracy": sum(r["answer_ok"] for r in rows) / len(rows)}
print(json.dumps(summary, indent=2))
if a.out:
json.dump({"summary": summary, "rows": rows}, open(a.out, "w"), indent=2, ensure_ascii=False)
if __name__ == "__main__":
main()