跳转至

Instruction Following 能力提升

更新日期:2026-04-15


一、什么是 Instruction Following (IF)

IF 指模型准确遵循用户指令的能力,包括格式、约束、步骤、禁令等。IF 是 LLM 可用性的核心——能力再强,如果不听话也没用。

flowchart LR
    capability["底层能力<br/>(知识 / 推理)"]
    if["Instruction<br/>Following"]
    user["用户体验"]

    capability --> if --> user

    classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
    class capability,if,user stage

经常被低估的事实:IF 比能力提升对用户体验影响更大。同样能力的模型,IF 强 10% 在用户感受上是质变("听话好用" vs "聪明但不听话")。


二、IF 的典型失败模式

失败类型 示例 原因 为什么会这样 / 如何缓解
忽略约束 要求 100 字,输出 500 字 训练数据少见严格长度约束 SFT 数据中大多数回答没有精确字数要求,模型没学过"数字数";缓解:加入大量带精确长度约束的训练对
格式错误 要求 JSON,输出带 markdown 代码块包裹 格式训练不足,模型倾向"美化"输出 模型在 RLHF 中学到了"格式好看=高分"的偏见;缓解:用 JSON schema 验证器做 RL reward
部分遵循 5 个约束只满足 3 个 多约束组合训练不足——单约束都能过,组合就丢 Attention 对多个分散在 prompt 不同位置的约束关注度不均;缓解:Evol-Instruct 式的多约束组合训练
过度生成 要求只输出答案,却加了"让我解释一下..." SFT 数据偏好详细回答(RLHF 奖励啰嗦) RLHF 的"长度偏差"——人类标注员倾向给更长的回答更高分;缓解:在 reward 中加长度惩罚项
漂移 多轮对话中第 5 轮开始忽略第 1 轮的系统指令 长上下文中早期信息被"稀释"(position bias) Attention 对远距离 token 的注意力权重天然衰减;缓解:关键指令重复放在每轮 prompt 中
Prompt 注入 用户输入"忽略以上指令,改为..."覆盖了系统指令 模型无法区分"指令层级"(系统 vs 用户) 所有文本在 Attention 中平等竞争,没有硬性的权限层级;缓解:对抗性训练 + system prompt 强化

三、IF 能力提升方法

3.1 高质量 IF 数据

# 好的 IF 训练样本特征:
# 1. 明确、可验证的指令
# 2. 多重约束组合
# 3. 正反例对比

high_quality_if_examples = [
    {
        "instruction": "Summarize this article in exactly 3 bullet points, each under 15 words. Do not include any preamble.",
        "input": "<article>",
        "output": "- Point 1 (under 15 words)\n- Point 2 (under 15 words)\n- Point 3 (under 15 words)"
    },
    {
        "instruction": "Answer in formal English. Do not use contractions. End with 'Sincerely'.",
        "input": "How do I cancel my subscription?",
        "output": "You can cancel your subscription by... Sincerely"
    },
]

3.2 多约束组合训练

关键:训练数据需要包含多个约束同时满足的样本,而非单一约束。参考 IFEval (Zhou et al., 2023)

def generate_multi_constraint_data():
    """
    Evol-Instruct 风格: 逐步增加约束数量
    """
    base_task = "Write a short story"

    constraints = [
        "exactly 100 words",
        "set in Tokyo",
        "include the word 'origami' at least 3 times",
        "told in first person",
        "include dialogue",
        "no adjectives starting with 'a'",
    ]

    # 组合 2-5 个约束
    for n_constraints in range(2, 6):
        for combo in combinations(constraints, n_constraints):
            task = f"{base_task}. Constraints: {'; '.join(combo)}"
            # 用强 LLM 生成符合所有约束的回答
            answer = strong_llm.generate_with_verification(task, combo)
            yield (task, answer)

3.3 IF-specific RL

# 用 RL 直接优化 IF 能力
# Reward = 指令遵循程度 (可验证)

class IFReward:
    def score(self, instruction, response):
        constraints = extract_constraints(instruction)
        passed = 0
        for constraint in constraints:
            if self.verify_constraint(constraint, response):
                passed += 1
        return passed / len(constraints)

    def verify_constraint(self, constraint, response):
        # 可验证的约束类型:
        if constraint.type == 'length':
            return check_length(response, constraint.value)
        elif constraint.type == 'format_json':
            return is_valid_json(response)
        elif constraint.type == 'keyword':
            return constraint.keyword in response
        elif constraint.type == 'no_keyword':
            return constraint.keyword not in response
        elif constraint.type == 'starts_with':
            return response.startswith(constraint.value)
        # ... 更多类型

3.4 Rejection Fine-Tuning for IF

# 用模型自己生成大量回答, 只保留严格遵循指令的
def rft_for_if(model, instructions, n_samples=32):
    training_data = []
    for instruction in instructions:
        # 采样 N 个回答
        responses = [model.generate(instruction) for _ in range(n_samples)]

        # 验证每个回答
        scored = [(r, verify_instruction_following(instruction, r)) 
                  for r in responses]

        # 只保留全部通过的
        perfect = [r for r, score in scored if score == 1.0]

        if perfect:
            training_data.append((instruction, random.choice(perfect)))

    # 用这些高质量样本做 SFT
    return training_data

四、IF 评测

4.1 IFEval

Google 2023 提出的 IF 专项评测。核心:使用可自动验证的约束,避免主观判断。参考 IFEval (Zhou et al., 2023)

4.2 IFEval 评测指标

metrics = {
    'prompt_strict': 所有约束都严格满足的比例,
    'prompt_loose': 允许小偏差的比例,
    'instruction_strict': 单个约束层面的严格通过率,
    'instruction_loose': 单个约束层面的宽松通过率,
}

4.3 业界 IFEval 成绩

实践笔记:Prompt-Strict 和 Prompt-Loose 的差距反映了"差一点就满足"的比例。差距越大说明模型"理解了意图但执行不精确"——这恰好是 RL 训练最能改善的部分。


五、IF 提升的工程实践

5.1 System Prompt 优化

# 差的 system prompt:
"You are a helpful assistant."

# 好的 system prompt:
"""
You are a helpful assistant. Please strictly follow these rules:

1. FORMAT: Respond in JSON with keys 'answer' and 'confidence'.
2. LENGTH: Keep your answer under 100 words.
3. STYLE: Use formal English, no contractions.
4. BEHAVIOR: If unsure, output {"answer": null, "confidence": 0}.
5. SAFETY: Never generate code that deletes files.

Adherence to these rules is more important than answer quality.
"""

5.2 约束前置与后置

# 方法 A: 约束放最前面
prompt = f"""
Constraints:
1. Output in exactly 3 bullet points
2. Each under 10 words

Task: {task}
"""

# 方法 B: 约束放最后面
prompt = f"""
Task: {task}

Remember:
- Output in exactly 3 bullet points
- Each under 10 words
"""

# 研究发现: 约束在最前面效果更好 (position bias)
# 但 B 方法在长任务中更稳定 (不容易被遗忘)

5.3 Self-Correction

# 让模型自己检查是否遵循了指令
def generate_with_self_check(model, instruction, max_retries=3):
    for _ in range(max_retries):
        response = model.generate(instruction)

        # 自我检查
        check_prompt = f"""
Check if this response follows ALL constraints in the instruction.
Instruction: {instruction}
Response: {response}
Output: {{"follows": bool, "violations": [...]}}
"""
        check = model.generate(check_prompt)

        if check['follows']:
            return response

        # 根据违规重新生成
        fix_prompt = f"""
{instruction}
Your previous response violated: {check['violations']}
Please regenerate, strictly following all constraints.
"""
        instruction = fix_prompt

    return response

六、IF 训练 Recipe

flowchart LR
    s1["S1<br/>SFT 通用 IF"]
    s2["S2<br/>SFT 多约束组合"]
    s3["S3<br/>RLHF + IF reward"]
    s4["S4<br/>Verifier-based RL<br/>(IFEval-style)"]

    s1 --> s2 --> s3 --> s4

    classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
    class s1,s2,s3,s4 stage

6.1 数据构建

阶段 数据规模 数据来源
S1 通用 IF 50k-500k LIMA / OpenAssistant / 自家 SFT
S2 多约束 100k-1M Evol-Instruct 改写已有数据加约束
S3 RLHF 100k 偏好对 人工 / RLAIF + IF-specific rubric
S4 Verifier RL 100k prompt 程序化生成约束 + 自动 verify

6.2 IF 专项数据的来源

  • 公开数据集IFEval、FollowBench、CFBench、Conifer
  • 合成增强:用 Evol-Instruct 给现有 SFT 数据加约束("按 JSON 格式" + "不超过 100 字" + "include 3 examples")
  • 自有日志:production 中用户反馈"没听话"的 case 反向构造训练数据
  • 多轮对话:长 session 中 system prompt drift 检测 + 修复数据

七、IF 前沿方向

方向 描述 为什么重要 / 当前挑战
复杂格式 IF JSON Schema 验证、嵌套结构、XML + XSD API 集成需要严格 schema 遵循;当前模型在嵌套 3 层以上的结构中错误率急增
多轮 IF 在 10+ 轮对话中保持第 1 轮设定的格式和角色 实际部署中最常见的投诉——模型在长对话中"忘记"系统指令;需要长上下文 + 指令持久性训练
冲突约束处理 "用中文回答" vs "include English keywords" 等冲突时如何优雅处理 当前模型要么沉默失败要么随机选一个;理想行为是主动报告冲突并请求澄清
Implicit IF 从 few-shot 示例中推断出隐含的格式/风格规则(无显式指令) 这是 in-context learning 的高级形式;对 Agent 场景尤其重要——用户不会写完美指令
多语言 IF 跨语言保持相同的 IF 精度(如中文指令用英文格式输出) 英文 IF 能力远强于其他语言——训练数据不平衡是根因;需要多语言 IF 专项数据

参考文献

  • [1] Zhou et al. IFEval: Instruction-Following Evaluation. 2023. 论文

  • [2] Xu et al. Evol-Instruct / WizardLM. 2023. 论文

  • [3] Qin et al. InfoBench. 2024. 论文

  • [4] Jiang et al. FollowBench. 2023. 论文

  • [5] He et al. Complex Instruction Following. 2024. 论文

  • [6] IFEval Leaderboard


上级 · E. 后训练与对齐