Aleksander22's picture
Slayer1B 1.10 Instruct 30.11 (SFT)
53d5fc6 verified
Raw History Blame Contribute Delete
28.9 kB
"""Live end-to-end evaluation of a Slayer1B checkpoint against the REAL environment (not synthetic tool results).
The model runs the whole loop itself: it decides whether to call a tool, the call is executed for real (web search, page
reading, NBP exchange rates, Open-Meteo weather, calculator, Python sandbox, CSV analysis — through the Slayer Studio tool
server), it reads the real result and must finish with a correct answer. Gold answers that change over time (exchange
rate, temperature, latest software release) are fetched from the authoritative source at evaluation time, so they cannot
be memorised from training data. Local documents / group chat / structured-output tools are executed here (deterministic).
Categories (0/1 per case):
web_live current facts with a live gold value (NBP rate, weather, GitHub latest release, HF licence)
web_fact stable facts that need a real web search (tool use + gold string in the answer)
web_recover a real tool error first (dead link / no result) -> the model must recover and still answer
decide when NOT to call a tool (chat, translation, writing, general knowledge) and when to ask instead
business scenarios A-E of the product brief + data, code, notes (programmatic checks)
No case text is used for training (written for this eval; build_i1.py drops any training conversation that contains one).
python live_eval.py --ckpt runs/i1/sft_step600.pt --studio http://127.0.0.1:5200 --out results/live/step600.json
python live_eval.py --watch runs/i1 --every 1 ... (evaluate every new checkpoint as training saves it)
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import time
import urllib.request
from datetime import date
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
SYS = {"pl": "Jesteś Slayer — prywatny, dwujęzyczny (PL/EN) asystent działający lokalnie na urządzeniu użytkownika. Odpowiadaj zwięźle, w języku użytkownika. "
"Korzystaj z narzędzi tylko wtedy, gdy są potrzebne, i nigdy nie zmyślaj ich wyników.",
"en": "You are Slayer — a private, bilingual (PL/EN) assistant running locally on the user's device. Answer concisely, in the user's language. "
"Use tools only when necessary and never invent their results."}
def T(name, desc, props, req):
return {"name": name, "description": desc, "parameters": {"type": "object", "properties": props, "required": req}}
S = lambda d: {"type": "string", "description": d} # noqa: E731
TOOLS = {
"web_search": T("web_search", "Search the internet. Requires network access.", {"query": S("Search query"), "max_results": {"type": "integer"}}, ["query"]),
"read_webpage": T("read_webpage", "Fetch a web page and extract its main text.", {"url": S("Absolute URL"), "page": {"type": "integer", "description": "Part of a long page to read, 1-based (default 1)"}}, ["url"]),
"get_exchange_rate": T("get_exchange_rate", "Current or historical average exchange rate of a currency in PLN (National Bank of Poland).",
{"currency": S("ISO 4217 code, e.g. EUR, USD, GBP"), "date": S("Optional YYYY-MM-DD (business day)")}, ["currency"]),
"get_weather": T("get_weather", "Current weather and a short daily forecast for a place.", {"location": S("City or place name"), "days": {"type": "integer", "description": "Forecast days, 1-7 (default 3)"}}, ["location"]),
"calculator": T("calculator", "Evaluate an arithmetic expression exactly.", {"expression": S("Arithmetic expression, e.g. 250 * 0.85")}, ["expression"]),
"convert_units": T("convert_units", "Convert a value between physical units.", {"value": {"type": "number"}, "from_unit": S("Source unit"), "to_unit": S("Target unit")}, ["value", "from_unit", "to_unit"]),
"search_document": T("search_document", "Search the user's local documents (PDF, TXT, MD) and return relevant excerpts with page numbers.",
{"query": S("Search query"), "document": S("Optional file name to restrict the search")}, ["query"]),
"read_document": T("read_document", "Read one page of a local document.", {"document": S("File name"), "page": {"type": "integer", "description": "1-based page number (default 1)"}}, ["document"]),
"search_messages": T("search_messages", "Search messages in the current group space.", {"query": S("What to look for"), "since": S("ISO date, optional")}, ["query"]),
"create_quiz": T("create_quiz", "Create an interactive multiple-choice quiz shown to the user.",
{"title": S("Quiz title"), "questions": {"type": "array", "items": {"type": "object", "properties": {"question": {"type": "string"}, "options": {"type": "array", "items": {"type": "string"}},
"answer_index": {"type": "integer"}, "explanation": {"type": "string"}},
"required": ["question", "options", "answer_index"]}}}, ["title", "questions"]),
"create_table": T("create_table", "Create a table shown to the user (and exportable as CSV).",
{"title": S("Table title"), "columns": {"type": "array", "items": {"type": "string"}}, "rows": {"type": "array", "items": {"type": "array", "items": {"type": "string"}}}}, ["columns", "rows"]),
"analyze_data": T("analyze_data", "Compute statistics over a small CSV table (header row first): count, sum, mean, min, max of numeric columns, optionally grouped by a column.",
{"csv": S("CSV text with a header row"), "columns": {"type": "array", "items": {"type": "string"}, "description": "Numeric columns to analyse (default: all numeric)"}, "group_by": S("Optional column to group by")}, ["csv"]),
"run_python": T("run_python", "Run a short Python 3 script in an isolated sandbox (no network, no files outside the sandbox, 8 s limit) and return stdout, stderr and the exit code.",
{"code": S("Python source code; print() what you need to see")}, ["code"]),
"save_note": T("save_note", "Save a note in the user's notes app on this device.", {"title": S("Note title"), "content": S("Note text (plain text or a checklist with '- [ ] ' items)")}, ["title", "content"]),
}
STUDIO_TOOLS = {"web_search", "read_webpage", "get_exchange_rate", "get_weather", "calculator", "convert_units", "run_python", "analyze_data", "save_note", "create_table", "create_quiz", "search_messages"}
WEB = ["web_search", "read_webpage"]
def http_json(url, data=None, timeout=60, tries=3):
"""Gold values are retried so every checkpoint is scored on the same set of cases."""
for k in range(tries):
try:
return _http_json(url, data, timeout)
except Exception:
if k == tries - 1 or data is not None:
raise
time.sleep(3)
def _http_json(url, data=None, timeout=60):
req = urllib.request.Request(url, data=json.dumps(data).encode() if data is not None else None,
headers={"Content-Type": "application/json", "User-Agent": "slayer-live-eval/0.1 (research evaluation)"})
# classic curve only: some routes drop the large post-quantum ClientHello
import ssl
ctx = ssl.create_default_context()
ctx.set_ecdh_curve("prime256v1")
with urllib.request.urlopen(req, timeout=timeout, **({"context": ctx} if url.startswith("https") else {})) as r:
return json.loads(r.read().decode())
def norm(s):
return re.sub(r"\s+", " ", re.sub(r"[^\w\s.,]", " ", str(s).lower())).strip()
def has_any(text, golds):
t = norm(text)
return any(norm(g) in t for g in golds if norm(g))
def numbers(text):
return [float(x.replace(" ", "").replace(",", ".")) for x in re.findall(r"-?\d[\d ]*(?:[.,]\d+)?", text.replace(" ", " ")) if x.strip(" -")]
# ------------------------------------------------------------------------------------------------ live gold values
def gold_nbp(code):
d = http_json(f"https://api.nbp.pl/api/exchangerates/rates/a/{code}/last/1/?format=json")
return d["rates"][0]["mid"]
def gold_weather(lat, lon):
d = http_json(f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current=temperature_2m")
return d["current"]["temperature_2m"]
def gold_release(repo):
d = http_json(f"https://api.github.com/repos/{repo}/releases/latest")
return d["tag_name"]
def build_cases():
C = []
add = lambda **k: C.append(k) # noqa: E731
# web_live — gold fetched now
for code, pl in [("EUR", "euro"), ("USD", "dolara amerykańskiego"), ("CHF", "franka szwajcarskiego")]:
try:
g = gold_nbp(code)
add(id=f"live_nbp_{code}", cat="web_live", lang="pl", tools=["get_exchange_rate", "web_search", "calculator"], user=f"Ile wynosi dzisiejszy średni kurs {pl} w NBP?",
check={"num": g, "tol": 0.00051, "need_any": ["get_exchange_rate", "web_search"]})
except Exception as e:
print("gold failed", code, e)
try:
g = gold_nbp("EUR")
add(id="live_nbp_calc", cat="web_live", lang="pl", tools=["get_exchange_rate", "calculator", "web_search"], user="Ile złotych to dziś 250 euro po średnim kursie NBP?",
check={"num": round(250 * g, 2), "tol": 0.6, "need_any": ["get_exchange_rate"]})
except Exception as e:
print("gold failed nbp calc", e)
for city, lat, lon, lang in [("Gdańsku", 54.35, 18.65, "pl"), ("Krakowie", 50.06, 19.94, "pl"), ("London", 51.51, -0.13, "en")]:
try:
g = gold_weather(lat, lon)
add(id=f"live_weather_{lat}", cat="web_live", lang=lang, tools=["get_weather", "web_search"],
user=f"Jaka jest teraz temperatura w {city}?" if lang == "pl" else f"What's the temperature in {city} right now?",
check={"num": g, "tol": 2.5, "need_any": ["get_weather"]})
except Exception as e:
print("gold failed", city, e)
for repo, name in [("astral-sh/uv", "uv (menedżer pakietów Pythona od Astral)"), ("vllm-project/vllm", "vLLM"), ("pandas-dev/pandas", "pandas")]:
try:
g = gold_release(repo)
add(id=f"live_release_{name.split()[0]}", cat="web_live", lang="pl", tools=WEB + ["calculator"],
user=f"Jaka jest najnowsza wydana wersja {name}? Sprawdź w sieci.", check={"any": [g, g.lstrip("v")], "need_any": WEB})
except Exception as e:
print("gold failed", repo, e)
add(id="live_hf_license", cat="web_live", lang="en", tools=WEB, user="What licence does the Hugging Face model SlayerLab/Slayer1B-1.10 use?",
check={"any": ["apache-2.0", "apache 2.0", "apache license 2.0", "apache"], "need_any": WEB})
# web_fact — stable facts, real search required (answer must come with a tool call)
for i, (lang, q, g) in enumerate([
("pl", "Kto zaprojektował katowicki Spodek? Sprawdź w internecie.", ["Gintowt", "Krasiński"]),
("pl", "W którym roku otwarto pierwszą linię warszawskiego metra? Poszukaj w sieci.", ["1995"]),
("pl", "Ile metrów wysokości ma Pałac Kultury i Nauki w Warszawie? Sprawdź.", ["237"]),
("pl", "Kto jest autorem powieści „Lalka”? Sprawdź w internecie i podaj źródło.", ["Prus"]),
("en", "Look up who founded the Hugging Face company and tell me their names.", ["Delangue", "Chaumond", "Wolf"]),
("en", "Search the web: in which year was the Python programming language first released?", ["1991"]),
("pl", "Znajdź w sieci, w jakim mieście znajduje się siedziba firmy CD Projekt.", ["Warszaw"]),
("en", "Which river flows through Wrocław? Please check online.", ["Oder", "Odra"])]):
add(id=f"fact{i}", cat="web_fact", lang=lang, tools=WEB + ["calculator", "get_weather"], user=q, check={"any": g, "need_any": WEB})
# web_recover — real errors first
add(id="recover_deadlink", cat="web_recover", lang="pl", tools=WEB,
user="Przeczytaj https://pl.wikipedia.org/wiki/Spodek_(hala_widowiskowo-sportowa_w_Katowicach)_xyz i powiedz, w którym roku otwarto Spodek.",
check={"any": ["1971"], "need_any": WEB, "min_calls": 2})
add(id="recover_deadlink_en", cat="web_recover", lang="en", tools=WEB,
user="Read https://en.wikipedia.org/wiki/Wawel_Castle_zz_missing and tell me in which city the castle is.", check={"any": ["Kraków", "Krakow", "Cracow"], "need_any": WEB, "min_calls": 2})
add(id="recover_currency", cat="web_recover", lang="pl", tools=["get_exchange_rate", "web_search"],
user="Jaki jest kurs korony czeskiej w NBP? (kod waluty chyba CZKK)", check={"num_fn": ("CZK",), "tol": 0.00051, "need_any": ["get_exchange_rate"]})
# decide — no tool / clarify
for i, (lang, q) in enumerate([("pl", "Cześć! Jak się dziś masz?"), ("pl", "Przetłumacz na angielski: „Dziękuję za szybką odpowiedź, prześlę umowę jutro.”"),
("en", "Write a two-sentence thank-you note to my colleague Ola for helping with the report."),
("pl", "Wyjaśnij w dwóch zdaniach, czym jest fotosynteza."), ("en", "Translate to Polish: 'The meeting is moved to Friday at 10.'"),
("pl", "Podaj trzy pomysły na prezent dla taty, który lubi wędkowanie.")]):
add(id=f"notool{i}", cat="decide", lang=lang, tools=WEB + ["calculator", "get_weather"], user=q, check={"no_tool": True})
for i, (lang, q) in enumerate([("pl", "Policz mi ratę kredytu."), ("en", "Convert it to kilograms please."), ("pl", "Wyślij to szefowi.")]):
add(id=f"clarify{i}", cat="decide", lang=lang, tools=["calculator", "convert_units", "web_search"], user=q, check={"no_tool": True, "ask": True})
add(id="calc_tool", cat="decide", lang="pl", tools=["calculator", "web_search"], user="Ile to 4873 * 219?", check={"num": 4873 * 219, "tol": 0.5, "need_any": ["calculator"]})
# identity: the model must say who it is (never an evasive "how can I help?" or another model's name), without tools
# phrasings that are NOT in identity_pairs.py (the first version reused its training prompts)
for i, (lang, q, prev) in enumerate([("pl", "Pod jakim imieniem działasz?", None), ("pl", "jak cie zwa kolego", None),
("en", "Is this Gemini I'm chatting with?", None),
("pl", "No ale jak ci na imię, bo nie powiedziałeś.", ("Możesz podać swoje imię?", "Chętnie pomogę! Opisz, czego potrzebujesz."))]):
add(id=f"identity{i}", cat="identity", lang=lang, tools=WEB + ["calculator"], user=q, prev=prev, check={"no_tool": True, "any": ["Slayer"]})
# business scenarios A-E (+ data, code, notes)
offer = {"Oferta_handlowa.pdf": ["OFERTA HANDLOWA nr 14/2026\nDostawca: Optima-Druk Sp. z o.o., ul. Kwiatowa 7, Poznań.\nPrzedmiot: 500 sztuk ulotek A5 i 200 plakatów B2.",
"Warunki handlowe\n1. Termin płatności: 30 dni od daty wystawienia faktury.\n2. Termin dostawy: 14 dni roboczych od akceptacji projektu.",
"3. Gwarancja: 24 miesiące na trwałość wydruku.\n4. Oferta ważna do 31 grudnia 2026 r."]}
add(id="biz_B_offer", cat="business", lang="pl", tools=["search_document", "read_document", "web_search"], docs=offer,
user="Sprawdź w Oferta_handlowa.pdf warunki płatności, termin dostawy i okres gwarancji.", check={"all": ["30 dni", "14 dni", "24 miesi"], "need_any": ["search_document", "read_document"]})
add(id="biz_C_suppliers", cat="business", lang="pl", tools=["calculator", "web_search"],
user="Dostawca A oferuje 200 produktów po 45 zł, dostawca B po 48 zł z rabatem 10%. Która oferta jest korzystniejsza cenowo?",
check={"nums": [9000, 8640, 360], "any": ["B"], "need_any": ["calculator"]})
group = [{"author": "Anna", "timestamp": "2026-11-24T09:10:00", "text": "Raport przygotuję do piątku."},
{"author": "Piotr", "timestamp": "2026-11-24T09:12:00", "text": "Ja zrobię analizę danych do środy."},
{"author": "Michał", "timestamp": "2026-11-24T09:20:00", "text": "Spotkajmy się w czwartek o 14."},
{"author": "Anna", "timestamp": "2026-11-24T09:21:00", "text": "Pasuje, ktoś zarezerwuje salę?"}]
add(id="biz_D_group", cat="business", lang="pl", tools=["search_messages", "create_table"], group=group, name="Michał",
user="@Slayer zbierz wszystkie ustalenia i terminy.", check={"all": ["Anna", "Piotr", "piąt", "środ", "czwart", "14"], "need_any": ["search_messages"]})
lecture = {"wyklad_algorytmy.md": ["# Wykład 5: Przeszukiwanie grafów\nBFS (przeszukiwanie wszerz) odwiedza wierzchołki warstwami, używa kolejki FIFO i w grafie bez wag znajduje najkrótszą ścieżkę.",
"DFS (przeszukiwanie w głąb) idzie jak najdalej jedną ścieżką, używa stosu lub rekurencji; przydaje się do wykrywania cykli i sortowania topologicznego. Obie metody mają złożoność O(V+E)."]}
add(id="biz_E_quiz", cat="business", lang="pl", tools=["search_document", "read_document", "create_quiz", "web_search"], docs=lecture,
user="Przeszukaj mój wykład, wyjaśnij różnicę między BFS a DFS i przygotuj pytania do nauki.", check={"need_all": ["create_quiz"], "need_any": ["search_document", "read_document"], "any": ["kolejk", "stos"]})
add(id="biz_A_brief", cat="business", lang="pl", tools=WEB + ["calculator"],
user="Jutro mamy spotkanie z firmą Asseco Poland. Znajdź o niej informacje i przygotuj krótkie podsumowanie.", check={"any": ["Rzesz", "oprogramow", "informaty"], "need_any": WEB})
csv = "miesiac,sprzedaz\nstyczen,120\nluty,95\nmarzec,140\nkwiecien,160\nmaj,130\nczerwiec,175"
add(id="biz_data_sum", cat="business", lang="pl", tools=["analyze_data", "calculator", "create_table"],
user=f"Ile wyniosła łączna sprzedaż w pierwszym półroczu i który miesiąc był najlepszy?\n{csv}", check={"nums": [820], "any": ["czerw"], "need_any": ["analyze_data", "calculator"]})
code = "def srednia(xs):\n return sum(xs) / len(xs)\n\nprint(srednia([]))"
add(id="biz_code_fix", cat="business", lang="pl", tools=["run_python", "web_search"],
user=f"Dlaczego ten kod się wywala i jak to poprawić?\n{code}", check={"any": ["ZeroDivision", "dzielenie przez zero", "pust"], "need_any": ["run_python"]})
add(id="biz_note", cat="business", lang="pl", tools=["save_note", "create_table", "web_search"],
user="Zapisz mi notatkę z zakupami: mleko, chleb, 6 jajek i kawa ziarnista.", check={"need_all": ["save_note"], "arg_has": {"save_note": ["mleko", "chleb", "jaj", "kaw"]}})
add(id="biz_email_en", cat="business", lang="pl", tools=WEB + ["calculator"],
user="Klient napisał: 'Hi, could you confirm the delivery date for order 552 and send the invoice?' Napisz krótką odpowiedź po angielsku, że dostawa będzie 12 grudnia, a fakturę wyślemy dziś.",
check={"no_tool": True, "any": ["12", "December"]})
return C
# ------------------------------------------------------------------------------------------------ local tools
def doc_tool(name, args, docs):
if name == "search_document":
q = set(norm(args.get("query", "")).split())
hits = []
for dn, pages in docs.items():
if args.get("document") and args["document"].lower() != dn.lower():
continue
for i, p in enumerate(pages):
s = len(q & set(norm(p).split()))
if s:
hits.append((s, dn, i + 1, p[:400]))
hits.sort(reverse=True)
return {"results": [{"document": d, "page": pg, "excerpt": ex} for _, d, pg, ex in hits[:3]]} if hits else {"results": [], "message": "No matches."}
dn = next((d for d in docs if d.lower() == str(args.get("document", "")).lower()), None)
if not dn:
return {"error": "document_not_found", "message": f"No document named {args.get('document')} in the local library.", "available": list(docs)}
pg = int(args.get("page") or 1)
if not 1 <= pg <= len(docs[dn]):
return {"error": "page_out_of_range", "message": f"{dn} has {len(docs[dn])} pages."}
return {"document": dn, "page": pg, "pages": len(docs[dn]), "text": docs[dn][pg - 1]}
def system_for(case, today):
lang = case["lang"]
files = list((case.get("docs") or {}).keys())
if lang == "pl":
note = f"Data: {today}. Sieć: online." + (f" Pliki: {', '.join(files)}." if files else "")
if case.get("group"):
note += " Przestrzeń grupowa „Projekt zespołowy” (Anna, Piotr, Michał). Odpowiadasz po wzmiance @Slayer; Twoją odpowiedź widzą wszyscy."
else:
note = f"Date: {today}. Network: online." + (f" Files: {', '.join(files)}." if files else "")
return SYS[lang] + "\n\n" + note
def run_case(model, fmt, case, studio, today, max_calls=6, gen=None, device="cuda"):
from chatfmt import parse_calls
from model_io import generate
tools = [TOOLS[n] for n in case["tools"]]
user = (case["name"] + ": " + case["user"]) if case.get("name") else case["user"]
msgs = [{"role": "system", "content": system_for(case, today)}]
if case.get("prev"):
msgs += [{"role": "user", "content": case["prev"][0]}, {"role": "assistant", "content": case["prev"][1]}]
msgs.append({"role": "user", "content": user})
calls, trace, final, errors = [], [], "", []
for _ in range(max_calls + 1):
out, stop = generate(model, fmt.prompt_ids(msgs, tools), stop_ids={fmt.ime, fmt.bos}, max_new_tokens=450, device=device, **(gen or {}))
text = fmt.tok.decode(out, skip_special_tokens=False).strip()
cs, errs = parse_calls(text)
errors += errs
if not cs:
final = text
break
msgs.append({"role": "assistant", "content": text.split("<tool_call>")[0].strip(), "tool_calls": [{"name": c["name"], "arguments": c["arguments"]} for c in cs]})
for c in cs:
calls.append(c)
if c["name"] not in case["tools"]:
res = {"error": "unknown_tool", "message": f"Tool \"{c['name']}\" does not exist."}
elif c["name"] in ("search_document", "read_document"):
res = doc_tool(c["name"], c["arguments"], case.get("docs") or {})
else:
try:
r = http_json(studio.rstrip("/") + "/api/gen/tool", {"name": c["name"], "args": c["arguments"], "language": case["lang"], "group": case.get("group")}, timeout=90)
res = json.loads(r["content"])
except Exception as e:
res = {"error": "tool_error", "message": str(e)[:200]}
trace.append({"call": c, "result": json.dumps(res, ensure_ascii=False)[:600]})
msgs.append({"role": "tool", "content": json.dumps(res, ensure_ascii=False)[:3000]})
if len(calls) >= max_calls:
break
return {"calls": calls, "trace": trace, "final": final, "parse_errors": errors}
def judge(case, r):
ch, names, fin = case["check"], [c["name"] for c in r["calls"]], r["final"]
why = []
if ch.get("no_tool") and names:
why.append("needless_tool")
if ch.get("ask") and "?" not in fin:
why.append("did_not_ask")
if ch.get("need_any") and not any(n in names for n in ch["need_any"]):
why.append("missing_tool")
for n in ch.get("need_all", []):
if n not in names:
why.append(f"missing_{n}")
if ch.get("min_calls") and len(names) < ch["min_calls"]:
why.append("no_recovery")
if any(n not in case["tools"] for n in names):
why.append("unknown_tool")
keys = [json.dumps(c, sort_keys=True, ensure_ascii=False) for c in r["calls"]]
if len(keys) != len(set(keys)):
why.append("repeat_call")
if not fin.strip():
why.append("no_final_answer")
if "num" in ch and not any(abs(x - ch["num"]) <= ch["tol"] for x in numbers(fin)):
why.append("wrong_number")
if "num_fn" in ch:
try:
g = gold_nbp(ch["num_fn"][0])
if not any(abs(x - g) <= ch["tol"] for x in numbers(fin)):
why.append("wrong_number")
except Exception:
pass
if ch.get("nums") and not all(any(abs(x - n) <= 0.5 for x in numbers(fin)) for n in ch["nums"]):
why.append("wrong_number")
if ch.get("any") and not has_any(fin, ch["any"]):
why.append("answer")
if ch.get("all") and not all(norm(g) in norm(fin) for g in ch["all"]):
why.append("answer")
for tn, words in (ch.get("arg_has") or {}).items():
args = json.dumps([c["arguments"] for c in r["calls"] if c["name"] == tn], ensure_ascii=False).lower()
if not all(w in args for w in words):
why.append(f"bad_args_{tn}")
return why
def evaluate(ckpt, studio, out, limit=0, cats=None, device="cuda", cases_fn=None):
import torch
from tokenizers import Tokenizer
from chatfmt import Fmt
from model_io import load
import os
fmt = Fmt(Tokenizer.from_file(os.environ.get("SLAYER_TOKENIZER", str(HERE / "ckpt/tokenizer.json"))))
if device == "cpu":
torch.set_num_threads(int(os.environ.get("EVAL_THREADS", "48")))
model, cfg, step = load(ckpt, device=device, dtype=torch.bfloat16 if device == "cuda" else torch.float32)
model.eval()
today = date.today().isoformat()
cases = [c for c in (cases_fn or build_cases)() if not cats or c["cat"] in cats][: limit or None]
res, t0 = [], time.time()
for c in cases:
try:
r = run_case(model, fmt, c, studio, today, device=device)
why = judge(c, r)
except Exception as e:
r, why = {"calls": [], "trace": [], "final": "", "error": repr(e)[:300]}, ["harness_error"]
res.append({"id": c["id"], "cat": c["cat"], "lang": c["lang"], "pass": not why, "why": why, "user": c["user"], **r})
by = {}
for x in res:
by.setdefault(x["cat"], []).append(x["pass"])
summary = {k: f"{sum(v)}/{len(v)}" for k, v in sorted(by.items())}
summary["total"] = f"{sum(x['pass'] for x in res)}/{len(res)}"
rep = {"ckpt": str(ckpt), "date": today, "seconds": round(time.time() - t0), "summary": summary, "cases": res}
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
print(json.dumps({"ckpt": str(ckpt), **summary}, ensure_ascii=False), flush=True)
del model
if device == "cuda":
torch.cuda.empty_cache()
return rep
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt")
ap.add_argument("--watch", help="run dir: evaluate every new sft_step*.pt that appears (until a DONE file shows up)")
ap.add_argument("--studio", default="http://127.0.0.1:5200")
ap.add_argument("--out", default="results/live/live.json")
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--cats", nargs="*")
ap.add_argument("--list", action="store_true")
ap.add_argument("--device", default="cuda")
ap.add_argument("--fresh", action="store_true", help="fresh_cases.py (card test set)")
a = ap.parse_args()
if a.list:
for c in build_cases():
print(c["cat"], c["id"], c["user"][:90])
return
if a.ckpt:
fn = None
if a.fresh:
from fresh_cases import cases as fn
evaluate(a.ckpt, a.studio, a.out, a.limit, a.cats, a.device, fn)
return
done = {p.name for p in Path(a.watch).glob("sft_step*.pt") if (Path(a.out).parent / f"{p.stem}.json").exists()} # already evaluated (resume)
run = Path(a.watch)
while True:
new = sorted((p for p in run.glob("sft_step*.pt") if p.name not in done), key=lambda p: int(re.findall(r"\d+", p.stem)[-1]))
for p in new:
time.sleep(20) # let the writer finish (save() writes .tmp then renames)
evaluate(p, a.studio, str(Path(a.out).parent / f"{p.stem}.json"), a.limit, a.cats, a.device)
done.add(p.name)
with open(Path(a.out).parent / "curve.jsonl", "a", encoding="utf-8") as f:
rep = json.loads((Path(a.out).parent / f"{p.stem}.json").read_text(encoding="utf-8"))
f.write(json.dumps({"ckpt": p.name, **rep["summary"]}, ensure_ascii=False) + "\n")
if (run / "DONE").exists() and not new:
break
time.sleep(60)
if __name__ == "__main__":
main()