Files
Negotiation_daegu/eval/01_win_rate/run_split.py
T
민헌andClaude Opus 5 f59ee53689 ① 실행 출력에서 ③ 표시 제거 — 정본이 아닌 값이 요약에 섞이지 않게
③은 2026-09-10 부터 eval/03_price_reduction/ 의 단독 측정이 정본이다.
①의 실행기는 가격 인하율을 부산물로 계속 계산해 result.json 에 남기지만,
화면 요약에 함께 찍히면 ③ 정본처럼 읽힌다.

run.py      요약 배너 제목을 "① 협상 성공률 — 평가 요약" 로, ③ 줄 삭제
            25건마다 찍던 중간집계에서도 ③ 제거
            독스트링에 ③ 정본 위치를 명시
run_split.py 3모델 종료 출력에서 ③ 제거

집계 로직과 result.json 스키마는 그대로다(화면 출력만 정리).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 13:14:01 +09:00

157 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""① 본측정 오케스트레이터 — OpenAI 3종 분할 측정.
계획서 목표 근거("LLM 협상 시뮬레이션 상위 세 개 모델 평균")에 맞춰 케이스를
3개 모델에 블록 분할(모델당 100건, 총 300건 — 2026-08-28 축소 결정)하고,
모델별 결과 + 3모델 통합을 집계한다.
※ 블록 분할 이유: 테스트셋이 27개 조합(유통×파트너×매출) 순환 구조라 교차 분할(id%3)을
쓰면 모델당 9개 조합만 배정된다. 연속 블록 333건이면 27조합이 각 ~12회씩 온전히 돈다.
사용:
python run_split.py # 새 측정 (본측정_YYYYMMDD/ 폴더 생성)
python run_split.py --resume --dir 본측정_20260828 # 중단 지점부터 재개
기록:
<폴더>/detail_<모델>.jsonl 건별 상세 (케이스마다 즉시 append — 중단 안전)
<폴더>/log_<모델>.txt 진행 로그 (25건마다 중간집계 포함, tail -f 가능)
<폴더>/result_<모델>.json 모델별 집계
<폴더>/result.json 3모델 통합 (모델별 breakdown + 가중평균 + ① 판정)
<폴더>/meta.json 측정 조건 (모델·분할·seed·시작/종료 시각)
"""
import argparse
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path
HERE = Path(__file__).parent
# 축소 설계 (2026-08-28 사용자 결정): 모델당 100건 × 3 = 총 300건
# 연속 블록 100건이면 27조합(유통×파트너×매출)이 각 3~4회씩 돌아 모델별 커버리지 유지
MODELS = [
("gpt-4o", "1:100"),
("gpt-4.1", "101:200"),
("gpt-4o-mini", "201:300"),
]
TESTSET = "00_data_testset_300.json"
TARGET_RATE, TARGET_REDUCTION = 70.0, 3.0
def run_model(model: str, case_range: str, out_dir: Path, resume: bool) -> int:
tag = model.replace(".", "_")
log_path = out_dir / f"log_{tag}.txt"
cmd = [sys.executable, str(HERE / "run.py"),
"--opponent", "llm", "--model", model,
"--testset", TESTSET, "--case-range", case_range,
"--out-dir", str(out_dir), "--tag", tag]
if resume:
cmd.append("--resume")
print(f"[{datetime.now().strftime('%H:%M:%S')}] {model} ({case_range}) 시작 → {log_path.name}",
flush=True)
with open(log_path, "a", encoding="utf-8") as log:
log.write(f"\n===== {datetime.now().isoformat()} {model} {case_range} =====\n")
log.flush()
rc = subprocess.call(cmd, stdout=log, stderr=subprocess.STDOUT)
print(f"[{datetime.now().strftime('%H:%M:%S')}] {model} 종료 (rc={rc})", flush=True)
return rc
def aggregate(out_dir: Path) -> dict:
per_model, all_details = {}, []
for model, case_range in MODELS:
tag = model.replace(".", "_")
detail_path = out_dir / f"detail_{tag}.jsonl"
rows = []
if detail_path.exists():
rows = [json.loads(x) for x in
detail_path.read_text(encoding="utf-8").splitlines() if x.strip()]
all_details.extend(rows)
n = len(rows)
s = sum(1 for r in rows if r.get("success"))
reds = [r["reduction_pct"] for r in rows if r.get("reduction_pct") is not None]
per_model[model] = {
"case_range": case_range, "n": n, "success": s,
"win_rate_pct": round(100 * s / n, 2) if n else None,
"avg_reduction_pct": round(sum(reds) / len(reds), 3) if reds else None,
"상품가_이하": sum(1 for r in rows if r.get("success_product")),
"앵커가_합의": sum(1 for r in rows if r.get("success_engine")),
}
total = len(all_details)
success = sum(1 for r in all_details if r.get("success"))
reds = [r["reduction_pct"] for r in all_details if r.get("reduction_pct") is not None]
rate = round(100 * success / total, 2) if total else 0.0
avg_red = round(sum(reds) / len(reds), 3) if reds else 0.0
model_rates = [m["win_rate_pct"] for m in per_model.values() if m["win_rate_pct"] is not None]
return {
"설계": "OpenAI 상위 3종 분할 측정 — 계획서 근거 '상위 세 개 모델 평균'(arxiv 2402.05863) 대응",
"testset": TESTSET, "seed": 20260828, "profiling": False,
"모델별": per_model,
"지표①_협상성공률": {
"판정기준": "목표가 이하 제안 확보",
"total": total, "success": success,
"win_rate_pct_통합": rate,
"win_rate_pct_3모델단순평균": round(sum(model_rates) / len(model_rates), 2)
if len(model_rates) == len(MODELS) else None,
"target_pct": TARGET_RATE,
"verdict": "PASS" if rate >= TARGET_RATE else "FAIL",
"참고지표": {
"상품가_이하_확보(계획서 기준: 손해 없는 협상)":
sum(1 for r in all_details if r.get("success_product")),
"앵커가_도달_합의":
sum(1 for r in all_details if r.get("success_engine")),
},
},
"지표③_평균가격협상률": {
"산식": "협상완료 합의 건의 (기존 공급가 − 최종 합의가) / 기존 공급가 평균",
"합의건수": len(reds), "avg_reduction_pct": avg_red,
"target_pct": TARGET_REDUCTION,
"verdict": "PASS" if avg_red >= TARGET_REDUCTION else "FAIL",
},
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dir", default=None, help="측정 폴더 (기본: 본측정_YYYYMMDD)")
ap.add_argument("--resume", action="store_true")
args = ap.parse_args()
out_dir = HERE / (args.dir or f"본측정_{datetime.now().strftime('%Y%m%d')}")
out_dir.mkdir(parents=True, exist_ok=True)
meta_path = out_dir / "meta.json"
meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.exists() else {
"설계": "OpenAI 3종 블록 분할 — 모델당 100건 (1~100/101~200/201~300)",
"models": dict(MODELS), "testset": TESTSET, "seed": 20260828,
"profiling": False, "시작": datetime.now().isoformat(),
}
meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
for model, case_range in MODELS:
rc = run_model(model, case_range, out_dir, resume=args.resume)
# 모델 하나 끝날 때마다 통합 결과 갱신 (중간에도 result.json이 항상 최신)
result = aggregate(out_dir)
(out_dir / "result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
if rc == 3: # 크레딧 소진 — 다음 모델로 넘어가지 않고 전체 중단
print("[중단] OpenAI 크레딧 소진 — 충전 후 `python3 run_split.py "
f"--dir {out_dir.name} --resume` 로 재개", flush=True)
raise SystemExit(3)
meta["종료"] = datetime.now().isoformat()
meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
result = aggregate(out_dir)
print()
print(json.dumps({"모델별": result["모델별"],
"①": result["지표①_협상성공률"]["win_rate_pct_통합"]},
ensure_ascii=False, indent=1))
if __name__ == "__main__":
main()