Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bench/bird/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
runs/
*.sqlite
*.zip
213 changes: 213 additions & 0 deletions bench/bird/SCHEMA_RECOVERY_PR_BODY.md

Large diffs are not rendered by default.

213 changes: 213 additions & 0 deletions bench/bird/SCHEMA_RECOVERY_RESULTS.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions bench/bird/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""BIRD Mini-Dev SQLite evidence evaluation."""
147 changes: 147 additions & 0 deletions bench/bird/dataset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"""Freeze the BIRD cohort and project records for inference."""

from __future__ import annotations

import hashlib
import json
from dataclasses import asdict, dataclass
from pathlib import Path

from bench.common.io import ProtocolError, digest, read_json, write_json, write_text

COHORT_PATH = Path(__file__).with_name("manifest-sqlite365.json")
TITLE = "BIRD Mini-Dev SQLite에서 evidence가 제공된 365문항"
EX_REFERENCE = {
"repository": "bird-bench/mini_dev",
"commit": "1c49a375e76c471e218564da3f4617513d33e371",
"path": "evaluation/evaluation_ex.py",
"blob_sha": "45cc3bb8cb6edf039e6a8a2897b7b5f06aa23970",
"function": "calculate_ex",
}


@dataclass(frozen=True)
class Case:
question_id: int
db_id: str
difficulty: str
question: str
evidence: str

def metadata(self) -> dict:
return {
"question_id": self.question_id,
"db_id": self.db_id,
"difficulty": self.difficulty,
}


def frozen_cohort() -> dict:
return read_json(COHORT_PATH)


def source_rows(source: Path, cohort: dict) -> list[dict]:
raw = source.read_bytes()
if hashlib.sha256(raw).hexdigest() != cohort["source_sha256"]:
raise ProtocolError("Annotation file differs from the frozen BIRD revision")
rows = [json.loads(line) for line in raw.splitlines()]
ids = [row["question_id"] for row in rows]
if len(ids) != cohort["source_count"] or len(set(ids)) != len(ids):
raise ProtocolError("Annotation count or question IDs do not match the cohort")
selected = sorted(
(row for row in rows if row["evidence"].strip()),
key=lambda row: row["question_id"],
)
if [row["question_id"] for row in selected] != cohort["question_ids"]:
raise ProtocolError("Evidence selection does not match the frozen question IDs")
if sorted({row["db_id"] for row in selected}) != cohort["db_ids"]:
raise ProtocolError("Database IDs do not match the frozen cohort")
return selected


def project(row: dict) -> Case:
return Case(
question_id=row["question_id"],
db_id=row["db_id"],
difficulty=row["difficulty"],
question=row["question"],
evidence=row["evidence"],
)


def database_path(directory: Path, db_id: str) -> Path:
filename = f"{db_id}.sqlite"
candidates = (directory / db_id / filename, directory / filename)
files = {path.resolve() for path in candidates if path.is_file()}
if len(files) != 1:
raise ProtocolError(f"Expected one SQLite database file for {db_id}")
db = files.pop()
for suffix in ("-wal", "-journal"):
sidecar = db.with_name(db.name + suffix)
if sidecar.exists() and sidecar.stat().st_size:
raise ProtocolError(
f"SQLite snapshot has an active sidecar: {db_id}{suffix}"
)
return db


def prepare(source: Path, db_dir: Path, db_revision: str, output: Path) -> dict:
cohort = frozen_cohort()
cases = [project(row) for row in source_rows(source, cohort)]
db_hashes = {
db_id: digest(database_path(db_dir, db_id)) for db_id in cohort["db_ids"]
}
if not db_revision.strip():
raise ProtocolError("A database snapshot revision is required")
projected = "".join(
json.dumps(asdict(case), ensure_ascii=False) + "\n" for case in cases
)
manifest = {
"format_version": 1,
"title": TITLE,
"cohort": cohort,
"database_revision": db_revision,
"database_sha256": db_hashes,
"cases": [case.metadata() for case in cases],
"cases_sha256": hashlib.sha256(projected.encode("utf-8")).hexdigest(),
"ex_reference": EX_REFERENCE,
}
output.mkdir(parents=True, exist_ok=False)
write_text(output / "cases.jsonl", projected)
write_json(output / "manifest.json", manifest)
return manifest


def load_manifest(directory: Path) -> dict:
manifest = read_json(directory / "manifest.json")
cohort = frozen_cohort()
if (
manifest["format_version"] != 1
or manifest["cohort"] != cohort
or manifest["ex_reference"] != EX_REFERENCE
or [c["question_id"] for c in manifest["cases"]] != cohort["question_ids"]
or sorted(manifest["database_sha256"]) != cohort["db_ids"]
or sorted({c["db_id"] for c in manifest["cases"]}) != cohort["db_ids"]
):
raise ProtocolError("Manifest differs from the frozen cohort or EX protocol")
return manifest


def load_cases(directory: Path, manifest: dict) -> list[Case]:
data = (directory / "cases.jsonl").read_bytes()
if hashlib.sha256(data).hexdigest() != manifest["cases_sha256"]:
raise ProtocolError("Inference input hash does not match the manifest")
cases = [Case(**json.loads(line)) for line in data.splitlines()]
if [case.metadata() for case in cases] != manifest["cases"]:
raise ProtocolError("Inference question metadata does not match the manifest")
return cases


def verify_databases(db_dir: Path, manifest: dict) -> dict[str, Path]:
paths = {}
for db_id, checksum in manifest["database_sha256"].items():
db = database_path(db_dir, db_id)
if digest(db) != checksum:
raise ProtocolError(f"SQLite snapshot hash changed: {db_id}")
paths[db_id] = db
return paths
190 changes: 190 additions & 0 deletions bench/bird/evaluate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
"""Prepare, run and score independent BIRD SQLite evaluations."""

from __future__ import annotations

import argparse
import asyncio
import json
import os
import signal
from dotenv import load_dotenv
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
from types import SimpleNamespace

from bench.common.io import ProtocolError
from bench.common.providers import Transport

from .dataset import load_cases, load_manifest, prepare, verify_databases
from .protocol import (
BASELINE,
BUDGETS,
CONDITIONS,
DEFAULT_PROFILES,
load_profile,
settings,
verify_product,
)
from .runner import run_evaluation
from .scoring import check_gold, require_gold_check, score


async def live_transport(**request):
from litellm import acompletion

return await acompletion(**request)


async def dry_run_transport(**request):
raw = {
"model": request["model"],
"choices": [
{
"message": {"content": "```sql\nSELECT 1\n```"},
"finish_reason": "stop",
}
],
}
return SimpleNamespace(model_dump=lambda: raw)


async def generate(
args: argparse.Namespace,
profile: dict[str, str],
transport: Transport,
api_key: str,
provider_version: str,
) -> dict:
product_commit = verify_product(args.product_commit)
manifest = load_manifest(args.prepared)
cases = load_cases(args.prepared, manifest)
if not args.dry_run:
require_gold_check(args.prepared, manifest, BUDGETS)
databases = verify_databases(args.db_dir, manifest)
snapshot = {
**settings(
manifest,
BUDGETS,
provider_version,
condition=args.condition,
profile=profile,
mode="dry-run" if args.dry_run else "live",
product_commit=product_commit,
),
"run_id": args.output.name,
}
stop = asyncio.Event()

def stop_after_active_cases(_signum, _frame) -> None:
stop.set()

handlers = {
num: signal.signal(num, stop_after_active_cases)
for num in (signal.SIGINT, signal.SIGTERM)
}
try:
return await run_evaluation(
args.output,
manifest,
snapshot,
cases,
databases,
transport,
api_key,
stop,
resume=args.resume,
)
finally:
for num, handler in handlers.items():
signal.signal(num, handler)


def parser() -> argparse.ArgumentParser:
root = argparse.ArgumentParser(description=__doc__)
subcommands = root.add_subparsers(dest="command", required=True)
prepare_cmd = subcommands.add_parser(
"prepare", help="Freeze inputs and DB checksums"
)
run_cmd = subcommands.add_parser(
"run", help="Generate SQL for one condition and model profile"
)
score_cmd = subcommands.add_parser("score", help="Score an independent run offline")

for command in (prepare_cmd, run_cmd, score_cmd):
command.add_argument("--output", type=Path, required=True)
command.add_argument("--db-dir", type=Path, required=True)
for command in (prepare_cmd, score_cmd):
command.add_argument(
"--source", type=Path, required=True, help="Pinned SQLite JSONL annotations"
)
prepare_cmd.add_argument(
"--db-revision", required=True, help="SQLite archive hash or image digest"
)
run_cmd.add_argument("--prepared", type=Path, required=True)
run_cmd.add_argument("--env-file", type=Path)
run_cmd.add_argument("--condition", choices=CONDITIONS, required=True)
run_cmd.add_argument(
"--product-commit",
default=BASELINE,
help="Git revision the loaded product source must match (default: recorded baseline)",
)
run_cmd.add_argument("--profile", required=True, help="Model profile name")
run_cmd.add_argument(
"--profiles", type=Path, default=DEFAULT_PROFILES, help="Model profiles JSON"
)
run_cmd.add_argument(
"--dry-run",
action="store_true",
help="Check first-request prompts with a scripted transport",
)
run_cmd.add_argument(
"--resume",
action="store_true",
help="Resume an interrupted run with the same settings",
)
score_cmd.add_argument(
"--gold-only", action="store_true", help="Check gold SQL in the prepared output"
)
return root


def main(argv: list[str] | None = None) -> int:
cli = parser()
args = cli.parse_args(argv)
try:
if args.command == "prepare":
manifest = prepare(args.source, args.db_dir, args.db_revision, args.output)
result = {"status": "prepared", "questions": len(manifest["cases"])}
elif args.command == "run":
profile = load_profile(args.profiles, args.profile)
if args.dry_run:
result = asyncio.run(
generate(args, profile, dry_run_transport, "", "scripted")
)
else:
if args.env_file:
load_dotenv(args.env_file, override=False)
key_env = profile["api_key_env"]
key = os.environ.get(key_env, "").strip()
if not key:
raise ProtocolError(f"Profile {profile['name']} requires {key_env}")
try:
provider_version = version("litellm")
except PackageNotFoundError:
raise ProtocolError(
"Install the benchmark extra before starting a run"
) from None
result = asyncio.run(
generate(args, profile, live_transport, key, provider_version)
)
else:
function = check_gold if args.gold_only else score
result = function(args.output, args.source, args.db_dir)
except (OSError, ValueError) as error:
cli.exit(1, f"{error}\n")
print(json.dumps(result, ensure_ascii=False, indent=2))
return 130 if result.get("status") == "interrupted" else 0


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