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,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})")
|
||||
Reference in new issue
Block a user