- 번호 → 개수 선택(엔터 = 정본 규모), Azure backend 컨테이너 전용, flock 으로 동시 실행 금지 - 컨테이너 /tmp/verify/<실행ID> 복사본에서 실행해 정본 eval 무변경, 운용 로그는 실행 전 크기로 원복 - 결과는 logs/verify/<실행ID>/, 판정은 logs/verify/판정_누적.tsv - ⑧ 직접 검색: 기준 상품과 몰별 제외 사유(AI 불일치·이름 검사·사진·기준 상품과 다름)를 identity.veto 로 표시 - ① run_split.py 에 --n 추가 — 모델 3종 블록 앞에서 균등 분할, 재개는 meta 의 분할 사용 - README 측정 실행 절 갱신 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018nTzDQLR2WxeeK96SZEs4g
172 lines
8.2 KiB
Python
172 lines
8.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 # 중단 지점부터 재개
|
|
python run_split.py --n 30 --dir 검증 # 축소 검증 — 모델마다 자기 블록의 앞 10건
|
|
|
|
기록:
|
|
<폴더>/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", "gpt-4.1", "gpt-4o-mini"]
|
|
BLOCK = 100
|
|
TESTSET = "00_data_testset_300.json"
|
|
TARGET_RATE, TARGET_REDUCTION = 70.0, 3.0
|
|
|
|
|
|
def split_plan(n: int) -> list[tuple[str, str]]:
|
|
"""총 n건을 모델 3종에 나눈다 — 각 모델은 정본과 같은 블록(1~100/101~200/201~300)의 앞쪽을 쓴다.
|
|
n=300 이면 정본 분할과 같고, 줄이면 모델별 배정이 블록 앞에서부터 잘린다."""
|
|
if not len(MODELS) <= n <= BLOCK * len(MODELS):
|
|
raise SystemExit(f"--n 은 {len(MODELS)}~{BLOCK * len(MODELS)} 사이여야 한다: {n}")
|
|
base, rem = divmod(n, len(MODELS))
|
|
return [(m, f"{i * BLOCK + 1}:{i * BLOCK + base + (1 if i < rem else 0)}")
|
|
for i, m in enumerate(MODELS)]
|
|
|
|
|
|
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, plan: list[tuple[str, str]]) -> dict:
|
|
per_model, all_details = {}, []
|
|
for model, case_range in plan:
|
|
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(plan) 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")
|
|
ap.add_argument("--n", type=int, default=BLOCK * len(MODELS),
|
|
help="총 협상 건수 (기본 300 = 정본). 모델 3종에 균등 분할")
|
|
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"
|
|
if meta_path.exists(): # 재개는 처음 실행한 분할을 그대로 쓴다
|
|
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
|
plan = list(meta["models"].items())
|
|
else:
|
|
plan = split_plan(args.n)
|
|
meta = {
|
|
"설계": "OpenAI 3종 블록 분할 — 정본은 모델당 100건 (1~100/101~200/201~300)",
|
|
"models": dict(plan), "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 plan:
|
|
rc = run_model(model, case_range, out_dir, resume=args.resume)
|
|
# 모델 하나 끝날 때마다 통합 결과 갱신 (중간에도 result.json이 항상 최신)
|
|
result = aggregate(out_dir, plan)
|
|
(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, plan)
|
|
print()
|
|
print(json.dumps({"모델별": result["모델별"],
|
|
"①": result["지표①_협상성공률"]["win_rate_pct_통합"]},
|
|
ensure_ascii=False, indent=1))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|