File size: 10,427 Bytes
6071ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
"""0/1 evaluations for Slayer1B chat + tool calling.

  python evals.py --ckpt wagi.pt --data data/s1_toolcall [--limit N] [--rank R --world W] --out results.json

A. chat_format   held-out general-talk prompts (test split): the reply must be non-empty, end with <|im_end|> (no
                 runaway), contain no role/control tokens, not loop, and be in the language of the prompt.
B1. tool_replay  held-out tool-use records (test split) whose upstream first answer is a tool call: the model must emit
                 a parseable <tool_call> naming a declared tool with all required arguments (exact tool = secondary).
B2. tool_loop    executable local tools (tools_suite.py), PL + EN: the model must call the expected tool with valid
                 arguments, receive the real result, and give a final answer containing values from that result
                 (end-to-end 0/1). Run twice: natural, and forced (assistant turn pre-filled with "<tool_call>\\n").
                 No-tool cases count an unnecessary call as failure.
Every score is a plain mean of 0/1 outcomes; per-case outputs are saved for inspection.
"""
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path

import torch
from tokenizers import Tokenizer

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from chatfmt import Fmt, parse_calls  # noqa: E402
from model_io import generate, load  # noqa: E402
import tools_suite  # noqa: E402

PL_CHARS = re.compile(r"[ąćęłńśźżĄĆĘŁŃŚŹŻ]")
PL_WORDS = set("się nie że jest są jak czy ale przez dla też ten oraz już tylko może można który która które gdzie kiedy bardzo jeśli".split())
EN_WORDS = set("the and of with is are was were this that you they not does will would should have has what how why which there".split())


def lang_of(t: str) -> str:
    w = re.findall(r"[^\W\d_]+", t.lower())
    if len(w) < 4:
        return "short"
    pl = sum(x in PL_WORDS for x in w) / len(w) + (0.05 if PL_CHARS.search(t) else 0)
    en = sum(x in EN_WORDS for x in w) / len(w)
    return "pl" if pl > en else "en"


def looping(t: str) -> bool:
    w = t.split()
    if len(w) < 40:
        return False
    grams = [" ".join(w[i:i + 6]) for i in range(len(w) - 5)]
    return max(grams.count(g) for g in set(grams)) >= 4


class Runner:
    def __init__(self, model, fmt, max_new=256, device="cuda"):
        self.m, self.f, self.max_new, self.dev = model, fmt, max_new, device
        self.stop = {fmt.ime, fmt.bos, fmt.ims}

    def reply(self, messages, tools=None, prefill: str = "", max_new: int | None = None):
        ids = self.f.prompt_ids(messages, tools) + self.f.enc(prefill)
        out, why = generate(self.m, ids, stop_ids=self.stop, max_new_tokens=max_new or self.max_new, device=self.dev)
        return prefill + self.f.tok.decode(out, skip_special_tokens=False), why


def eval_chat(r: Runner, items, max_new=1024):
    res = []
    for it in items:
        text, why = r.reply(it["messages"], max_new=max_new)
        user_lang = it.get("language") if it.get("language") in ("pl", "en") else lang_of(it["messages"][-1]["content"] or "")
        checks = {"stopped": why == "stop", "non_empty": bool(text.strip()),
                  "no_control_text": not any(s in text for s in ("<|im_start|>", "<|endoftext|>", "<tool_call>")),
                  "no_loop": not looping(text),
                  "language_match": lang_of(text) in (user_lang, "short")}
        res.append({"id": it["id"], "ok": all(checks.values()), **checks, "output": text[:2000]})
    return res


def eval_replay(r: Runner, items):
    res = []
    for it in items:
        if not it.get("expected_call"):
            continue
        text, why = r.reply(it["messages"], it["tools"])
        calls, errs = parse_calls(text)
        declared = {t["name"]: t for t in it["tools"]}
        ok_call = bool(calls) and all(c["name"] in declared for c in calls)
        req_ok = True
        for c in calls:
            sch = declared.get(c["name"], {}).get("parameters")
            sch = json.loads(sch) if isinstance(sch, str) else (sch or {})
            if any(k not in c["arguments"] for k in (sch.get("required") or [])):
                req_ok = False
        exact = bool(calls) and calls[0]["name"] == it["expected_call"][0]["name"]
        res.append({"id": it["id"], "ok": ok_call and req_ok and not errs, "valid_call": ok_call and not errs,
                    "required_args": req_ok, "same_tool_as_reference": exact, "errors": errs, "output": text[:600]})
    return res


def run_loop(r: Runner, case, forced: bool, max_rounds=3):
    msgs = [{"role": "user", "content": case["prompt"]}]
    trace, called, valid_args, seen_calls = [], [], True, set()
    for rnd in range(max_rounds + 1):
        text, why = r.reply(msgs, case["tools"], prefill="<tool_call>\n" if (forced and rnd == 0 and case["expect_tool"]) else "")
        calls, errs = parse_calls(text)
        trace.append({"assistant": text[:800], "stop": why, "errors": errs})
        if errs:
            valid_args = False
        if not calls:
            final = re.sub(r"<tool_call>.*", "", text, flags=re.S).strip()
            return {"final": final, "called": called, "valid_args": valid_args, "trace": trace}
        sig = json.dumps([(c["name"], c["arguments"]) for c in calls], sort_keys=True, ensure_ascii=False)
        if sig in seen_calls:            # the same call again: the model is looping; stop and count it as a failure
            return {"final": "", "called": called + [c["name"] for c in calls], "valid_args": valid_args, "trace": trace, "note": "repeated_call"}
        seen_calls.add(sig)
        tc = []
        for c in calls:
            called.append(c["name"])
            req = next((t["parameters"].get("required", []) for t in case["tools"] if t["name"] == c["name"]), None)
            if req is None or any(k not in c["arguments"] for k in req):
                valid_args = False
            result = tools_suite.execute(c["name"], c["arguments"])
            tc.append((c, result))
            trace[-1].setdefault("results", []).append(result)
        msgs.append({"role": "assistant", "content": "", "tool_calls": [{"name": c["name"], "arguments": json.dumps(c["arguments"], ensure_ascii=False)} for c, _ in tc]})
        for _, res_ in tc:
            msgs.append({"role": "tool", "content": json.dumps(res_, ensure_ascii=False)})
    return {"final": "", "called": called, "valid_args": valid_args, "trace": trace, "note": "max_rounds"}


def eval_loop(r: Runner, cases, forced: bool):
    res = []
    for c in cases:
        o = run_loop(r, c, forced)
        if c["expect_tool"] is None:
            ok = not o["called"] and bool(o["final"])
            res.append({"id": c["id"], "lang": c["lang"], "kind": "no_tool", "ok": ok, **{k: o[k] for k in ("called", "final")}})
            continue
        used = c["expect_tool"] in o["called"]
        uses_result = all(s in o["final"].replace(" ", "").replace(",", ".") or s in o["final"] for s in c["must_contain"])
        res.append({"id": c["id"], "lang": c["lang"], "kind": c["expect_tool"], "note": o.get("note"), "ok": used and o["valid_args"] and uses_result and bool(o["final"]),
                    "called_expected_tool": used, "valid_args": o["valid_args"], "answer_uses_result": uses_result,
                    "called": o["called"], "final": o["final"][:400], "trace": o["trace"]})
    return res


def summary(rows, keys=("ok",)):
    if not rows:
        return {}
    s = {"n": len(rows)}
    for k in keys:
        s[k] = round(sum(bool(x.get(k)) for x in rows) / len(rows), 4)
    return s


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ckpt", required=True)
    ap.add_argument("--data", required=True)
    ap.add_argument("--tokenizer", default=str(HERE.parents[1] / "slayer-general-talk-pl-en/_research/slayer1b/tutorials/runtime/tokenizer.json"))
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--rank", type=int, default=0)
    ap.add_argument("--world", type=int, default=1)
    ap.add_argument("--max-new", type=int, default=256)
    ap.add_argument("--chat-max-new", type=int, default=1024)
    ap.add_argument("--out", required=True)
    ap.add_argument("--only", default="chat,replay,loop,loop_forced")
    a = ap.parse_args()
    dev = "cuda" if torch.cuda.is_available() else "cpu"
    model, cfg, step = load(a.ckpt, device=dev, dtype=torch.bfloat16 if dev == "cuda" else torch.float32)
    model.eval()
    fmt = Fmt(Tokenizer.from_file(a.tokenizer))
    r = Runner(model, fmt, a.max_new, dev)
    d = Path(a.data) / "eval"
    pick = lambda xs: [x for i, x in enumerate(xs[: a.limit or None]) if i % a.world == a.rank]
    only = set(a.only.split(","))
    rd = lambda fn: pick([json.loads(l) for l in open(d / fn, encoding="utf-8")]) if (d / fn).exists() else []
    chat = rd("chat_prompts.jsonl") if "chat" in only else []
    replay = rd("tool_replay.jsonl") if "replay" in only else []
    loop_cases = pick(tools_suite.cases())
    out = {"ckpt": a.ckpt, "step": step, "results": {}, "summary": {}}
    if "chat" in only:
        rows = eval_chat(r, chat, a.chat_max_new)
        out["results"]["chat_format"], out["summary"]["chat_format"] = rows, summary(rows, ("ok", "stopped", "language_match", "no_loop"))
    if "replay" in only:
        rows = eval_replay(r, replay)
        out["results"]["tool_replay"], out["summary"]["tool_replay"] = rows, summary(rows, ("ok", "valid_call", "required_args", "same_tool_as_reference"))
    for mode in ("loop", "loop_forced"):
        if mode in only:
            rows = eval_loop(r, loop_cases, forced=(mode == "loop_forced"))
            tool_rows = [x for x in rows if x["kind"] != "no_tool"]
            out["results"][mode] = rows
            out["summary"][mode] = {"end_to_end": summary(tool_rows, ("ok", "called_expected_tool", "valid_args", "answer_uses_result")),
                                    "no_tool_correct": summary([x for x in rows if x["kind"] == "no_tool"]),
                                    "pl": summary([x for x in tool_rows if x["lang"] == "pl"]), "en": summary([x for x in tool_rows if x["lang"] == "en"])}
    Path(a.out).write_text(json.dumps(out, indent=1, ensure_ascii=False), encoding="utf-8")
    print(json.dumps(out["summary"], indent=1))


if __name__ == "__main__":
    main()