File size: 6,155 Bytes
fb6c876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73f7e6f
fb6c876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73f7e6f
 
 
fb6c876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73f7e6f
 
fb6c876
 
73f7e6f
 
fb6c876
 
 
 
 
 
 
 
 
 
73f7e6f
 
 
 
 
fb6c876
 
73f7e6f
 
fb6c876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()