LLM 后训练实践
第2课:SFT进阶

2.3 LLM-as-Judge 评估方法

深入理解 LLM-as-Judge 评估框架,掌握 MT-Bench 评判模板,了解位置偏差和评委模型选择

为什么需要 LLM-as-Judge

传统评估方法的困境

评估方法问题
人类评估成本高(每条 $0.5-2)、耗时长(数周)、标注者间一致性低
BLEU/ROUGE基于词级匹配,无法衡量开放式回复的质量
Perplexity衡量语言建模能力,不衡量对齐质量
固定基准仅覆盖特定能力维度,无法评估通用对话质量

LLM-as-Judge 的优势

LLM-as-Judge 使用强 LLM(如 GPT-4、Qwen3-32B)对目标模型的回复进行评分,兼具人类评估的全面性自动评估的效率

  • 成本低:API 调用费用远低于人类标注
  • 速度快:数分钟完成数百条评估
  • 可复现:相同输入给出(几乎)相同结果
  • 可扩展:轻松覆盖多维度、多模型
  • 与人类高度相关:GPT-4 的评判与人类偏好的一致性超过 80%

Zheng 等(2023) 的研究表明,GPT-4 作为评委的判断与人类偏好的一致性超过 80%,高于人类评估者之间的一致性(约 81%)。这使得 LLM-as-Judge 成为实践中最常用的评估方法。


MT-Bench 评估框架

框架概述

MT-Bench(Multi-Turn Benchmark)是 LLM-as-Judge 的标准化实现:

特性详情
问题数量80 个
对话轮数每个问题 2 轮(第一轮提问 + 追问)
类别数8 个
评分范围1-10 分
评估模式单回复评分 / 成对比较

八大类别详解

类别示例问题(第一轮)示例追问(第二轮)
写作"写一封给客户的道歉邮件""现在改写为更正式的语气"
角色扮演"你是一位18世纪的探险家,描述你的发现""用现代人的视角重新描述"
推理"一个帽子里有3红2蓝球,取2个...""如果改成5红3蓝呢?"
数学"解方程 3x212=03x^2 - 12 = 0""验证你的答案"
编程"实现快速排序算法""添加性能测试"
知识提取"从给定段落中提取关键信息""用表格形式整理"
STEM"解释光合作用的过程""如果没有阳光会怎样"
人文社科"比较古希腊和古罗马的政治制度""对现代民主有何启示"

评分标准

MT-Bench 的评分指南:

1-2 分:回复质量极差
  - 完全不相关、答非所问
  - 包含严重事实错误
  - 输出无意义文本或乱码

3-4 分:回复质量差
  - 部分相关但遗漏关键信息
  - 存在明显错误
  - 格式和组织混乱

5-6 分:回复质量一般
  - 基本回答了问题
  - 有小错误或遗漏
  - 深度和细节不足

7-8 分:回复质量好
  - 准确、有用、组织良好
  - 覆盖主要方面
  - 表达清晰

9-10 分:回复质量出色
  - 全面、准确、有深度
  - 有独到见解或创意
  - 格式完美、表达流畅

评判提示模板

单回复评分模板

以下是 MT-Bench 官方使用的单回复评分提示模板:

JUDGE_PROMPT_SINGLE = """[System]
Please act as an impartial judge and evaluate the quality of the response
provided by an AI assistant to the user question displayed below. Your
evaluation should consider factors such as the helpfulness, relevance,
accuracy, depth, creativity, and level of detail of the response. Begin
your evaluation by providing a short explanation. Be as objective as
possible. After providing your explanation, you must rate the response
on a scale of 1 to 10 by strictly following this format:
"[[rating]]", for example: "Rating: [[5]]".

[Question]
{question}

[The Start of Assistant's Answer]
{answer}
[The End of Assistant's Answer]"""

成对比较模板

JUDGE_PROMPT_PAIRWISE = """[System]
Please act as an impartial judge and evaluate the quality of the responses
provided by two AI assistants to the user question displayed below. You
should choose the assistant that follows the user's instructions and
answers the user's question better. Your evaluation should consider
factors such as the helpfulness, relevance, accuracy, depth, creativity,
and level of detail of the response. Begin your evaluation by comparing
the two responses and provide a short explanation. Avoid any position
biases and ensure that the order in which the responses were presented
does not influence your decision. Do not allow the length of the responses
to influence your evaluation. Do not favor certain names of the assistants.
Be as objective as possible. After providing your explanation, output your
final verdict by strictly following this format: "[[A]]" if assistant A
is better, "[[B]]" if assistant B is better, and "[[C]]" for a tie.

[User Question]
{question}

[The Start of Assistant A's Answer]
{answer_a}
[The End of Assistant A's Answer]

[The Start of Assistant B's Answer]
{answer_b}
[The End of Assistant B's Answer]"""

中文适配模板

针对中文场景,可以使用中文评判模板:

JUDGE_PROMPT_ZH = """[系统]
请你作为一位公正的评委,评估以下 AI 助手对用户问题的回复质量。
你的评估应考虑以下因素:回复的有用性、相关性、准确性、深度、
创造性和详细程度。请先给出简短的评价说明,然后按照以下格式
给出 1-10 分的评分:"[[评分]]",例如:"评分:[[7]]"。

[用户问题]
{question}

[助手回复开始]
{answer}
[助手回复结束]"""

完整评估代码实现

使用 Qwen3-32B API 作为评委

import json
import re
import time
from openai import OpenAI

# ===== 1. 配置评委模型 API =====
# 使用阿里云 Model Studio 的 Qwen3-32B
client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

JUDGE_MODEL = "qwen3-32b"

# ===== 2. 评判函数 =====
def judge_response(question: str, answer: str, judge_model: str = JUDGE_MODEL) -> dict:
    """使用 LLM-as-Judge 对回复打分"""
    prompt = JUDGE_PROMPT_SINGLE.format(question=question, answer=answer)

    response = client.chat.completions.create(
        model=judge_model,
        messages=[{"role": "user", "content": prompt}],
        temperature=0.0,       # 评判时使用低 temperature 保证一致性
        max_tokens=512,
    )

    judge_output = response.choices[0].message.content

    # 提取评分
    match = re.search(r'\[\[(\d+)\]\]', judge_output)
    score = int(match.group(1)) if match else None

    return {
        "question": question,
        "answer": answer,
        "judge_output": judge_output,
        "score": score,
    }

# ===== 3. 批量评估 =====
def evaluate_model(model, tokenizer, test_prompts, judge_model=JUDGE_MODEL):
    """对模型在一组提示上进行 LLM-as-Judge 评估"""
    results = []
    for prompt in test_prompts:
        # 生成回复
        answer = generate_response(model, tokenizer, prompt)

        # 评判
        result = judge_response(prompt, answer, judge_model)
        results.append(result)

        # API 限速
        time.sleep(1)

    # 计算统计
    scores = [r["score"] for r in results if r["score"] is not None]
    avg_score = sum(scores) / len(scores) if scores else 0

    return {
        "results": results,
        "avg_score": avg_score,
        "num_evaluated": len(scores),
    }

# ===== 4. 多模型对比 =====
test_prompts = [
    "用三句话解释什么是量子计算",
    "写一首关于秋天的五言绝句",
    "如何用 Python 实现二分查找?请给出完整代码",
    "比较机器学习和深度学习的区别",
    "小明有 23 个苹果,给了小红 7 个,又买了 15 个,现在有几个?",
    # ... 更多测试提示
]

# 评估结果对比表
print(f"{'模型':<30} {'平均分':<10} {'评估数':<10}")
print("=" * 50)
# for model_name, model_obj in models.items():
#     result = evaluate_model(model_obj, tokenizer, test_prompts)
#     print(f"{model_name:<30} {result['avg_score']:<10.2f} {result['num_evaluated']:<10}")

成对比较评估

def pairwise_judge(question: str, answer_a: str, answer_b: str) -> dict:
    """成对比较两个模型的回复"""
    # 第一次评判:A在前,B在后
    prompt_ab = JUDGE_PROMPT_PAIRWISE.format(
        question=question, answer_a=answer_a, answer_b=answer_b
    )
    result_ab = client.chat.completions.create(
        model=JUDGE_MODEL,
        messages=[{"role": "user", "content": prompt_ab}],
        temperature=0.0,
        max_tokens=512,
    )

    # 第二次评判:B在前,A在后(缓解位置偏差)
    prompt_ba = JUDGE_PROMPT_PAIRWISE.format(
        question=question, answer_a=answer_b, answer_b=answer_a
    )
    result_ba = client.chat.completions.create(
        model=JUDGE_MODEL,
        messages=[{"role": "user", "content": prompt_ba}],
        temperature=0.0,
        max_tokens=512,
    )

    # 提取判定结果
    verdict_ab = extract_verdict(result_ab.choices[0].message.content)
    verdict_ba = extract_verdict(result_ba.choices[0].message.content)

    # 综合两次结果
    # 如果两次一致 → 高置信度
    # 如果两次不一致 → 标记为 tie
    return {
        "verdict_ab": verdict_ab,
        "verdict_ba": verdict_ba,
        "consistent": is_consistent(verdict_ab, verdict_ba),
    }

位置偏差与缓解

什么是位置偏差

位置偏差(Position Bias)是 LLM-as-Judge 最主要的系统性偏差:

  • 首位偏差(Primacy Bias):评委倾向于选择先出现的回复(~60% 的情况)
  • 近因偏差(Recency Bias):少数模型倾向于选择后出现的回复

偏差测量

# 测量位置偏差的方法
# 对同一对回复,交换位置后重复评判

position_bias_results = []
for question, answer_a, answer_b in test_pairs:
    # A在前
    v1 = judge(question, answer_a, answer_b)  # 假设选了 A

    # B在前
    v2 = judge(question, answer_b, answer_a)  # 如果仍选 A(现在在后面) → 无偏差
                                                # 如果选了 B(现在在前面) → 位置偏差!

    position_bias_results.append({
        "consistent": v1 == flip(v2),  # True = 无偏差
    })

bias_rate = 1 - sum(r["consistent"] for r in position_bias_results) / len(position_bias_results)
print(f"Position bias rate: {bias_rate:.1%}")

缓解策略

策略方法效果
交换位置对每对比较评判两次,取一致结果最有效
多次采样temperature > 0 时多次评判,多数投票较好
提示强调在提示中明确要求"忽略位置"有一定效果
选择好的评委GPT-4、Qwen3-32B 偏差较小基础措施

评委模型选择

可用评委模型

评委模型质量成本速度推荐场景
GPT-4最高论文发表、最终评估
GPT-4o很高日常开发评估
Qwen3-32B本课程推荐
Qwen3-235B-A22B很高重要评估
Claude 3.5 Sonnet很高替代选择

本课程推荐:使用阿里云 Model Studio 的 Qwen3-32B API 作为评委模型。其优势:

  1. 中文理解能力强
  2. API 价格低
  3. 评判质量接近 GPT-4
  4. 与课程使用的 Qwen3 系列一致

评委模型的局限性

即使是最强的评委模型,也存在局限:

  1. 自我偏好(Self-Preference Bias):评委倾向于给风格相似的回复更高分。使用 Qwen3 评判 Qwen3 的回复可能存在偏高分
  2. 长度偏好:评委可能偏好更长的回复,即使短回复更精准
  3. 格式偏好:使用 markdown 格式的回复可能获得更高分
  4. 知识边界:评委模型可能在某些专业领域缺乏判断能力

缓解方法:在最终评估中使用多个不同的评委模型进行交叉验证。


本节小结

概念要点
LLM-as-Judge用强 LLM 评判目标模型回复,平衡成本与质量
MT-Bench80 题 8 类别标准化评估框架
单回复评分绝对评分(1-10),简单直接
成对比较比较两个模型的回复,更符合偏好本质
位置偏差评委倾向选择先出现的回复,需交换位置缓解
评委选择Qwen3-32B(课程推荐)/ GPT-4(研究发表)
中文评估使用中文评判模板,选择中文能力强的评委