chore: 2차년도 성능평가 측정 구성 초기 업로드
data(train 520·holdout 120), server(발화 생성 서버), eval(grounding_eval), run_eval.py·run_test.sh. logs/ 는 실행 때마다 생기는 기록이라 README.md 만 올리고 나머지는 .gitignore 로 뺀다. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
13ab9dee84
70 files changed
+17141
No files matched your search
@@ -0,0 +1,57 @@
|
||||
# Grounding_Eval
|
||||
|
||||
2차년도 공인시험 「대화 상황 지식 그라운딩 적절성 개선율 (ROUGE 기준)」의 측정 도구입니다.
|
||||
홀드아웃 문항마다 베이스라인과 개발 모델이 같은 대화 히스토리에서 응답을 만들고, 정답(선호) 발화와의 ROUGE 를
|
||||
턴 → 세션 평균 → 전체 평균으로 집계해 개선율과 통계 검정을 냅니다 (성능평가확인서 §2.3.3, §3.2.1).
|
||||
|
||||
독립 패키지입니다. 의존성은 `kiwipiepy`(형태소 분석)뿐이고, 모델 호출·ROUGE·통계는 표준 라이브러리로 구현했습니다.
|
||||
입력은 파일(JSONL)로만 받습니다.
|
||||
|
||||
## 흐름
|
||||
|
||||
| 단계 | 명령 | 입력 → 출력 |
|
||||
|---|---|---|
|
||||
| 1. 문항 추출 | `extract` | 지시 순응 데이터 JSONL → 문항 JSONL (홀드아웃 `strategy_conditioned_response`, 정답 포함) |
|
||||
| 2. 응답 생성 | `generate` | 문항 → 모델별 생성 JSONL (`sample_id`, `candidate`, 모델·디코딩 설정) |
|
||||
| 3. 채점 | `score` | 문항 + 베이스라인·개발 생성 JSONL → `turn_scores.csv`(턴별 ROUGE 산출표), `summary.json` |
|
||||
|
||||
```bash
|
||||
python3 -m venv .venv
|
||||
.venv/bin/pip install -e ".[test]"
|
||||
|
||||
.venv/bin/grounding-eval extract --instructions 지시순응_데이터.jsonl --out 문항.jsonl
|
||||
.venv/bin/grounding-eval generate --instructions 지시순응_데이터.jsonl --system baseline \
|
||||
--base-url http://<서버>/v1 --model <베이스 모델> --out baseline.jsonl --yes
|
||||
.venv/bin/grounding-eval generate --instructions 지시순응_데이터.jsonl --system developed \
|
||||
--base-url http://<서버>/v1 --model <개발 모델> --out developed.jsonl --yes
|
||||
.venv/bin/grounding-eval score --instructions 지시순응_데이터.jsonl \
|
||||
--baseline baseline.jsonl --developed developed.jsonl --out-dir 결과/
|
||||
```
|
||||
|
||||
- `generate`는 `--yes`가 없으면 호출할 문항 수와 설정만 출력합니다(API 비용 방지). 출력 파일에 이미 있는 문항은 건너뛰므로 중단 후 같은 명령으로 이어 갑니다.
|
||||
- API 키는 환경 변수(기본 `OPENAI_API_KEY`, `--api-key-env`로 변경)에서 읽습니다. 키가 필요 없는 로컬 서버는 `--no-api-key`.
|
||||
|
||||
## 입력 형식
|
||||
|
||||
지시 순응 데이터 JSONL 의 한 줄에서 쓰는 필드: `sample_id`, `dialogue_id`(세션), `turn`, `split`, `task_type`,
|
||||
`messages`(정답 발화 직전까지의 대화, OpenAI 메시지 형식), `reference_response`(정답).
|
||||
|
||||
## 측정 조건 (기본값, 시험기관 합의 후 고정)
|
||||
|
||||
| 항목 | 기본값 | 옵션 |
|
||||
|---|---|---|
|
||||
| 주 판정 지표 | ROUGE-1 F1 (ROUGE-2·L 병기) | `--primary` |
|
||||
| 토큰화 | Kiwi 형태소 (`kiwipiepy` 버전을 `summary.json`에 기록) | `--tokenizer eojeol` |
|
||||
| 전처리 | NFC 정규화, 공백 정리, 숫자 천 단위 쉼표 제거, 문장부호 품사 제외 | `--keep-punct` |
|
||||
| 집계 | 턴 F1 → 세션 평균 → 전체 평균 | |
|
||||
| 개선율 | (개발 − 베이스라인) ÷ 베이스라인 × 100, 목표 10% | |
|
||||
| 통계 | 세션 단위 Wilcoxon signed-rank(동순위 없고 n ≤ 25 면 정확 분포, 아니면 정규근사), 부트스트랩 10,000회 95% 구간 | `--bootstrap`, `--seed` |
|
||||
| 디코딩 | temperature 0, top_p 1.0, seed 0, max_tokens 512 (두 모델 동일) | `generate` 옵션 |
|
||||
|
||||
## 테스트
|
||||
|
||||
```bash
|
||||
.venv/bin/python -m pytest
|
||||
```
|
||||
|
||||
생성 테스트는 로컬에 띄운 가짜 OpenAI 호환 서버를 쓰므로 API 비용이 들지 않습니다.
|
||||
@@ -0,0 +1,6 @@
|
||||
"""지식 그라운딩 적절성 측정 도구 (ROUGE 기준)."""
|
||||
from grounding_eval.data import EvalItem, load_items
|
||||
from grounding_eval.generate import GenerationConfig, generate_all
|
||||
from grounding_eval.score import ScoreConfig, score_turns, summarize
|
||||
|
||||
__all__ = ["EvalItem", "GenerationConfig", "ScoreConfig", "generate_all", "load_items", "score_turns", "summarize"]
|
||||
@@ -0,0 +1,3 @@
|
||||
from grounding_eval.cli import main
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,154 @@
|
||||
"""명령줄 실행: extract / generate / score.
|
||||
|
||||
python -m grounding_eval extract --instructions 지시순응_데이터.jsonl --out 문항.jsonl
|
||||
python -m grounding_eval generate --instructions 지시순응_데이터.jsonl --system baseline \\
|
||||
--base-url https://api.openai.com/v1 --model <모델> --out baseline.jsonl [--yes]
|
||||
python -m grounding_eval score --instructions 지시순응_데이터.jsonl \\
|
||||
--baseline baseline.jsonl --developed developed.jsonl --out-dir 결과/
|
||||
|
||||
generate 는 --yes 가 없으면 호출할 문항 수와 설정만 보여 주고 끝난다 (API 비용 방지).
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import sys
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
|
||||
from grounding_eval.data import HOLDOUT_SPLIT, load_items, read_jsonl, write_jsonl
|
||||
from grounding_eval.generate import GenerationConfig, GenerationError, generate_all, load_api_key
|
||||
from grounding_eval.rouge import METRICS
|
||||
from grounding_eval.score import SYSTEMS, ScoreConfig, candidates_by_id, score_turns, summarize
|
||||
from grounding_eval.tokenize import TOKENIZERS
|
||||
|
||||
TURN_TABLE = "turn_scores.csv"
|
||||
SUMMARY = "summary.json"
|
||||
|
||||
|
||||
def _add_item_args(p):
|
||||
p.add_argument("--instructions", required=True, help="지시 순응 데이터 JSONL")
|
||||
p.add_argument("--split", default=HOLDOUT_SPLIT, help=f"평가 분할 (기본 {HOLDOUT_SPLIT})")
|
||||
|
||||
|
||||
def _items(args):
|
||||
items = load_items(args.instructions, split=args.split)
|
||||
if not items:
|
||||
raise SystemExit("평가 문항이 없습니다 (분할 조건을 확인하세요)")
|
||||
return items
|
||||
|
||||
|
||||
def cmd_extract(args):
|
||||
items = _items(args)
|
||||
out = Path(args.out)
|
||||
if out.exists() and not args.overwrite:
|
||||
raise SystemExit(f"{out} 가 이미 있습니다 (--overwrite 로 덮어쓰기)")
|
||||
write_jsonl(out, [asdict(i) for i in items])
|
||||
sessions = len({i.dialogue_id for i in items})
|
||||
print(f"문항 {len(items)}개 (세션 {sessions}개) → {out}")
|
||||
|
||||
|
||||
def cmd_generate(args):
|
||||
items = _items(args)
|
||||
config = GenerationConfig(base_url=args.base_url, model=args.model, temperature=args.temperature,
|
||||
top_p=args.top_p, seed=args.seed, max_tokens=args.max_tokens)
|
||||
plan = {"system": args.system, "items": len(items), "out": args.out, **asdict(config)}
|
||||
if not args.yes:
|
||||
print(json.dumps(plan, ensure_ascii=False, indent=1))
|
||||
print("API 를 호출하지 않았습니다. 위 설정으로 실행하려면 --yes 를 붙이세요.")
|
||||
return
|
||||
api_key = None if args.no_api_key else load_api_key(args.api_key_env)
|
||||
result = generate_all(items, config, args.system, args.out, api_key=api_key, workers=args.workers,
|
||||
log=lambda m: print(m, file=sys.stderr))
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
if result["failed"]:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def write_turn_table(rows, path):
|
||||
columns = ["sample_id", "dialogue_id", "turn", "reference"]
|
||||
for system in SYSTEMS:
|
||||
columns.append(f"{system}_candidate")
|
||||
columns += [f"{system}_{m}_f1" for m in METRICS]
|
||||
with Path(path).open("w", encoding="utf-8-sig", newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=columns)
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
|
||||
|
||||
def cmd_score(args):
|
||||
items = _items(args)
|
||||
out_dir = Path(args.out_dir)
|
||||
targets = [out_dir / TURN_TABLE, out_dir / SUMMARY]
|
||||
if any(t.exists() for t in targets) and not args.overwrite:
|
||||
raise SystemExit(f"{out_dir} 에 결과가 이미 있습니다 (--overwrite 로 덮어쓰기)")
|
||||
config = ScoreConfig(tokenizer=args.tokenizer, drop_punct=not args.keep_punct, primary_metric=args.primary,
|
||||
bootstrap_iterations=args.bootstrap, seed=args.seed,
|
||||
extra={"instructions": str(args.instructions), "split": args.split,
|
||||
"baseline_file": str(args.baseline), "developed_file": str(args.developed)})
|
||||
baseline = candidates_by_id(read_jsonl(args.baseline), "baseline")
|
||||
developed = candidates_by_id(read_jsonl(args.developed), "developed")
|
||||
rows = score_turns(items, baseline, developed, config)
|
||||
summary = summarize(rows, config)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
write_turn_table(rows, targets[0])
|
||||
targets[1].write_text(json.dumps(summary, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
m = summary["metrics"][summary["primary_metric"]]
|
||||
pct = m["improvement_pct"]
|
||||
print(f"세션 {summary['sessions']}개, 턴 {summary['turns']}개 | {summary['primary_metric']} "
|
||||
f"베이스라인 {m['baseline']:.4f} → 개발 {m['developed']:.4f} | 개선율 "
|
||||
f"{'-' if pct is None else f'{pct:.2f}%'} | {'달성' if summary['achieved'] else '미달'} "
|
||||
f"(목표 {summary['target_pct']}%) | Wilcoxon p={summary['wilcoxon']['p_value']:.4g}")
|
||||
print(f"저장: {targets[0]}, {targets[1]}")
|
||||
|
||||
|
||||
def build_parser():
|
||||
parser = argparse.ArgumentParser(prog="grounding_eval", description="지식 그라운딩 적절성 측정 (ROUGE)")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
p = sub.add_parser("extract", help="평가 문항(정답 포함)을 JSONL 로 저장")
|
||||
_add_item_args(p)
|
||||
p.add_argument("--out", required=True)
|
||||
p.add_argument("--overwrite", action="store_true")
|
||||
p.set_defaults(func=cmd_extract)
|
||||
|
||||
p = sub.add_parser("generate", help="모델 응답 생성 (OpenAI 호환 API)")
|
||||
_add_item_args(p)
|
||||
p.add_argument("--system", required=True, choices=SYSTEMS)
|
||||
p.add_argument("--base-url", required=True)
|
||||
p.add_argument("--model", required=True)
|
||||
p.add_argument("--out", required=True)
|
||||
p.add_argument("--temperature", type=float, default=0.0)
|
||||
p.add_argument("--top-p", type=float, default=1.0)
|
||||
p.add_argument("--seed", type=int, default=0)
|
||||
p.add_argument("--max-tokens", type=int, default=512)
|
||||
p.add_argument("--workers", type=int, default=1)
|
||||
p.add_argument("--api-key-env", default="OPENAI_API_KEY", help="API 키를 담은 환경 변수 이름")
|
||||
p.add_argument("--no-api-key", action="store_true", help="키 없이 호출 (로컬 서버)")
|
||||
p.add_argument("--yes", action="store_true", help="실제로 API 를 호출")
|
||||
p.set_defaults(func=cmd_generate)
|
||||
|
||||
p = sub.add_parser("score", help="턴별 ROUGE·개선율·통계 검정")
|
||||
_add_item_args(p)
|
||||
p.add_argument("--baseline", required=True)
|
||||
p.add_argument("--developed", required=True)
|
||||
p.add_argument("--out-dir", required=True)
|
||||
p.add_argument("--tokenizer", choices=TOKENIZERS, default="kiwi")
|
||||
p.add_argument("--keep-punct", action="store_true", help="문장부호 토큰을 남김")
|
||||
p.add_argument("--primary", choices=METRICS, default="rouge1", help="주 판정 지표")
|
||||
p.add_argument("--bootstrap", type=int, default=10_000)
|
||||
p.add_argument("--seed", type=int, default=0)
|
||||
p.add_argument("--overwrite", action="store_true")
|
||||
p.set_defaults(func=cmd_score)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = build_parser().parse_args(argv)
|
||||
try:
|
||||
args.func(args)
|
||||
except (ValueError, GenerationError) as e:
|
||||
raise SystemExit(f"오류: {e}") from e
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
"""평가 문항 읽기.
|
||||
|
||||
입력은 지시 순응 데이터 JSONL(한 줄에 샘플 하나)이다. 이 도구가 쓰는 필드:
|
||||
sample_id, dialogue_id, turn, split, task_type, messages, reference_response.
|
||||
문항 = 홀드아웃(split=test_holdout)의 strategy_conditioned_response 샘플. messages 는 정답 발화 직전까지의 대화이고,
|
||||
reference_response 가 정답(선호) 발화다. 세션 = dialogue_id.
|
||||
"""
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
TASK_TYPE = "strategy_conditioned_response"
|
||||
HOLDOUT_SPLIT = "test_holdout"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EvalItem:
|
||||
sample_id: str
|
||||
dialogue_id: str
|
||||
turn: int
|
||||
messages: list
|
||||
reference: str
|
||||
|
||||
|
||||
def read_jsonl(path) -> list[dict]:
|
||||
rows = []
|
||||
with Path(path).open(encoding="utf-8") as f:
|
||||
for line_no, line in enumerate(f, start=1):
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
rows.append(json.loads(line))
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError(f"{path}:{line_no}: JSON 이 아닙니다 ({e.msg})") from e
|
||||
return rows
|
||||
|
||||
|
||||
def write_jsonl(path, rows) -> None:
|
||||
with Path(path).open("w", encoding="utf-8") as f:
|
||||
for row in rows:
|
||||
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
def select_items(samples: list[dict], split: str = HOLDOUT_SPLIT) -> list[EvalItem]:
|
||||
"""평가 문항을 고른다."""
|
||||
items = []
|
||||
for s in samples:
|
||||
if s.get("task_type") != TASK_TYPE or s.get("split") != split:
|
||||
continue
|
||||
if not s.get("reference_response"):
|
||||
continue
|
||||
items.append(EvalItem(sample_id=s["sample_id"], dialogue_id=s["dialogue_id"], turn=int(s["turn"]),
|
||||
messages=s["messages"], reference=s["reference_response"]))
|
||||
ids = [i.sample_id for i in items]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError("sample_id 가 중복됩니다")
|
||||
return sorted(items, key=lambda i: (i.dialogue_id, i.turn))
|
||||
|
||||
|
||||
def load_items(path, split: str = HOLDOUT_SPLIT) -> list[EvalItem]:
|
||||
return select_items(read_jsonl(path), split=split)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""문항별 모델 응답 생성 (OpenAI 호환 Chat Completions API).
|
||||
|
||||
베이스라인과 개발 모델을 같은 조건(같은 문항·같은 대화 히스토리·같은 디코딩 설정)으로 실행한다.
|
||||
OpenAI API, vLLM·TGI 등 OpenAI 호환 서버 모두 base_url 만 바꿔 쓴다.
|
||||
API 키는 환경 변수(기본 OPENAI_API_KEY)에서 읽는다. 로컬 서버처럼 키가 필요 없으면 비워 둔다.
|
||||
|
||||
출력은 JSONL 이고 한 줄에 문항 하나: sample_id, dialogue_id, turn, system, model, candidate, finish_reason, usage, params.
|
||||
이미 출력 파일에 있는 sample_id 는 건너뛴다 (중단 후 이어서 실행).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable, Optional
|
||||
|
||||
from grounding_eval.data import EvalItem, read_jsonl
|
||||
|
||||
RETRY_STATUS = frozenset({408, 409, 429, 500, 502, 503, 504})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GenerationConfig:
|
||||
base_url: str
|
||||
model: str
|
||||
temperature: float = 0.0
|
||||
top_p: float = 1.0
|
||||
seed: int = 0
|
||||
max_tokens: int = 512
|
||||
timeout: float = 120.0
|
||||
retries: int = 4
|
||||
|
||||
|
||||
class GenerationError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def load_api_key(env_name: Optional[str]) -> Optional[str]:
|
||||
if not env_name:
|
||||
return None
|
||||
key = os.environ.get(env_name)
|
||||
if not key:
|
||||
raise GenerationError(f"환경 변수 {env_name} 에 API 키가 없습니다")
|
||||
return key
|
||||
|
||||
|
||||
def chat_completion(config: GenerationConfig, messages: list, api_key: Optional[str],
|
||||
sleep: Callable[[float], None] = time.sleep) -> dict:
|
||||
body = json.dumps({"model": config.model, "messages": messages, "temperature": config.temperature,
|
||||
"top_p": config.top_p, "seed": config.seed, "max_tokens": config.max_tokens}).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if api_key:
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
url = config.base_url.rstrip("/") + "/chat/completions"
|
||||
last_error = None
|
||||
for attempt in range(config.retries + 1):
|
||||
request = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=config.timeout) as response:
|
||||
return json.loads(response.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
detail = e.read().decode("utf-8", errors="replace")[:300]
|
||||
last_error = GenerationError(f"HTTP {e.code}: {detail}")
|
||||
if e.code not in RETRY_STATUS:
|
||||
raise last_error from e
|
||||
except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
|
||||
last_error = GenerationError(f"연결 실패: {e}")
|
||||
if attempt < config.retries:
|
||||
sleep(min(2 ** attempt, 30))
|
||||
raise last_error
|
||||
|
||||
|
||||
def generate_one(item: EvalItem, config: GenerationConfig, system: str, api_key: Optional[str],
|
||||
sleep: Callable[[float], None] = time.sleep) -> dict:
|
||||
response = chat_completion(config, item.messages, api_key, sleep=sleep)
|
||||
try:
|
||||
choice = response["choices"][0]
|
||||
candidate = choice["message"]["content"] or ""
|
||||
except (KeyError, IndexError, TypeError) as e:
|
||||
raise GenerationError(f"{item.sample_id}: 응답 형식이 올바르지 않습니다: {str(response)[:300]}") from e
|
||||
params = asdict(config)
|
||||
params.pop("base_url")
|
||||
return {"sample_id": item.sample_id, "dialogue_id": item.dialogue_id, "turn": item.turn, "system": system,
|
||||
"model": response.get("model", config.model), "candidate": candidate,
|
||||
"finish_reason": choice.get("finish_reason"), "usage": response.get("usage"), "params": params}
|
||||
|
||||
|
||||
def generate_all(items: list[EvalItem], config: GenerationConfig, system: str, out_path,
|
||||
api_key: Optional[str] = None, workers: int = 1,
|
||||
sleep: Callable[[float], None] = time.sleep,
|
||||
log: Callable[[str], None] = print) -> dict:
|
||||
"""문항 전체를 생성해 out_path 에 이어 쓴다. {"done", "skipped", "failed": [sample_id, ...]} 를 돌려준다."""
|
||||
out_path = Path(out_path)
|
||||
done_ids = {r["sample_id"] for r in read_jsonl(out_path)} if out_path.exists() else set()
|
||||
todo = [i for i in items if i.sample_id not in done_ids]
|
||||
failed = []
|
||||
with out_path.open("a", encoding="utf-8") as f, ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
|
||||
futures = {pool.submit(generate_one, item, config, system, api_key, sleep): item for item in todo}
|
||||
for n, future in enumerate(as_completed(futures), start=1):
|
||||
item = futures[future]
|
||||
try:
|
||||
row = future.result()
|
||||
except GenerationError as e:
|
||||
failed.append(item.sample_id)
|
||||
log(f"[{n}/{len(todo)}] 실패 {item.sample_id}: {e}")
|
||||
continue
|
||||
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
f.flush()
|
||||
log(f"[{n}/{len(todo)}] 생성 {item.sample_id}")
|
||||
return {"done": len(todo) - len(failed), "skipped": len(items) - len(todo), "failed": sorted(failed)}
|
||||
@@ -0,0 +1,56 @@
|
||||
"""ROUGE-N / ROUGE-L (정밀도·재현율·F1). 토큰 목록을 받아 계산한다.
|
||||
|
||||
- ROUGE-N: n-gram 중첩 수 = 공통 n-gram 의 min(후보 개수, 정답 개수) 합
|
||||
- ROUGE-L: 최장 공통 부분수열(LCS) 길이 기준
|
||||
- 후보나 정답 중 하나라도 비어 있으면 0
|
||||
"""
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass
|
||||
|
||||
METRICS = ("rouge1", "rouge2", "rougeL")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Score:
|
||||
precision: float
|
||||
recall: float
|
||||
f1: float
|
||||
|
||||
|
||||
def _score(overlap: int, cand_total: int, ref_total: int) -> Score:
|
||||
if overlap == 0 or cand_total == 0 or ref_total == 0:
|
||||
return Score(0.0, 0.0, 0.0)
|
||||
p, r = overlap / cand_total, overlap / ref_total
|
||||
return Score(p, r, 2 * p * r / (p + r))
|
||||
|
||||
|
||||
def _ngrams(tokens: list[str], n: int) -> Counter:
|
||||
return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
|
||||
|
||||
|
||||
def rouge_n(candidate: list[str], reference: list[str], n: int) -> Score:
|
||||
cand, ref = _ngrams(candidate, n), _ngrams(reference, n)
|
||||
overlap = sum((cand & ref).values())
|
||||
return _score(overlap, sum(cand.values()), sum(ref.values()))
|
||||
|
||||
|
||||
def _lcs_length(a: list[str], b: list[str]) -> int:
|
||||
if not a or not b:
|
||||
return 0
|
||||
prev = [0] * (len(b) + 1)
|
||||
for x in a:
|
||||
cur = [0]
|
||||
for j, y in enumerate(b, start=1):
|
||||
cur.append(prev[j - 1] + 1 if x == y else max(prev[j], cur[j - 1]))
|
||||
prev = cur
|
||||
return prev[-1]
|
||||
|
||||
|
||||
def rouge_l(candidate: list[str], reference: list[str]) -> Score:
|
||||
return _score(_lcs_length(candidate, reference), len(candidate), len(reference))
|
||||
|
||||
|
||||
def rouge_all(candidate: list[str], reference: list[str]) -> dict[str, Score]:
|
||||
return {"rouge1": rouge_n(candidate, reference, 1),
|
||||
"rouge2": rouge_n(candidate, reference, 2),
|
||||
"rougeL": rouge_l(candidate, reference)}
|
||||
@@ -0,0 +1,116 @@
|
||||
"""턴별 ROUGE 채점과 집계 (성능평가확인서 §3.2.1).
|
||||
|
||||
1. 문항마다 베이스라인·개발 모델의 생성 발화(candidate)와 정답 발화(reference)의 ROUGE F1 을 계산한다
|
||||
2. 턴 점수를 세션(dialogue_id)별로 평균하고, 세션 평균을 다시 전체 평균한다
|
||||
3. 개선율(%) = (개발 − 베이스라인) ÷ 베이스라인 × 100. 주 지표가 목표(10%) 이상이면 달성
|
||||
4. 주 지표의 세션 점수로 Wilcoxon signed-rank 와 부트스트랩 신뢰구간을 낸다
|
||||
|
||||
생성 결과 파일은 JSONL 이고 한 줄에 {"sample_id": ..., "candidate": ...} 를 담는다 (다른 필드는 무시).
|
||||
두 모델은 같은 문항 전체에 대한 응답이 있어야 한다 (동일 조건).
|
||||
"""
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from grounding_eval.data import EvalItem
|
||||
from grounding_eval.rouge import METRICS, rouge_all
|
||||
from grounding_eval.stats import bootstrap_improvement_ci, improvement_pct, wilcoxon
|
||||
from grounding_eval.tokenize import kiwi_version, normalize, tokenize
|
||||
|
||||
TARGET_IMPROVEMENT_PCT = 10.0
|
||||
SYSTEMS = ("baseline", "developed")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ScoreConfig:
|
||||
tokenizer: str = "kiwi"
|
||||
drop_punct: bool = True
|
||||
primary_metric: str = "rouge1"
|
||||
target_pct: float = TARGET_IMPROVEMENT_PCT
|
||||
bootstrap_iterations: int = 10_000
|
||||
seed: int = 0
|
||||
extra: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
def candidates_by_id(rows: list[dict], label: str) -> dict[str, str]:
|
||||
out = {}
|
||||
for row in rows:
|
||||
sid = row.get("sample_id")
|
||||
if sid is None or "candidate" not in row:
|
||||
raise ValueError(f"{label}: sample_id 와 candidate 가 필요합니다: {row}")
|
||||
if sid in out:
|
||||
raise ValueError(f"{label}: sample_id {sid} 가 중복됩니다")
|
||||
out[sid] = row["candidate"] or ""
|
||||
return out
|
||||
|
||||
|
||||
def _check_coverage(items: list[EvalItem], cands: dict[str, str], label: str) -> None:
|
||||
missing = [i.sample_id for i in items if i.sample_id not in cands]
|
||||
if missing:
|
||||
raise ValueError(f"{label}: 생성 발화가 없는 문항 {len(missing)}개 (예: {missing[:3]})")
|
||||
|
||||
|
||||
def score_turns(items: list[EvalItem], baseline: dict[str, str], developed: dict[str, str],
|
||||
config: ScoreConfig) -> list[dict]:
|
||||
"""턴별 ROUGE 산출표의 행 목록."""
|
||||
_check_coverage(items, baseline, "baseline")
|
||||
_check_coverage(items, developed, "developed")
|
||||
rows = []
|
||||
for item in items:
|
||||
ref_tokens = tokenize(item.reference, config.tokenizer, config.drop_punct)
|
||||
row = {"sample_id": item.sample_id, "dialogue_id": item.dialogue_id, "turn": item.turn,
|
||||
"reference": normalize(item.reference)}
|
||||
for system, cands in (("baseline", baseline), ("developed", developed)):
|
||||
cand = cands[item.sample_id]
|
||||
scores = rouge_all(tokenize(cand, config.tokenizer, config.drop_punct), ref_tokens)
|
||||
row[f"{system}_candidate"] = normalize(cand)
|
||||
for metric in METRICS:
|
||||
row[f"{system}_{metric}_f1"] = scores[metric].f1
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def session_scores(rows: list[dict], system: str, metric: str) -> dict[str, float]:
|
||||
by_session = defaultdict(list)
|
||||
for row in rows:
|
||||
by_session[row["dialogue_id"]].append(row[f"{system}_{metric}_f1"])
|
||||
return {sid: sum(v) / len(v) for sid, v in sorted(by_session.items())}
|
||||
|
||||
|
||||
def summarize(rows: list[dict], config: ScoreConfig) -> dict:
|
||||
if not rows:
|
||||
raise ValueError("채점할 문항이 없습니다")
|
||||
if config.primary_metric not in METRICS:
|
||||
raise ValueError(f"primary_metric 은 {METRICS} 중 하나여야 합니다")
|
||||
metrics = {}
|
||||
for metric in METRICS:
|
||||
means = {s: session_scores(rows, s, metric) for s in SYSTEMS}
|
||||
overall = {s: sum(means[s].values()) / len(means[s]) for s in SYSTEMS}
|
||||
metrics[metric] = {"baseline": overall["baseline"], "developed": overall["developed"],
|
||||
"improvement_pct": improvement_pct(overall["baseline"], overall["developed"])}
|
||||
primary = metrics[config.primary_metric]
|
||||
base_sessions = list(session_scores(rows, "baseline", config.primary_metric).values())
|
||||
dev_sessions = list(session_scores(rows, "developed", config.primary_metric).values())
|
||||
test = wilcoxon(base_sessions, dev_sessions)
|
||||
ci = bootstrap_improvement_ci(base_sessions, dev_sessions, config.bootstrap_iterations, seed=config.seed)
|
||||
achieved = primary["improvement_pct"] is not None and primary["improvement_pct"] >= config.target_pct
|
||||
return {
|
||||
"sessions": len(base_sessions),
|
||||
"turns": len(rows),
|
||||
"metrics": metrics,
|
||||
"primary_metric": config.primary_metric,
|
||||
"target_pct": config.target_pct,
|
||||
"achieved": achieved,
|
||||
"wilcoxon": {"n": test.n, "w_plus": test.w_plus, "w_minus": test.w_minus,
|
||||
"p_value": test.p_value, "method": test.method, "significant_0.05": test.p_value < 0.05},
|
||||
"bootstrap_ci95_improvement_pct": list(ci) if ci else None,
|
||||
"conditions": {
|
||||
"tokenizer": config.tokenizer,
|
||||
"tokenizer_version": kiwi_version() if config.tokenizer == "kiwi" else None,
|
||||
"drop_punct": config.drop_punct,
|
||||
"normalization": "NFC, 공백 정리, 숫자 천 단위 쉼표 제거",
|
||||
"aggregation": "턴 F1 → 세션 평균 → 전체 평균",
|
||||
"bootstrap_iterations": config.bootstrap_iterations,
|
||||
"seed": config.seed,
|
||||
**config.extra,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
"""세션 단위 대응 표본 통계 (성능평가확인서: Wilcoxon signed-rank, 부트스트랩 10,000회 95% 신뢰구간).
|
||||
|
||||
Wilcoxon signed-rank (양측)
|
||||
- 차이 d = 개발 − 베이스라인. 차이가 0인 세션은 뺀다 (wilcox 방식)
|
||||
- |d| 의 순위를 매기고 동순위는 평균 순위
|
||||
- 동순위가 없고 n ≤ EXACT_MAX_N 이면 정확 분포, 아니면 정규근사(동순위 보정, 연속성 보정)
|
||||
|
||||
부트스트랩
|
||||
- 세션을 복원 추출해 개선율 = (개발 평균 − 베이스라인 평균) ÷ 베이스라인 평균 × 100 을 반복 계산하고 백분위 구간을 낸다
|
||||
"""
|
||||
import math
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
EXACT_MAX_N = 25
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WilcoxonResult:
|
||||
n: int # 차이가 0이 아닌 세션 수
|
||||
w_plus: float
|
||||
w_minus: float
|
||||
p_value: float
|
||||
method: str # "exact" | "normal" | "none"
|
||||
|
||||
|
||||
def _ranks(values: list[float]) -> list[float]:
|
||||
order = sorted(range(len(values)), key=lambda i: values[i])
|
||||
ranks = [0.0] * len(values)
|
||||
i = 0
|
||||
while i < len(order):
|
||||
j = i
|
||||
while j + 1 < len(order) and values[order[j + 1]] == values[order[i]]:
|
||||
j += 1
|
||||
avg = (i + j) / 2 + 1
|
||||
for k in range(i, j + 1):
|
||||
ranks[order[k]] = avg
|
||||
i = j + 1
|
||||
return ranks
|
||||
|
||||
|
||||
def _exact_p(n: int, w: float) -> float:
|
||||
"""순위 1..n 의 부분집합 합이 w 이하인 경우의 수로 양측 p."""
|
||||
limit = int(math.floor(w))
|
||||
counts = [0] * (limit + 1)
|
||||
counts[0] = 1
|
||||
for r in range(1, n + 1):
|
||||
for s in range(limit, r - 1, -1):
|
||||
counts[s] += counts[s - r]
|
||||
return min(1.0, 2 * sum(counts) / 2 ** n)
|
||||
|
||||
|
||||
def wilcoxon(baseline: list[float], developed: list[float]) -> WilcoxonResult:
|
||||
if len(baseline) != len(developed):
|
||||
raise ValueError("baseline 과 developed 의 세션 수가 다릅니다")
|
||||
diffs = [d - b for b, d in zip(baseline, developed) if d - b != 0]
|
||||
n = len(diffs)
|
||||
if n == 0:
|
||||
return WilcoxonResult(0, 0.0, 0.0, 1.0, "none")
|
||||
abs_d = [abs(d) for d in diffs]
|
||||
ranks = _ranks(abs_d)
|
||||
w_plus = sum(r for r, d in zip(ranks, diffs) if d > 0)
|
||||
w_minus = sum(r for r, d in zip(ranks, diffs) if d < 0)
|
||||
has_ties = len(set(abs_d)) < n
|
||||
if not has_ties and n <= EXACT_MAX_N:
|
||||
return WilcoxonResult(n, w_plus, w_minus, _exact_p(n, min(w_plus, w_minus)), "exact")
|
||||
mean = n * (n + 1) / 4
|
||||
tie_sizes = [abs_d.count(v) for v in set(abs_d)]
|
||||
var = n * (n + 1) * (2 * n + 1) / 24 - sum(t ** 3 - t for t in tie_sizes) / 48
|
||||
if var <= 0:
|
||||
return WilcoxonResult(n, w_plus, w_minus, 1.0, "normal")
|
||||
diff = w_plus - mean
|
||||
z = (abs(diff) - 0.5) / math.sqrt(var) if abs(diff) >= 0.5 else 0.0
|
||||
p = math.erfc(z / math.sqrt(2))
|
||||
return WilcoxonResult(n, w_plus, w_minus, min(1.0, p), "normal")
|
||||
|
||||
|
||||
def improvement_pct(baseline_mean: float, developed_mean: float) -> Optional[float]:
|
||||
if baseline_mean == 0:
|
||||
return None
|
||||
return (developed_mean - baseline_mean) / baseline_mean * 100
|
||||
|
||||
|
||||
def bootstrap_improvement_ci(baseline: list[float], developed: list[float], iterations: int = 10_000,
|
||||
confidence: float = 0.95, seed: int = 0) -> Optional[tuple[float, float]]:
|
||||
"""세션 복원 추출 부트스트랩의 개선율(%) 백분위 신뢰구간. 계산할 수 없으면 None."""
|
||||
if len(baseline) != len(developed):
|
||||
raise ValueError("baseline 과 developed 의 세션 수가 다릅니다")
|
||||
n = len(baseline)
|
||||
if n == 0:
|
||||
return None
|
||||
rng = random.Random(seed)
|
||||
values = []
|
||||
for _ in range(iterations):
|
||||
idx = [rng.randrange(n) for _ in range(n)]
|
||||
b = sum(baseline[i] for i in idx) / n
|
||||
d = sum(developed[i] for i in idx) / n
|
||||
pct = improvement_pct(b, d)
|
||||
if pct is not None:
|
||||
values.append(pct)
|
||||
if not values:
|
||||
return None
|
||||
values.sort()
|
||||
alpha = (1 - confidence) / 2
|
||||
lo = values[int(math.floor(alpha * (len(values) - 1)))]
|
||||
hi = values[int(math.ceil((1 - alpha) * (len(values) - 1)))]
|
||||
return lo, hi
|
||||
@@ -0,0 +1,52 @@
|
||||
"""한국어 토큰화와 전처리 규칙. 베이스라인과 개발 모델에 같은 규칙을 적용한다 (성능평가확인서 ROUGE 산출 조건).
|
||||
|
||||
전처리 (normalize)
|
||||
- 유니코드 NFC 정규화, 앞뒤 공백 제거, 연속 공백을 하나로
|
||||
- 숫자 천 단위 구분 쉼표 제거: "4,900원" → "4900원" (표기 차이로 점수가 갈리지 않게)
|
||||
|
||||
토큰화
|
||||
- kiwi: Kiwi 형태소 분석 결과의 형태소(form). drop_punct 이면 문장부호·기호 품사(S*: SF, SP, SS, SE, SO, SW)를 뺀다
|
||||
(숫자 SN, 외국어 SL, 한자 SH 는 남긴다)
|
||||
- eojeol: 공백 기준 어절 (형태소 분석기 없이 비교할 때)
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
from functools import lru_cache
|
||||
|
||||
PUNCT_TAGS = frozenset({"SF", "SP", "SS", "SSO", "SSC", "SE", "SO", "SW"})
|
||||
TOKENIZERS = ("kiwi", "eojeol")
|
||||
|
||||
_THOUSANDS = re.compile(r"(?<=\d),(?=\d{3}(?!\d))")
|
||||
_SPACES = re.compile(r"\s+")
|
||||
|
||||
|
||||
def normalize(text: str) -> str:
|
||||
text = unicodedata.normalize("NFC", text or "")
|
||||
text = _THOUSANDS.sub("", text)
|
||||
return _SPACES.sub(" ", text).strip()
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _kiwi():
|
||||
from kiwipiepy import Kiwi
|
||||
return Kiwi()
|
||||
|
||||
|
||||
def kiwi_version() -> str:
|
||||
import kiwipiepy
|
||||
return kiwipiepy.__version__
|
||||
|
||||
|
||||
def tokenize(text: str, method: str = "kiwi", drop_punct: bool = True) -> list[str]:
|
||||
text = normalize(text)
|
||||
if not text:
|
||||
return []
|
||||
if method == "eojeol":
|
||||
tokens = text.split(" ")
|
||||
if drop_punct:
|
||||
tokens = [t.strip(".,!?;:\"'()[]{}…~·") for t in tokens]
|
||||
return [t for t in tokens if t]
|
||||
if method == "kiwi":
|
||||
return [t.form for t in _kiwi().tokenize(text)
|
||||
if not (drop_punct and t.tag in PUNCT_TAGS)]
|
||||
raise ValueError(f"unknown tokenizer: {method} (choose from {TOKENIZERS})")
|
||||
@@ -0,0 +1,23 @@
|
||||
[project]
|
||||
name = "grounding-eval"
|
||||
version = "0.1.0"
|
||||
description = "지식 그라운딩 적절성 측정 도구: 홀드아웃 문항 추출·모델 응답 생성·턴별 ROUGE·개선율·통계 검정"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = ["kiwipiepy>=0.24"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = ["pytest"]
|
||||
|
||||
[project.scripts]
|
||||
grounding-eval = "grounding_eval.cli:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=61"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["grounding_eval"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["."]
|
||||
@@ -0,0 +1,77 @@
|
||||
import csv
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from grounding_eval.cli import main
|
||||
from grounding_eval.data import read_jsonl, write_jsonl
|
||||
|
||||
|
||||
def sample(sid, did, turn, ref, split="test_holdout"):
|
||||
return {"sample_id": sid, "dialogue_id": did, "turn": turn, "split": split,
|
||||
"task_type": "strategy_conditioned_response", "reference_response": ref,
|
||||
"messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "u"}]}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def instructions(tmp_path):
|
||||
path = tmp_path / "i.jsonl"
|
||||
write_jsonl(path, [sample("A", "D1", 2, "연간 400개 거래를 고려해 4,900원을 제안드립니다."),
|
||||
sample("B", "D2", 2, "대체 공급사 견적도 받아 보았습니다."),
|
||||
sample("C", "D3", 2, "학습용", split="train")])
|
||||
return path
|
||||
|
||||
|
||||
def test_extract(instructions, tmp_path, capsys):
|
||||
out = tmp_path / "items.jsonl"
|
||||
|
||||
main(["extract", "--instructions", str(instructions), "--out", str(out)])
|
||||
|
||||
rows = read_jsonl(out)
|
||||
assert [r["sample_id"] for r in rows] == ["A", "B"]
|
||||
assert "reference" in rows[0] and "messages" in rows[0]
|
||||
with pytest.raises(SystemExit):
|
||||
main(["extract", "--instructions", str(instructions), "--out", str(out)])
|
||||
|
||||
|
||||
def test_generate_without_yes_makes_no_call(instructions, tmp_path, capsys):
|
||||
out = tmp_path / "b.jsonl"
|
||||
|
||||
main(["generate", "--instructions", str(instructions), "--system", "baseline",
|
||||
"--base-url", "http://127.0.0.1:9/v1", "--model", "m", "--out", str(out)])
|
||||
|
||||
assert "--yes" in capsys.readouterr().out
|
||||
assert not out.exists()
|
||||
|
||||
|
||||
def test_score_writes_turn_table_and_summary(instructions, tmp_path):
|
||||
base, dev = tmp_path / "b.jsonl", tmp_path / "d.jsonl"
|
||||
write_jsonl(base, [{"sample_id": "A", "candidate": "조금 더 깎아 주실 수 있을까요"},
|
||||
{"sample_id": "B", "candidate": "검토 부탁드립니다"}])
|
||||
write_jsonl(dev, [{"sample_id": "A", "candidate": "연간 400개 거래를 감안해 4900원을 제안드립니다"},
|
||||
{"sample_id": "B", "candidate": "대체 공급사 견적을 받아 보았습니다"}])
|
||||
out_dir = tmp_path / "result"
|
||||
|
||||
main(["score", "--instructions", str(instructions), "--baseline", str(base), "--developed", str(dev),
|
||||
"--out-dir", str(out_dir), "--bootstrap", "200"])
|
||||
|
||||
summary = json.loads((out_dir / "summary.json").read_text(encoding="utf-8"))
|
||||
with (out_dir / "turn_scores.csv").open(encoding="utf-8-sig") as f:
|
||||
table = list(csv.DictReader(f))
|
||||
assert (summary["sessions"], summary["turns"]) == (2, 2)
|
||||
assert summary["metrics"]["rouge1"]["developed"] > summary["metrics"]["rouge1"]["baseline"]
|
||||
assert summary["achieved"] is True
|
||||
assert summary["conditions"]["tokenizer"] == "kiwi" and summary["conditions"]["tokenizer_version"]
|
||||
assert [r["sample_id"] for r in table] == ["A", "B"]
|
||||
with pytest.raises(SystemExit):
|
||||
main(["score", "--instructions", str(instructions), "--baseline", str(base), "--developed", str(dev),
|
||||
"--out-dir", str(out_dir)])
|
||||
|
||||
|
||||
def test_score_reports_missing_candidates(instructions, tmp_path):
|
||||
base = tmp_path / "b.jsonl"
|
||||
write_jsonl(base, [{"sample_id": "A", "candidate": "x"}])
|
||||
|
||||
with pytest.raises(SystemExit, match="생성 발화가 없는 문항"):
|
||||
main(["score", "--instructions", str(instructions), "--baseline", str(base), "--developed", str(base),
|
||||
"--out-dir", str(tmp_path / "r")])
|
||||
@@ -0,0 +1,47 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from grounding_eval.data import load_items, select_items
|
||||
|
||||
|
||||
def sample(sid, did="DLG-1", turn=2, split="test_holdout", task="strategy_conditioned_response",
|
||||
ref="응답"):
|
||||
return {"sample_id": sid, "dialogue_id": did, "turn": turn, "split": split, "task_type": task,
|
||||
"messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "u"}],
|
||||
"reference_response": ref}
|
||||
|
||||
|
||||
def test_selects_holdout_response_samples_only():
|
||||
samples = [sample("A"), sample("B", split="train"), sample("C", task="next_strategy"), sample("D", ref="")]
|
||||
|
||||
assert [i.sample_id for i in select_items(samples)] == ["A"]
|
||||
|
||||
|
||||
def test_items_sorted_by_dialogue_and_turn():
|
||||
samples = [sample("A", did="DLG-2", turn=2), sample("B", did="DLG-1", turn=4), sample("C", did="DLG-1", turn=2)]
|
||||
|
||||
assert [i.sample_id for i in select_items(samples)] == ["C", "B", "A"]
|
||||
|
||||
|
||||
def test_duplicate_sample_id_raises():
|
||||
with pytest.raises(ValueError):
|
||||
select_items([sample("A"), sample("A", turn=4)])
|
||||
|
||||
|
||||
def test_load_items_reads_jsonl(tmp_path):
|
||||
path = tmp_path / "i.jsonl"
|
||||
path.write_text("\n".join(json.dumps(s, ensure_ascii=False) for s in [sample("A"), sample("B", split="train")]) + "\n",
|
||||
encoding="utf-8")
|
||||
|
||||
items = load_items(path)
|
||||
|
||||
assert len(items) == 1 and items[0].reference == "응답"
|
||||
|
||||
|
||||
def test_load_items_reports_bad_line(tmp_path):
|
||||
path = tmp_path / "i.jsonl"
|
||||
path.write_text('{"sample_id": "A"}\nnot json\n', encoding="utf-8")
|
||||
|
||||
with pytest.raises(ValueError, match=":2:"):
|
||||
load_items(path)
|
||||
@@ -0,0 +1,140 @@
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from grounding_eval.data import EvalItem, read_jsonl
|
||||
from grounding_eval.generate import (GenerationConfig, GenerationError, chat_completion, generate_all,
|
||||
load_api_key)
|
||||
|
||||
|
||||
class FakeServer:
|
||||
"""OpenAI 호환 /chat/completions 흉내. 마지막 user 메시지를 되돌려 준다."""
|
||||
|
||||
def __init__(self, fail_first=0, status=500):
|
||||
self.requests, self.fail_left, self.status = [], fail_first, status
|
||||
server = self
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
server.requests.append({"path": self.path, "auth": self.headers.get("Authorization"), "body": body})
|
||||
if server.fail_left > 0:
|
||||
server.fail_left -= 1
|
||||
self.send_response(server.status)
|
||||
self.end_headers()
|
||||
self.wfile.write(b'{"error": "fail"}')
|
||||
return
|
||||
reply = {"model": body["model"], "usage": {"total_tokens": 3},
|
||||
"choices": [{"message": {"role": "assistant", "content": "echo:" + body["messages"][-1]["content"]},
|
||||
"finish_reason": "stop"}]}
|
||||
data = json.dumps(reply, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
||||
self.url = f"http://127.0.0.1:{self.httpd.server_address[1]}/v1"
|
||||
|
||||
def close(self):
|
||||
self.httpd.shutdown()
|
||||
self.httpd.server_close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server():
|
||||
s = FakeServer()
|
||||
yield s
|
||||
s.close()
|
||||
|
||||
|
||||
def items(n=3):
|
||||
return [EvalItem(sample_id=f"S{i}", dialogue_id="D1", turn=2 * i, reference="r",
|
||||
messages=[{"role": "system", "content": "sys"}, {"role": "user", "content": f"u{i}"}])
|
||||
for i in range(n)]
|
||||
|
||||
|
||||
def no_sleep(_):
|
||||
pass
|
||||
|
||||
|
||||
def test_request_uses_fixed_decoding_and_auth(server):
|
||||
config = GenerationConfig(base_url=server.url, model="base-model", seed=42)
|
||||
|
||||
chat_completion(config, [{"role": "user", "content": "안녕"}], "KEY")
|
||||
|
||||
req = server.requests[0]
|
||||
assert req["path"] == "/v1/chat/completions"
|
||||
assert req["auth"] == "Bearer KEY"
|
||||
assert {k: req["body"][k] for k in ("model", "temperature", "top_p", "seed")} == \
|
||||
{"model": "base-model", "temperature": 0.0, "top_p": 1.0, "seed": 42}
|
||||
|
||||
|
||||
def test_no_auth_header_without_key(server):
|
||||
chat_completion(GenerationConfig(base_url=server.url, model="m"), [{"role": "user", "content": "x"}], None)
|
||||
|
||||
assert server.requests[0]["auth"] is None
|
||||
|
||||
|
||||
def test_generate_all_writes_rows_and_resumes(server, tmp_path):
|
||||
out = tmp_path / "base.jsonl"
|
||||
config = GenerationConfig(base_url=server.url, model="m")
|
||||
|
||||
first = generate_all(items(2), config, "baseline", out, sleep=no_sleep, log=lambda _: None)
|
||||
second = generate_all(items(3), config, "baseline", out, sleep=no_sleep, log=lambda _: None)
|
||||
|
||||
rows = read_jsonl(out)
|
||||
assert first == {"done": 2, "skipped": 0, "failed": []}
|
||||
assert second == {"done": 1, "skipped": 2, "failed": []}
|
||||
assert sorted(r["sample_id"] for r in rows) == ["S0", "S1", "S2"]
|
||||
assert {r["candidate"] for r in rows} == {"echo:u0", "echo:u1", "echo:u2"}
|
||||
assert all(r["system"] == "baseline" and r["params"]["temperature"] == 0.0 for r in rows)
|
||||
assert len(server.requests) == 3
|
||||
|
||||
|
||||
def test_retries_on_server_error(tmp_path):
|
||||
s = FakeServer(fail_first=2, status=503)
|
||||
try:
|
||||
sleeps = []
|
||||
result = chat_completion(GenerationConfig(base_url=s.url, model="m", retries=3),
|
||||
[{"role": "user", "content": "x"}], None, sleep=sleeps.append)
|
||||
finally:
|
||||
s.close()
|
||||
assert result["choices"][0]["message"]["content"] == "echo:x"
|
||||
assert sleeps == [1, 2]
|
||||
|
||||
|
||||
def test_client_error_is_not_retried_and_reported(tmp_path):
|
||||
s = FakeServer(fail_first=5, status=400)
|
||||
try:
|
||||
out = tmp_path / "o.jsonl"
|
||||
result = generate_all(items(1), GenerationConfig(base_url=s.url, model="m", retries=3), "baseline", out,
|
||||
sleep=no_sleep, log=lambda _: None)
|
||||
assert result == {"done": 0, "skipped": 0, "failed": ["S0"]}
|
||||
assert len(s.requests) == 1
|
||||
assert read_jsonl(out) == []
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
def test_connection_failure_raises_after_retries():
|
||||
with pytest.raises(GenerationError, match="연결 실패"):
|
||||
chat_completion(GenerationConfig(base_url="http://127.0.0.1:9/v1", model="m", retries=1, timeout=2),
|
||||
[{"role": "user", "content": "x"}], None, sleep=no_sleep)
|
||||
|
||||
|
||||
def test_load_api_key(monkeypatch):
|
||||
monkeypatch.setenv("TEST_EVAL_KEY", "abc")
|
||||
monkeypatch.delenv("MISSING_EVAL_KEY", raising=False)
|
||||
|
||||
assert load_api_key("TEST_EVAL_KEY") == "abc"
|
||||
assert load_api_key(None) is None
|
||||
with pytest.raises(GenerationError):
|
||||
load_api_key("MISSING_EVAL_KEY")
|
||||
@@ -0,0 +1,43 @@
|
||||
import pytest
|
||||
|
||||
from grounding_eval.rouge import rouge_all, rouge_l, rouge_n
|
||||
|
||||
|
||||
def test_rouge1_counts_clipped_overlap():
|
||||
# 후보 a a b c / 정답 a b b d → 공통 a(min 2,1)=1, b(min 1,2)=1 → 2
|
||||
score = rouge_n(["a", "a", "b", "c"], ["a", "b", "b", "d"], 1)
|
||||
|
||||
assert score.precision == pytest.approx(2 / 4)
|
||||
assert score.recall == pytest.approx(2 / 4)
|
||||
assert score.f1 == pytest.approx(0.5)
|
||||
|
||||
|
||||
def test_rouge2_uses_bigrams():
|
||||
# 후보 바이그램 (a,b)(b,c) / 정답 (a,b)(b,d)(d,c) → 공통 1
|
||||
score = rouge_n(["a", "b", "c"], ["a", "b", "d", "c"], 2)
|
||||
|
||||
assert score.precision == pytest.approx(1 / 2)
|
||||
assert score.recall == pytest.approx(1 / 3)
|
||||
assert score.f1 == pytest.approx(2 * (1 / 2) * (1 / 3) / (1 / 2 + 1 / 3))
|
||||
|
||||
|
||||
def test_rouge_l_uses_longest_common_subsequence():
|
||||
# LCS(a b c d e, a c e x) = a c e → 3
|
||||
score = rouge_l(["a", "b", "c", "d", "e"], ["a", "c", "e", "x"])
|
||||
|
||||
assert score.precision == pytest.approx(3 / 5)
|
||||
assert score.recall == pytest.approx(3 / 4)
|
||||
|
||||
|
||||
def test_identical_sequences_score_one():
|
||||
tokens = ["연간", "400", "개", "거래"]
|
||||
assert all(s.f1 == pytest.approx(1.0) for s in rouge_all(tokens, tokens).values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cand, ref", [([], ["a"]), (["a"], []), ([], []), (["a"], ["b"])])
|
||||
def test_empty_or_disjoint_scores_zero(cand, ref):
|
||||
assert all(s.f1 == 0.0 for s in rouge_all(cand, ref).values())
|
||||
|
||||
|
||||
def test_bigram_on_single_token_is_zero():
|
||||
assert rouge_n(["a"], ["a"], 2).f1 == 0.0
|
||||
@@ -0,0 +1,65 @@
|
||||
import pytest
|
||||
|
||||
from grounding_eval.data import EvalItem
|
||||
from grounding_eval.score import ScoreConfig, candidates_by_id, score_turns, session_scores, summarize
|
||||
|
||||
CONFIG = ScoreConfig(tokenizer="eojeol", bootstrap_iterations=200)
|
||||
|
||||
|
||||
def item(sid, did, turn, ref):
|
||||
return EvalItem(sample_id=sid, dialogue_id=did, turn=turn, messages=[], reference=ref)
|
||||
|
||||
|
||||
ITEMS = [
|
||||
item("A", "D1", 2, "가 나 다 라"),
|
||||
item("B", "D1", 4, "마 바 사 아"),
|
||||
item("C", "D2", 2, "자 차 카 타"),
|
||||
]
|
||||
BASE = {"A": "가 나 x y", "B": "x y z w", "C": "자 x y z"} # F1 0.5, 0, 0.25
|
||||
DEV = {"A": "가 나 다 y", "B": "마 바 z w", "C": "자 차 y z"} # F1 0.75, 0.5, 0.5
|
||||
|
||||
|
||||
def test_turn_scores():
|
||||
rows = score_turns(ITEMS, BASE, DEV, CONFIG)
|
||||
|
||||
assert [r["baseline_rouge1_f1"] for r in rows] == pytest.approx([0.5, 0.0, 0.25])
|
||||
assert [r["developed_rouge1_f1"] for r in rows] == pytest.approx([0.75, 0.5, 0.5])
|
||||
|
||||
|
||||
def test_session_mean_then_overall_mean():
|
||||
rows = score_turns(ITEMS, BASE, DEV, CONFIG)
|
||||
|
||||
assert session_scores(rows, "baseline", "rouge1") == pytest.approx({"D1": 0.25, "D2": 0.25})
|
||||
summary = summarize(rows, CONFIG)
|
||||
# 세션 평균: 베이스라인 (0.25 + 0.25)/2 = 0.25, 개발 (0.625 + 0.5)/2 = 0.5625
|
||||
assert summary["metrics"]["rouge1"]["baseline"] == pytest.approx(0.25)
|
||||
assert summary["metrics"]["rouge1"]["developed"] == pytest.approx(0.5625)
|
||||
assert summary["metrics"]["rouge1"]["improvement_pct"] == pytest.approx(125.0)
|
||||
assert summary["achieved"] is True
|
||||
assert (summary["sessions"], summary["turns"]) == (2, 3)
|
||||
|
||||
|
||||
def test_not_achieved_below_target():
|
||||
summary = summarize(score_turns(ITEMS, BASE, BASE, CONFIG), CONFIG)
|
||||
|
||||
assert summary["metrics"]["rouge1"]["improvement_pct"] == pytest.approx(0.0)
|
||||
assert summary["achieved"] is False
|
||||
assert summary["wilcoxon"]["method"] == "none"
|
||||
|
||||
|
||||
def test_missing_candidate_raises():
|
||||
with pytest.raises(ValueError, match="developed"):
|
||||
score_turns(ITEMS, BASE, {"A": "가"}, CONFIG)
|
||||
|
||||
|
||||
def test_candidates_by_id_validates_rows():
|
||||
assert candidates_by_id([{"sample_id": "A", "candidate": None}], "x") == {"A": ""}
|
||||
with pytest.raises(ValueError):
|
||||
candidates_by_id([{"sample_id": "A"}], "x")
|
||||
with pytest.raises(ValueError):
|
||||
candidates_by_id([{"sample_id": "A", "candidate": "a"}, {"sample_id": "A", "candidate": "b"}], "x")
|
||||
|
||||
|
||||
def test_unknown_primary_metric_raises():
|
||||
with pytest.raises(ValueError):
|
||||
summarize(score_turns(ITEMS, BASE, DEV, CONFIG), ScoreConfig(tokenizer="eojeol", primary_metric="bleu"))
|
||||
@@ -0,0 +1,89 @@
|
||||
import pytest
|
||||
|
||||
from grounding_eval.stats import bootstrap_improvement_ci, improvement_pct, wilcoxon
|
||||
|
||||
|
||||
def test_exact_all_positive():
|
||||
# n=5, 모두 개선 → W- = 0, 양측 p = 2 × 1/32
|
||||
result = wilcoxon([0, 0, 0, 0, 0], [1, 2, 3, 4, 5])
|
||||
|
||||
assert (result.n, result.w_plus, result.w_minus, result.method) == (5, 15, 0, "exact")
|
||||
assert result.p_value == pytest.approx(0.0625)
|
||||
|
||||
|
||||
def test_exact_mixed_signs():
|
||||
# 차이 1, -2, 3, 4, 5 → W+ = 13, W- = 2. 합이 2 이하인 부분집합 {}, {1}, {2} → p = 2 × 3/32
|
||||
result = wilcoxon([0] * 5, [1, -2, 3, 4, 5])
|
||||
|
||||
assert (result.w_plus, result.w_minus) == (13, 2)
|
||||
assert result.p_value == pytest.approx(0.1875)
|
||||
|
||||
|
||||
def test_zero_differences_are_dropped():
|
||||
result = wilcoxon([1, 1, 1], [1, 2, 1])
|
||||
|
||||
assert result.n == 1
|
||||
assert result.p_value == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_no_difference_at_all():
|
||||
result = wilcoxon([1, 2], [1, 2])
|
||||
|
||||
assert (result.n, result.p_value, result.method) == (0, 1.0, "none")
|
||||
|
||||
|
||||
def test_ties_use_average_ranks_and_normal_approximation():
|
||||
# |d| = 1, 1, 1 → 평균 순위 2
|
||||
result = wilcoxon([0, 0, 0], [1, 1, -1])
|
||||
|
||||
assert (result.w_plus, result.w_minus, result.method) == (4, 2, "normal")
|
||||
|
||||
|
||||
def test_normal_approximation_is_symmetric_and_detects_large_effect():
|
||||
base = [0.30 + i * 0.001 for i in range(40)]
|
||||
up = [b + 0.02 + i * 0.0001 for i, b in enumerate(base)]
|
||||
down = [b - 0.02 - i * 0.0001 for i, b in enumerate(base)]
|
||||
|
||||
r_up, r_down = wilcoxon(base, up), wilcoxon(base, down)
|
||||
|
||||
assert r_up.method == "normal"
|
||||
assert r_up.p_value == pytest.approx(r_down.p_value)
|
||||
assert r_up.p_value < 0.001
|
||||
|
||||
|
||||
def test_length_mismatch_raises():
|
||||
with pytest.raises(ValueError):
|
||||
wilcoxon([1], [1, 2])
|
||||
|
||||
|
||||
def test_improvement_pct():
|
||||
assert improvement_pct(0.30, 0.34) == pytest.approx(13.333, abs=1e-3)
|
||||
assert improvement_pct(0.0, 0.1) is None
|
||||
|
||||
|
||||
def test_bootstrap_constant_improvement():
|
||||
lo, hi = bootstrap_improvement_ci([1.0] * 10, [1.1] * 10, iterations=500)
|
||||
|
||||
assert lo == pytest.approx(10.0) and hi == pytest.approx(10.0)
|
||||
|
||||
|
||||
def test_bootstrap_is_reproducible_with_seed():
|
||||
base = [0.2, 0.3, 0.25, 0.4, 0.35]
|
||||
dev = [0.25, 0.28, 0.3, 0.45, 0.4]
|
||||
|
||||
assert bootstrap_improvement_ci(base, dev, iterations=300, seed=7) == \
|
||||
bootstrap_improvement_ci(base, dev, iterations=300, seed=7)
|
||||
|
||||
|
||||
def test_bootstrap_interval_contains_point_estimate():
|
||||
base = [0.2, 0.3, 0.25, 0.4, 0.35, 0.28]
|
||||
dev = [0.25, 0.28, 0.3, 0.45, 0.4, 0.33]
|
||||
point = improvement_pct(sum(base) / 6, sum(dev) / 6)
|
||||
|
||||
lo, hi = bootstrap_improvement_ci(base, dev, iterations=2000)
|
||||
|
||||
assert lo <= point <= hi
|
||||
|
||||
|
||||
def test_bootstrap_without_sessions():
|
||||
assert bootstrap_improvement_ci([], []) is None
|
||||
@@ -0,0 +1,43 @@
|
||||
import pytest
|
||||
|
||||
from grounding_eval.tokenize import normalize, tokenize
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text, expected", [
|
||||
("4,900원을 제안드립니다", "4900원을 제안드립니다"),
|
||||
("1,234,567원", "1234567원"),
|
||||
(" 연간 400개 ", "연간 400개"),
|
||||
("3,5%", "3,5%"), # 천 단위가 아닌 쉼표는 그대로
|
||||
(None, ""),
|
||||
])
|
||||
def test_normalize(text, expected):
|
||||
assert normalize(text) == expected
|
||||
|
||||
|
||||
def test_kiwi_tokens_are_morphemes_without_punctuation():
|
||||
tokens = tokenize("연간 400개 거래를 감안해 4,900원을 제안드립니다.")
|
||||
|
||||
assert tokens[:4] == ["연간", "400", "개", "거래"]
|
||||
assert "4900" in tokens
|
||||
assert "." not in tokens
|
||||
|
||||
|
||||
def test_kiwi_keeps_punctuation_when_asked():
|
||||
assert "." in tokenize("제안드립니다.", drop_punct=False)
|
||||
|
||||
|
||||
def test_number_formats_tokenize_the_same():
|
||||
assert tokenize("4,900원") == tokenize("4900원")
|
||||
|
||||
|
||||
def test_eojeol_tokens():
|
||||
assert tokenize("4,900원을 제안드립니다.", method="eojeol") == ["4900원을", "제안드립니다"]
|
||||
|
||||
|
||||
def test_empty_text():
|
||||
assert tokenize(" ") == []
|
||||
|
||||
|
||||
def test_unknown_tokenizer_raises():
|
||||
with pytest.raises(ValueError):
|
||||
tokenize("가", method="mecab")
|
||||
Reference in new issue
Block a user