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
69 changes: 69 additions & 0 deletions bench/bird/SCHEMA_BATCH_RESULTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# BIRD SQLite 365 스키마 배치 조회 평가

PR 273의 게시 결과(`e0a7fb1`)와 PR 275의 새 실행(`9274ff1`)을 비교했다.
세 모델에서 evidence 조건 A, B, D를 각각 실행했다. 조건별 365문항과 11개 SQLite DB, 채점 규칙을 공유한다.
PR 275 제품에 PR 273 평가 실행 코드(`1f47f28`)를 가져와 3,285건을 실행했다.
두 제품 버전에 이르는 변경 전체와 각각의 모델 실행 변동이 비교에 반영된다.

| 모델 프로필 | 조건 | PR 273 EX (정답) | PR 275 EX (정답) | 차이(%p) | PR 273만 정답 | PR 275만 정답 | Holm 보정 p |
|---|---|---:|---:|---:|---:|---:|---:|
| openai-gpt41-mini | A | 16.44% (60) | 17.81% (65) | +1.37 | 26 | 31 | 1.000 |
| openai-gpt41-mini | B | 21.37% (78) | 20.82% (76) | -0.55 | 30 | 28 | 1.000 |
| openai-gpt41-mini | D | 16.16% (59) | 17.26% (63) | +1.10 | 22 | 26 | 1.000 |
| openai-gpt41 | A | 3.01% (11) | 3.56% (13) | +0.55 | 4 | 6 | 1.000 |
| openai-gpt41 | B | 2.47% (9) | 4.11% (15) | +1.64 | 2 | 8 | 0.875 |
| openai-gpt41 | D | 3.01% (11) | 3.56% (13) | +0.55 | 6 | 8 | 1.000 |
| openai-gpt6-luna | A | 40.27% (147) | 40.00% (146) | -0.27 | 42 | 41 | 1.000 |
| openai-gpt6-luna | B | 38.36% (140) | 43.84% (160) | +5.48 | 27 | 47 | 0.239 |
| openai-gpt6-luna | D | 35.07% (128) | 34.79% (127) | -0.27 | 42 | 41 | 1.000 |

**Luna D는 365문항 모두 실행·채점을 완료했다.** 정답은 127문항(34.79%)이며, 최종 미실행 문항은 0건이다.
세션 종료로 응답이 저장되지 않았던 29번, 69번, 146번, 287번은 같은 설정으로 다시 실행해 일반 문항과 같은 규칙으로 채점했다.

정확도 차이는 동일 문항을 짝지어 계산했다. p값은 양측 정확 McNemar 검정 후 아홉 비교에 Holm 보정을 적용한 값이다.

## 도구 사용과 호출 예산

| 모델 프로필 | 조건 | 다중 테이블 요청 문항 | 오류 없이 완료된 다중 테이블 조회 문항 | 스키마 조회 문항 | 전체 도구 호출 | 모델 호출 | 8회 상한 소진 |
|---|---|---:|---:|---:|---:|---:|---:|
| openai-gpt41-mini | A | 195/365 | 195/365 | 313 → 329 | 1,661 → 1,342 | 1,950 → 1,614 | 52 → 27 |
| openai-gpt41-mini | B | 238/365 | 238/365 | 326 → 337 | 1,712 → 1,303 | 1,988 → 1,580 | 54 → 32 |
| openai-gpt41-mini | D | 237/365 | 236/365 | 321 → 329 | 1,713 → 1,162 | 1,993 → 1,449 | 50 → 17 |
| openai-gpt41 | A | 2/365 | 2/365 | 0 → 2 | 0 → 10 | 365 → 375 | 0 → 0 |
| openai-gpt41 | B | 0/365 | 0/365 | 0 → 0 | 0 → 0 | 365 → 365 | 0 → 0 |
| openai-gpt41 | D | 0/365 | 0/365 | 0 → 0 | 0 → 0 | 365 → 365 | 0 → 0 |
| openai-gpt6-luna | A | 353/365 | 351/365 | 365 → 363 | 1,818 → 999 | 1,897 → 1,345 | 30 → 16 |
| openai-gpt6-luna | B | 350/365 | 349/365 | 365 → 364 | 1,922 → 1,039 | 1,927 → 1,386 | 38 → 15 |
| openai-gpt6-luna | D | 349/365 | 349/365 | 365 → 365 | 2,004 → 1,116 | 2,068 → 1,453 | 54 → 25 |

다중 테이블 요청은 `explore_schema`의 `tables`에 서로 다른 이름을 두 개 이상 전달한 경우다.
완료 문항은 그런 요청 중 오류 플래그 없이 반환된 호출이 있는 문항이다.
스키마 조회 문항은 오류 없이 한 테이블 이상의 컬럼을 요청한 문항이다.
API 오류, 실패 사유, 토큰, 응답 모델 ID와 시간은 [상세 지표](results/schema-275-v1/comparison.json)에 기록했다. 같은 문항의 EX와 PR 275 실행의 실패 사유는 [문항별 비교 점수](results/schema-275-v1/paired-scores.jsonl)에 있다.

## 실행 조건

- OpenAI SDK는 GPT‑4.1 두 프로필에 3.51.0, Luna에 3.57.0을 사용했다. Luna의 reasoning effort는 none이었다.
- 이번 실행은 Luna 평가 커밋의 공통 잠금 파일을 사용했다. PR 273의 초기 GPT‑4.1 평가 커밋의 잠금 파일과 비교해 Pydantic 및 Pydantic Core의 패치 버전에 차이가 있다.
- 각 프로필에서 A, B, D 순서로 실행했고 세 프로필은 동시에 실행했다. 개별 조합의 동시 실행은 4건이다.
- 준비한 manifest는 PR 273 게시 manifest와 일치했고 정답 SQL 365건이 사전 점검을 통과했다.

## 재현

[PR 273의 입력 준비 절차](https://github.com/jhpark324/Lang2SQL/blob/1f47f28/bench/bird/README.md)에 따라
고정된 BIRD 주석과 SQLite 배포본을 확보한다. 데이터 리비전과 DB별 해시는 상세 지표의 `provenance`에 있다.
저장소 루트에서 `uv sync --locked --extra benchmark`를 실행한 뒤, `bench.bird.evaluate`의
`prepare`와 `score --gold-only`로 입력을 준비하고 기준 SQL을 점검한다.
생성 단계에서는 아래 명령으로 PR 275 제품 소스를 지정한다.

```bash
uv run --locked --extra benchmark python -m bench.bird.evaluate run \
--condition "$BIRD_CONDITION" --profile "$BIRD_PROFILE" \
--product-commit 9274ff1 --prepared "$PREPARED" --db-dir "$DB_DIR" --output "$RUN"
uv run --locked --extra benchmark python -m bench.bird.evaluate score \
--source "$SOURCE" --db-dir "$DB_DIR" --output "$RUN"
```

조건은 `A`, `B`, `D`이고 모델 프로필은 `openai-gpt41-mini`, `openai-gpt41`, `openai-gpt6-luna`이다.
`PREPARED`와 `DB_DIR`은 공유하고 조합마다 서로 다른 `RUN` 디렉터리를 사용한다.
GPT‑4.1 계열을 기존 SDK와 맞출 때는 별도 디렉터리에 `openai==3.51.0`을 설치해 해당 실행의 `PYTHONPATH`에 둔다.
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
Loading