Microck's picture
Vendor the GSM8K control items, save per-item control predictions, format the evaluator
c2e8d04 verified
Raw History Blame Contribute Delete
9.27 kB
"""General-capability controls for the CSV-repair fine-tune: a GSM8K slice and a single-turn tool-calling set.
They check that training on repair episodes did not cost ordinary skills (a drop of more than 3 points is flagged).
Both score a model on the same OpenAI-compatible server as ``evaluate.py``:
- ``gsm8k``: the first ``--gsm8k`` (at most 250) problems of ``openai/gsm8k`` (main, test), answered in one turn;
correct when the last number of the reply equals the reference answer. The 250 problems are vendored next to this
file (``GSM8K_FILE``: dataset revision ``GSM8K_REVISION``, MIT license) so the control needs neither ``datasets``
nor network access.
- ``tool_use``: 120 seeded requests over four unrelated tools (weather, currency, calendar, stock quote); correct
when the reply is exactly one call to the right tool with the right arguments.
Both return a summary of numbers and the per-item records, which ``run_eval.py`` saves next to the repair episodes.
"""
from __future__ import annotations
import asyncio
import json
import random
import re
from pathlib import Path
from typing import Any
# The first 250 rows of openai/gsm8k, config main, split test, in file order, as {"index", "question", "answer"}.
GSM8K_FILE = Path(__file__).with_name("gsm8k_main_test_first250.jsonl")
GSM8K_REVISION = "740312add88f781978c0658806c59bc2815b9866"
_NUMBER = re.compile(r"-?\d[\d,]*(?:\.\d+)?")
CONTROL_TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city", "unit"],
},
},
},
{
"type": "function",
"function": {
"name": "convert_currency",
"description": "Convert an amount between currencies.",
"parameters": {
"type": "object",
"properties": {
"amount": {"type": "number"},
"from_currency": {"type": "string"},
"to_currency": {"type": "string"},
},
"required": ["amount", "from_currency", "to_currency"],
},
},
},
{
"type": "function",
"function": {
"name": "create_event",
"description": "Add an event to the user's calendar.",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string"},
"date": {"type": "string", "description": "YYYY-MM-DD"},
"duration_minutes": {"type": "integer"},
},
"required": ["title", "date", "duration_minutes"],
},
},
},
{
"type": "function",
"function": {
"name": "get_stock_quote",
"description": "Latest price for a ticker symbol.",
"parameters": {"type": "object", "properties": {"ticker": {"type": "string"}}, "required": ["ticker"]},
},
},
]
_CITIES = ["Nairobi", "Montreal", "Hanoi", "Bergen", "Cordoba", "Adelaide", "Krakow", "Osaka"]
_CCY = ["USD", "EUR", "JPY", "GBP", "CHF", "INR"]
_TICKERS = ["AAPL", "MSFT", "NVDA", "TSLA", "SAP", "TM"]
_MONTHS = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
def tool_use_items(count: int = 120, seed: int = 7) -> list[dict[str, Any]]:
rng = random.Random(seed)
items = []
for i in range(count):
kind = i % 4
if kind == 0:
city, unit = rng.choice(_CITIES), rng.choice(["celsius", "fahrenheit"])
text = rng.choice(
[
f"What's the weather in {city} right now? Give it in {unit}.",
f"Check the current weather for {city}, in {unit} please.",
]
)
want = ("get_weather", {"city": city, "unit": unit})
elif kind == 1:
amount = rng.choice([25, 100, 250, 1200, 75.5])
a, b = rng.sample(_CCY, 2)
text = rng.choice([f"How much is {amount} {a} in {b}?", f"Convert {amount} {a} to {b}."])
want = ("convert_currency", {"amount": amount, "from_currency": a, "to_currency": b})
elif kind == 2:
month, day = rng.randint(1, 12), rng.randint(1, 28)
minutes = rng.choice([30, 45, 60, 90])
title = rng.choice(["Dentist", "Team sync", "Call with Priya", "Gym", "Budget review"])
text = f"Put '{title}' on my calendar for {_MONTHS[month - 1]} {day}, 2027, {minutes} minutes."
want = (
"create_event",
{"title": title, "date": f"2027-{month:02d}-{day:02d}", "duration_minutes": minutes},
)
else:
ticker = rng.choice(_TICKERS)
text = rng.choice([f"What's {ticker} trading at?", f"Get me the latest quote for {ticker}."])
want = ("get_stock_quote", {"ticker": ticker})
items.append({"prompt": text, "tool": want[0], "arguments": want[1]})
return items
def _same(a: Any, b: Any) -> bool:
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return abs(float(a) - float(b)) < 1e-9
if isinstance(a, str) and isinstance(b, str):
return a.strip().lower() == b.strip().lower()
return a == b
async def run_tool_use(
client: Any, model: str, seed: int, gate: asyncio.Semaphore
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
items = tool_use_items()
def correct(item: dict[str, Any], calls: list[Any]) -> bool:
if len(calls) != 1 or calls[0].function.name != item["tool"]:
return False
try:
args = json.loads(calls[0].function.arguments)
except json.JSONDecodeError:
return False
return set(args) == set(item["arguments"]) and all(_same(args[k], v) for k, v in item["arguments"].items())
async def one(i: int, item: dict[str, Any]) -> dict[str, Any]:
async with gate:
r = await client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": item["prompt"]}],
tools=CONTROL_TOOLS,
tool_choice="auto",
temperature=0.7,
top_p=0.8,
max_tokens=512,
seed=seed * 100_003 + i,
)
calls = r.choices[0].message.tool_calls or []
return {
"index": i,
"tool": item["tool"],
"arguments": item["arguments"],
"calls": [{"name": c.function.name, "arguments": c.function.arguments} for c in calls],
"content": r.choices[0].message.content or "",
"correct": correct(item, calls),
}
records = await asyncio.gather(*(one(i, item) for i, item in enumerate(items)))
hits = sum(rec["correct"] for rec in records)
return {"tool_use_accuracy": round(100.0 * hits / len(records), 2), "tool_use_n": len(records)}, records
def _last_number(text: str) -> float | None:
found = _NUMBER.findall(text or "")
if not found:
return None
try:
return float(found[-1].replace(",", ""))
except ValueError:
return None
async def run_gsm8k(
client: Any, model: str, seed: int, count: int, gate: asyncio.Semaphore
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
rows = [json.loads(line) for line in GSM8K_FILE.read_text().splitlines() if line.strip()]
if not 0 < count <= len(rows):
raise ValueError(f"--gsm8k must be between 1 and {len(rows)}, the problems vendored in {GSM8K_FILE.name}")
rows = rows[:count]
async def one(i: int, row: dict[str, Any]) -> dict[str, Any]:
async with gate:
r = await client.chat.completions.create(
model=model,
temperature=0.7,
top_p=0.8,
max_tokens=1024,
seed=seed * 100_003 + i,
messages=[
{
"role": "user",
"content": row["question"] + "\nSolve it step by step and end with the "
"final answer as a number on its own line.",
}
],
)
want = float(row["answer"].split("####")[-1].strip().replace(",", ""))
content = r.choices[0].message.content or ""
got = _last_number(content)
return {
"index": row["index"],
"reference": want,
"parsed": got,
"content": content,
"correct": got is not None and abs(got - want) < 1e-6,
}
records = await asyncio.gather(*(one(i, row) for i, row in enumerate(rows)))
hits = sum(rec["correct"] for rec in records)
return {"gsm8k_accuracy": round(100.0 * hits / len(records), 2), "gsm8k_n": len(records)}, records