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:
민헌andClaude Opus 5.5 committed 2026-10-21 14:05:48 +09:00
commit 13ab9dee84
70 files changed
+17141

No files matched your search

+77
View File
@@ -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")])
+47
View File
@@ -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)
+140
View File
@@ -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")
+43
View File
@@ -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
+65
View File
@@ -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"))
+89
View File
@@ -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
+43
View File
@@ -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")