成对评估器与位置偏差消除

成对评估器把模型输出与参考答案直接比较并给出胜者或平局,适合用数据集中的已知良好基线来检验新提示词或模型。文中还介绍了通过交换顺序并两次调用判定来消除单例位置偏差的做法。

A **双向评价器** 把模型放进去 `output` head-to-head 反对: `reference` 回答并返回一个赢家(或平局 ) 。 用它来比照一个已知的好基线来衡量一个新的即时或模型。 下面的例子要求一个 LLM 法官选择更好的候选人—— 但是 **百叶窗** 因此,法官从来不会看到模型输出是哪一边,而哪一边是参考点。 演示顺序是随机的, 使用从输入中得出的种子( 所以运行可复制) , 并且法官的位置选择在调用后会解码回原标签。 这会减轻LLM 位置偏差 — — 法官们倾向于系统地选择他们首先看到的任何反应。法官从未看到模型输出是哪一边,而它是参考文献——只有“Candidate 1”和“Candidate 2 ” 。 种子洗牌是按例决定的,因此同样的输入总是产生相同的演示顺序。 ## 代码 - Python 键 - TypeScript ``` import hashlib import json import os from openai import OpenAI _MODEL = "gpt-6-luna" _client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) _SYSTEM_PROMPT = ( "You are an impartial judge comparing two candidate responses. " "Decide which candidate is the better answer. " "Reply with strict JSON: " '{"winner": "1" | "2" | "tie", "reason": "<one-sentence justification>"}.' ) _USER_TEMPLATE = """Candidate 1: {first} Candidate 2: {second}""" def _seeded_flip(*parts): """Return True if output and reference should be swapped before showing to the judge. Seed is derived deterministically from the inputs so two runs on the same example produce the same presentation order — important for reproducibility and for caching at the LLM layer. """ digest = hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest() return int(digest[:8], 16) % 2 == 1 def evaluate(output, reference): if not output or not reference: return { "label": "missing", "score": 0.0, "explanation": "Missing output or reference.", } flip = _seeded_flip(str(output), str(reference)) first, second = (reference, output) if flip else (output, reference) response = _client.chat.completions.create( model=_MODEL, temperature=0, response_format={"type": "json_object"}, messages=[ {"role": "system", "content": _SYSTEM_PROMPT}, { "role": "user", "content": _USER_TEMPLATE.format(first=first, second=second), }, ], ) try: parsed = json.loads(response.choices[0].message.content) except (json.JSONDecodeError, AttributeError, TypeError) as exc: return { "label": "invalid", "score": 0.0, "explanation": f"Failed to parse judge response: {exc}", } winner_position = str(parsed.get("winner", "")).strip() reason = str(parsed.get("reason", ""))[:300] # Decode position back to output / reference using the flip we applied. if winner_position == "tie": label = "tie" elif winner_position == "1": label = "reference" if flip else "output" elif winner_position == "2": label = "output" if flip else "reference" else: return { "label": "invalid", "score": 0.0, "explanation": ( f"Judge returned unexpected winner {winner_position!r}; " f"expected '1', '2', or 'tie'." ), } score = {"output": 1.0, "reference": -1.0, "tie": 0.0}[label] output_position = "2" if flip else "1" return { "label": label, "score": score, "explanation": ( f"Judge chose position {winner_position} " f"(output was shown as position {output_position}). {reason}" ), } ``` **沙盒依赖性** ——粘贴到沙盒配置的依赖字段,每行一个包: ``` openai ``` ``` import OpenAI from "openai"; const MODEL = "gpt-6-luna"; const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); const SYSTEM_PROMPT = "You are an impartial judge comparing two candidate responses. " + "Decide which candidate is the better answer. " + "Reply with strict JSON: " + '{"winner": "1" | "2" | "tie", "reason": "<one-sentence justification>"}.'; function userPrompt(first: string, second: string): string { return `Candidate 1:\n${first}\n\nCandidate 2:\n${second}`; } // Deterministic per-example flip without external deps. Not cryptographically // strong — just a stable, well-distributed seed so the order is reproducible. function seededFlip(...parts: string[]): boolean { let hash = 5381; const input = parts.join("|"); for (let i = 0; i < input.length; i++) { hash = ((hash << 5) + hash + input.charCodeAt(i)) | 0; } return (hash & 1) === 1; } async function evaluate({ output, reference }: EvaluatorParams) { if (!output || !reference) { return { label: "missing", score: 0, explanation: "Missing output or reference.", }; } const flip = seededFlip(String(output), String(reference)); const [first, second] = flip ? [String(reference), String(output)] : [String(output), String(reference)]; const response = await client.chat.completions.create({ model: MODEL, temperature: 0, response_format: { type: "json_object" }, messages: [ { role: "system", content: SYSTEM_PROMPT }, { role: "user", content: userPrompt(first, second) }, ], }); let parsed: { winner?: unknown; reason?: unknown }; try { parsed = JSON.parse(response.choices[0].message.content ?? "{}"); } catch (err) { return { label: "invalid", score: 0, explanation: `Failed to parse judge response: ${(err as Error).message}`, }; } const winnerPosition = String(parsed.winner ?? "").trim(); const reason = String(parsed.reason ?? "").slice(0, 300); let label: "output" | "reference" | "tie"; if (winnerPosition === "tie") { label = "tie"; } else if (winnerPosition === "1") { label = flip ? "reference" : "output"; } else if (winnerPosition === "2") { label = flip ? "output" : "reference"; } else { return { label: "invalid", score: 0, explanation: `Judge returned unexpected winner ${JSON.stringify( winnerPosition )}; expected "1", "2", or "tie".`, }; } const scoreMap: Record<typeof label, number> = { output: 1, reference: -1, tie: 0, }; const outputPosition = flip ? "2" : "1"; return { label, score: scoreMap[label], explanation: `Judge chose position ${winnerPosition} ` + `(output was shown as position ${outputPosition}). ${reason}`, }; } ``` TypeScript版本使用一个小的djb2-风格的字符串散列,而不是SHA-256来避免一个 `node:crypto` 输入可能不会在每个 TS 沙盒中解析。它不是在密码学上很强 — — 不需要如此 — — 但它具有决定性,分布良好,足以平衡整个数据集的演示文稿命令。**沙盒依赖性** ——粘贴到沙盒配置的依赖字段,每行一个包: ``` openai ``` 那个... `flip` 裁决记录在解释中,这样你就可以从追踪中审核解码。 ## 输入映射 | 参数 | 绑定到 | | --- | --- | | `output` | 您想要评价的模型输出, 通常 `output`. | | `reference` | 比较的相互竞争的答案——通常是储存在实例上的基线或已知良好反应,通常是: `reference`. | ## 输出配置 分类。 函数随标签一起返回自己的数值分数, 因此配置这些 label-to-score 映射来匹配其生成的内容 : | 标签 | 得分数 | 含义 | | --- | --- | --- | | `output` | `1.0` | 模型输出胜过引用. | | `reference` | `-1.0` | 参考值比模型输出值强. | | `tie` | `0.0` | 法官不能将他们分开。 | | `missing` | `0.0` | 其中一项投入是空的。 | | `invalid` | `0.0` | 法官返回了错误的输出。 | 优化方向 : **最大化** - 你想吗? `output` 以参照基准取胜。 ## 运行时间要求 | 设置 | 数值 | | --- | --- | | 沙盒 | A **主办单位** 匹配语言的后端。 Python : **E2B**, **代托纳-蟒蛇**, **Vercel 沙盒- Python**,或 **模式**. TypeScript: **代托纳-TypeScript** 或 时 间 **Vercel Sandbox — TypeScript (英语).** (当地的德诺沙盒开始于 `--no-npm` 且无法安装 `openai` 软件包)。 | | 依赖关系 | Python : (原始内容存档于2017-09-29). `openai`. TypeScript: `openai` (npm) (英语). | | 互联网接入 | **要求数** 切换( T) **允许互联网访问** 打开。沙盒必须到达 `api.openai.com`. | | 环境变量 | `OPENAI_API_KEY` - 最好设为 **秘密引用** 键入 [设置 – 保密](<https://arize.com/docs/phoenix/settings/secrets>). | 每一个 `evaluate(...)` 电话打来 **一个** 聊天- 补齐请求 `gpt-6-luna`。规模: - 提升沙盒配置 **超时** 以舒适的覆盖LLM 往返加冷启动包安装. - 注意法官的每盘成本——每个对偶的提示都包括输出和参考,所以符号计数随着输出长度的增长而增加. - 有关高评价,见 **交换和确认** 。它使成本翻倍,但消除了每个实例上的位置偏差,而不是依赖随机排列的顺序来将其取消。 ## 备选案文 ### 交换和确认(position-bias-free ) 盲目上方随机排列每个例子的顺序,因此位置偏差在预期中取消——但任何单一的例子仍然可以有偏差。要删除每个例子,请给法官打电话两次(每个顺序),只有在两个调用都同意时才能返回一名胜者: ``` def evaluate(output, reference): if not output or not reference: return {"label": "missing", "score": 0.0, "explanation": "Missing input."} def _ask(first, second): response = _client.chat.completions.create( model=_MODEL, temperature=0, response_format={"type": "json_object"}, messages=[ {"role": "system", "content": _SYSTEM_PROMPT}, { "role": "user", "content": _USER_TEMPLATE.format(first=first, second=second), }, ], ) return json.loads(response.choices[0].message.content).get("winner") pick_or = _ask(output, reference) # "1" = output, "2" = reference, "tie" pick_ro = _ask(reference, output) # "1" = reference, "2" = output, "tie" # Translate both picks into output / reference / tie. vote_or = {"1": "output", "2": "reference", "tie": "tie"}.get(pick_or, "invalid") vote_ro = {"1": "reference", "2": "output", "tie": "tie"}.get(pick_ro, "invalid") if vote_or == vote_ro and vote_or in {"output", "reference", "tie"}: label = vote_or else: label = "tie" # disagreement → call it a tie score = {"output": 1.0, "reference": -1.0, "tie": 0.0, "invalid": 0.0}[label] return { "label": label, "score": score, "explanation": ( f"Order output,reference → {pick_or}; " f"order reference,output → {pick_ro}; final = {label}." ), } ``` 成本2 × API的调用,但每个实例的判决都独立于基本模型的位置偏差. ### 其他方向 - **多标准判断** ——请法官在几个轴(正确性,简洁性,格式)上得分,并结合每轴判决. 返回一个结构化的 `explanation` 所以,追踪显示 崩溃。 - **嵌入双向** - 将LLM呼叫替换为相近的余弦 `output` 财务报告和财务报告 `reference` 使用 OpenAI 嵌入或 [scikit-learn](<https://arize.com/docs/phoenix/evaluation/server-evals/code-evaluators/scikit-learn>)但是它不会像LLM法官在自由文本解答上那样获得语义等效。 这页有用吗? [建议编辑](<https://github.com/arize-ai/phoenix/edit/main/docs/phoenix/evaluation/server-evals/code-evaluators/pairwise.mdx>)提出问题

查看原始来源