File size: 9,274 Bytes
647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 647451b c2e8d04 | 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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | """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
|