File size: 13,612 Bytes
2b42456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a587ba9
2b42456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a587ba9
2b42456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a587ba9
2b42456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
"""Harness: dataset loading, evaluation loop, CLI."""

from __future__ import annotations

import argparse
import json
import sys
import traceback
from pathlib import Path
from typing import Any, Callable, Iterable, Sequence

from .cases_build import build, manifest, write_jsonl
from .grade import grade_case
from .prompts import render_case
from .report import build_report, render_markdown, write_report
from .runners import Prompt, Runner, build_runner, run_batch
from .schema import PROTOCOLS, Case, CaseResult, Protocol
from .tools import tools_for

ROOT = Path(__file__).resolve().parent.parent
DATASET_PATH = ROOT / "data" / "tooluse1.jsonl"
RESULTS_DIR = ROOT / "results"


def load_cases(
    path: Path = DATASET_PATH,
    langs: Sequence[str] | None = None,
    categories: Sequence[str] | None = None,
    limit: int | None = None,
) -> list[Case]:
    if not path.exists():
        raise FileNotFoundError(f"dataset not found at {path}; run `python -m tooluse1.harness build`")
    cases: list[Case] = []
    with path.open(encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if line:
                cases.append(Case.from_dict(json.loads(line)))
    if langs:
        wanted = {lang.lower() for lang in langs}
        cases = [case for case in cases if case.lang in wanted]
    if categories:
        wanted_categories = {category.lower() for category in categories}
        cases = [case for case in cases if case.category in wanted_categories]
    if limit is not None:
        cases = cases[:limit]
    return cases


def _failed_result(case: Case, protocol: Protocol, error: str) -> CaseResult:
    return CaseResult(
        case_id=case.id,
        protocol=protocol,
        lang=case.lang,
        category=case.category,
        difficulty=case.difficulty,
        passed=False,
        called=False,
        expected_call=case.expect.kind == "call",
        name_correct=False,
        args_exact=False,
        answer_ok=False,
        malformed=False,
        output="",
        detail=error or "runner error",
    )


def run_cases(
    cases: Sequence[Case],
    runner: Runner,
    protocols: Sequence[Protocol] = PROTOCOLS,
    on_result: Callable[[CaseResult], None] | None = None,
    skip: set[tuple[str, str]] | None = None,
    batch_size: int = 1,
) -> list[CaseResult]:
    results: list[CaseResult] = []
    done = skip or set()
    step = max(1, batch_size)
    for protocol in protocols:
        pending = [case for case in cases if (case.id, protocol) not in done]
        for start in range(0, len(pending), step):
            chunk = pending[start : start + step]
            prompts = [
                Prompt(
                    case=case,
                    protocol=protocol,
                    messages=tuple(render_case(case, protocol, tools_for(case.tools))),
                )
                for case in chunk
            ]
            outputs = run_batch(runner, prompts, step)
            for case, output in zip(chunk, outputs):
                result = (
                    _failed_result(case, protocol, output.error)
                    if output.text is None
                    else grade_case(case, protocol, output.text)
                )
                results.append(result)
                if on_result is not None:
                    on_result(result)
    return results


def slugify(model_id: str) -> str:
    return model_id.replace("/", "__").replace("\\", "__").replace(":", "-") or "model"


def _dedupe(results: Iterable[CaseResult]) -> list[CaseResult]:
    seen: dict[tuple[str, str], CaseResult] = {}
    for result in results:
        seen[(result.case_id, result.protocol)] = result
    return list(seen.values())


def _cmd_build(args: argparse.Namespace) -> int:
    cases = build()
    path = write_jsonl(cases, Path(args.out))
    info = manifest(cases, source=path)
    (path.parent / "manifest.json").write_text(json.dumps(info, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(info, ensure_ascii=False, indent=2))
    return 0


def _cmd_run(args: argparse.Namespace) -> int:
    protocols: tuple[Protocol, ...] = tuple(PROTOCOLS) if args.protocol == "all" else (args.protocol,)
    cases = load_cases(
        Path(args.dataset),
        langs=args.langs.split(",") if args.langs else None,
        categories=args.category.split(",") if args.category else None,
        limit=args.limit,
    )
    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)
    stem = f"{slugify(args.name or args.model or args.backend)}__{args.protocol}"

    existing = _dedupe(_load_results(out_dir / f"{stem}.json")) if args.resume else []
    done = {(result.case_id, result.protocol) for result in existing}

    runner = build_runner(
        args.backend,
        model=args.model,
        base_url=args.base_url,
        api_key=args.api_key,
        max_new_tokens=args.max_new_tokens,
        scripted_file=args.scripted_file,
        dtype=args.dtype,
        disable_thinking=not args.thinking,
    )
    if args.model and args.backend in ("transformers", "local"):
        print(
            f"loaded via {getattr(runner, 'load_info', 'n/a')} | "
            f"thinking {'on' if args.thinking else 'off'} | max_new_tokens={args.max_new_tokens} | dtype={args.dtype}"
        )

    total = sum(1 for protocol in protocols for case in cases if (case.id, protocol) not in done)
    print(
        f"model={runner.name} backend={args.backend} protocol={args.protocol} "
        f"cases={len(cases)} evaluations={total} batch={args.batch_size}"
    )

    collected: list[CaseResult] = list(existing)
    progress = {"done": 0, "passed": 0}

    def snapshot(partial: bool) -> dict[str, Any]:
        results = _dedupe(collected)
        results.sort(key=lambda item: (item.protocol, item.case_id))
        report = build_report(results, model_id=args.name or (runner.name if args.model else args.backend), protocol=args.protocol)
        if args.notes:
            report["notes"] = args.notes
        report["partial"] = partial
        return report

    def on_result(result: CaseResult) -> None:
        collected.append(result)
        progress["done"] += 1
        if result.passed:
            progress["passed"] += 1
        if not result.passed and args.verbose:
            print(f"[{progress['done']}/{total}] FAIL {result.case_id} ({result.protocol}) {result.detail[:160]}")
        if progress["done"] % 25 == 0:
            write_report(snapshot(True), out_dir, stem)
            print(
                f"[{progress['done']}/{total}] {progress['passed'] / progress['done'] * 100:.1f}%"
                f" (checkpoint written, --resume safe)"
            )

    run_cases(cases, runner=runner, protocols=protocols, on_result=on_result, skip=done, batch_size=args.batch_size)

    report = snapshot(False)
    paths = write_report(report, out_dir, stem)
    print(render_markdown(report["summary"]))
    print(f"wrote {paths['json']} and {paths['markdown']}")
    return 0


def _load_results(path: Path) -> list[CaseResult]:
    if not path.exists():
        return []
    payload = json.loads(path.read_text(encoding="utf-8"))
    return [
        CaseResult(
            case_id=item["case_id"],
            protocol=item["protocol"],
            lang=item["lang"],
            category=item["category"],
            difficulty=item["difficulty"],
            passed=item["passed"],
            called=item["called"],
            expected_call=item["expected_call"],
            name_correct=item["name_correct"],
            args_exact=item["args_exact"],
            answer_ok=item["answer_ok"],
            malformed=item["malformed"],
            output=item["output"],
            detail=item.get("detail", ""),
        )
        for item in payload.get("results", [])
    ]


def _cmd_selftest(args: argparse.Namespace) -> int:
    """Validate the grader against runners with known, exact behaviour."""
    cases = load_cases(Path(args.dataset), limit=args.limit)
    expectations = {"oracle": 1.0, "fenced": 1.0, "thinking": 1.0}
    failures: list[str] = []

    for backend in ("oracle", "fenced", "thinking", "null"):
        runner = build_runner(backend)
        results = run_cases(cases, runner, protocols=tuple(PROTOCOLS))
        report = build_report(results, model_id=backend, protocol="all")
        overall = report["summary"]["overall"]
        print(
            f"{backend:<9} n={overall['cases']:<4} score={overall['score'] * 100:6.1f}%  "
            f"calls={overall['correct_call_when_expected'] * 100:6.1f}%  "
            f"abstain={overall['correct_abstention'] * 100:6.1f}%  "
            f"spurious={overall['spurious_call_rate'] * 100:6.1f}%"
        )
        if backend in expectations and overall["score"] < expectations[backend]:
            failures.append(f"{backend} scored {overall['score']} < {expectations[backend]}")
            for item in report["failures"][:10]:
                failures.append(f"  {backend}: {item['case_id']} ({item['protocol']}) {item['detail'][:140]}")
        if backend == "null" and overall["correct_call_when_expected"] > 0:
            failures.append("null runner produced calls")
    if args.out:
        runner = build_runner("oracle")
        report = build_report(run_cases(cases, runner, protocols=tuple(PROTOCOLS)), model_id="oracle", protocol="all")
        write_report(report, Path(args.out), "selftest__oracle__all")
    if failures:
        print("\nSELFTEST FAILURES")
        print("\n".join(failures))
        return 1
    print("\nselftest passed: grading is consistent with the corpus across all protocols")
    return 0


def _cmd_report(args: argparse.Namespace) -> int:
    results = _load_results(Path(args.results))
    report = build_report(results, model_id=args.model, protocol=args.protocol)
    markdown = render_markdown(report["summary"], report)
    if args.out:
        Path(args.out).write_text(markdown, encoding="utf-8")
        print(f"wrote {args.out}")
    else:
        print(markdown)
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="tooluse1", description="ToolUse.1 tool-calling benchmark")
    subparsers = parser.add_subparsers(dest="command", required=True)

    build_parser_ = subparsers.add_parser("build", help="regenerate the frozen dataset")
    build_parser_.add_argument("--out", default=str(DATASET_PATH))
    build_parser_.set_defaults(func=_cmd_build)

    run_parser = subparsers.add_parser("run", help="evaluate a model")
    run_parser.add_argument("--model", default="", help="model id or local path")
    run_parser.add_argument("--backend", default="transformers", choices=["transformers", "local", "openai", "vllm", "ollama", "llamacpp", "scripted", "oracle", "null", "fenced", "thinking"])
    run_parser.add_argument("--base-url", default="http://localhost:8000/v1")
    run_parser.add_argument("--api-key", default="")
    run_parser.add_argument("--scripted-file", default="")
    run_parser.add_argument("--protocol", default="all", choices=["all", *PROTOCOLS])
    run_parser.add_argument("--langs", default="")
    run_parser.add_argument("--category", default="")
    run_parser.add_argument("--limit", type=int, default=None)
    run_parser.add_argument("--max-new-tokens", type=int, default=256)
    run_parser.add_argument(
        "--dtype",
        default="auto",
        choices=["auto", "bfloat16", "float16", "float32"],
        help="compute dtype; T4/Turing has no bfloat16, use float16 there (and report it)",
    )
    run_parser.add_argument("--dataset", default=str(DATASET_PATH))
    run_parser.add_argument(
        "--batch-size",
        type=int,
        default=1,
        help="evaluations per generate call (local backends; 8-16 saturates a small GPU)",
    )
    run_parser.add_argument("--out", default=str(RESULTS_DIR))
    run_parser.add_argument("--name", default="", help="human-readable run label; overrides the model path in the results file and filename")
    run_parser.add_argument("--notes", default="")
    run_parser.add_argument("--resume", action="store_true")
    run_parser.add_argument("--thinking", action="store_true", help="do not disable the model's reasoning mode")
    run_parser.add_argument("--verbose", "-v", action="store_true")
    run_parser.set_defaults(func=_cmd_run)

    selftest = subparsers.add_parser("selftest", help="check the grader against known-good runners")
    selftest.add_argument("--dataset", default=str(DATASET_PATH))
    selftest.add_argument("--limit", type=int, default=None)
    selftest.add_argument("--out", default="")
    selftest.set_defaults(func=_cmd_selftest)

    report_parser = subparsers.add_parser("report", help="re-render a results file as markdown")
    report_parser.add_argument("results")
    report_parser.add_argument("--model", default="")
    report_parser.add_argument("--protocol", default="all")
    report_parser.add_argument("--out", default="")
    report_parser.set_defaults(func=_cmd_report)
    return parser


def main(argv: Sequence[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        return int(args.func(args))
    except FileNotFoundError as error:
        print(f"error: {error}", file=sys.stderr)
        return 2
    except KeyboardInterrupt:
        print("\ninterrupted", file=sys.stderr)
        return 130
    except Exception:  # noqa: BLE001
        traceback.print_exc()
        return 1


if __name__ == "__main__":
    raise SystemExit(main())