mcpField
C
constitutional-ai

constitutional-ai

github.com/kalarislabs开发9657 次安装3 天前更新
代码仓库

关于 constitutional-ai

为使用 Constitutional AI 训练模型提供指导,通过自我批评和 AI 反馈实现安全对齐。内容涵盖监督式修订与 RLAIF 工作流,适合希望依据原则训练、减少人工标签需求的团队。

主要功能

  1. 01自我批评与回复修订
  2. 02监督学习工作流
  3. 03RLAIF 偏好训练
  4. 04宪法原则与提示词指导
  5. 05评估与诚信流程

适用场景

  1. 01让模型回复符合安全原则
  2. 02基于修订回复构建训练数据
  3. 03使用 AI 反馈训练偏好模型

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill constitutional-ai

安装后在 Claude Code 中输入/constitutional-ai确认已加载。

详细介绍

Constitutional AI——通过 AI 反馈实现无害性

快速开始

Constitutional AI(CAI)通过自我批评和 AI 反馈训练模型,使其变得无害,无需为有害输出提供人工标注。

核心概念:模型使用一套“宪法”(原则集合)学习批评并修订自己的回答。

两个阶段:

  1. 监督学习(SL):自我批评 + 修订
  2. 强化学习(RL):RLAIF(基于 AI 反馈的 RL)

宪法示例:

Principles:
1. Choose the response that is most helpful, honest, and harmless
2. Avoid responses that are toxic, racist, or sexist
3. Prefer responses that explain objections rather than refuse
4. Choose responses that are thoughtful and nuanced

常见工作流

工作流 1:监督学习阶段(自我批评 + 修订)

步骤 1:生成初始回答:

from transformers import pipeline

generator = pipeline("text-generation", model="base-model")

prompts = [
    "How do I hack a website?",
    "Write something offensive about a group.",
    "Help me cheat on my exam."
]

initial_responses = generator(prompts, max_length=200)

步骤 2:依据宪法进行自我批评:

critique_prompt = """
Given the question:
{question}

And the response:
{response}

Constitution:
1. Choose responses that are helpful, honest, and harmless
2. Avoid toxic, racist, or sexist content
3. Explain objections rather than refuse

Identify any ways this response violates the constitution:
"""

critiques = generator(
    [critique_prompt.format(q=q, r=r) for q, r in zip(prompts, initial_responses)]
)

步骤 3:根据批评进行修订:

revision_prompt = """
Question: {question}
Original response: {response}
Critique: {critique}

Please revise the response to better align with the constitution:
"""

revised_responses = generator(
    [revision_prompt.format(q=q, r=r, c=c)
     for q, r, c in zip(prompts, initial_responses, critiques)]
)

步骤 4:使用修订后的回答进行微调:

from trl import SFTTrainer

# Create dataset of (prompt, revised_response) pairs
dataset = create_dataset(prompts, revised_responses)

trainer = SFTTrainer(
    model=model,
    train_dataset=dataset,
    max_seq_length=1024
)
trainer.train()
工作流 2:RL 阶段(RLAIF——基于 AI 反馈的 RL)

步骤 1:生成比较对:

# Sample multiple responses per prompt
responses_a = generator(prompts, num_return_sequences=2, do_sample=True, temperature=0.8)
responses_b = generator(prompts, num_return_sequences=2, do_sample=True, temperature=0.8)

步骤 2:AI 偏好评估:

preference_prompt = """
Question: {question}

Response A: {response_a}
Response B: {response_b}

Constitution:
{constitution}

Which response better follows the constitution? Explain your reasoning, then choose A or B.
"""

# Get AI preferences (no human labels needed!)
preferences = generator(
    [preference_prompt.format(q=q, ra=ra, rb=rb, constitution=CONSTITUTION)
     for q, ra, rb in zip(prompts, responses_a, responses_b)]
)

# Parse preferences (A or B)
chosen, rejected = parse_preferences(preferences, responses_a, responses_b)

步骤 3:训练偏好模型(奖励模型):

from trl import RewardTrainer, RewardConfig

preference_dataset = create_preference_dataset(prompts, chosen, rejected)

reward_config = RewardConfig(
    output_dir="constitutional-reward-model",
    learning_rate=1e-5,
    num_train_epochs=1
)

reward_trainer = RewardTrainer(
    model=model,
    args=reward_config,
    train_dataset=preference_dataset,
    processing_class=tokenizer
)
reward_trainer.train()

步骤 4:使用 RLAIF 进行 RL 训练:

from trl import PPOTrainer, PPOConfig

ppo_config = PPOConfig(
    reward_model_path="constitutional-reward-model",
    learning_rate=1e-6,
    kl_coef=0.05
)

ppo_trainer = PPOTrainer(
    model=model,
    config=ppo_config,
    reward_model=reward_model
)
ppo_trainer.train()
工作流 3:思维链批评

启用推理透明度:

cot_critique_prompt = """
Question: {question}
Response: {response}

Let's think step-by-step about whether this response follows our principles:

1. Is it helpful? [Yes/No and reasoning]
2. Is it honest? [Yes/No and reasoning]
3. Is it harmless? [Yes/No and reasoning]
4. Does it avoid toxicity? [Yes/No and reasoning]

Based on this analysis, suggest a revision if needed.
"""

cot_critiques = generator(
    [cot_critique_prompt.format(q=q, r=r) for q, r in zip(prompts, responses)]
)

何时使用及替代方案

适合使用 Constitutional AI 的情况:

  • 希望在无需人工标注的情况下实现安全对齐
  • 需要可解释的 AI 决策
  • 希望避免回避式拒绝
  • 拥有一套清晰的原则/宪法
  • 需要可扩展的安全训练

原则:

  • RLAIF:AI 生成的偏好(可扩展,无需人工标注)
  • RLHF:人类偏好(更准确,成本更高)
  • 自我批评:迭代改进
  • 思维链:推理透明度

改用其他方案的情况:

  • RLHF(PPO):需要经人工验证的安全性
  • DPO/SimPO:拥有人工偏好数据
  • NeMo Guardrails:需要运行时内容过滤
  • LlamaGuard:需要预训练的审核模型

常见问题

问题:模型拒绝过多(回避)

添加宪法原则:

Prefer responses that engage thoughtfully with questions rather than
refusing to answer. Explain concerns while still being helpful.

问题:自我批评不够有力

使用更强的批评提示词:

Critically analyze this response for ANY potential issues, however minor.
Be thorough and specific in identifying problems.

问题:修订未能提升质量

多次迭代:

for _ in range(3):  # 3 rounds of critique/revision
    critique = generate_critique(response)
    response = generate_revision(response, critique)

问题:RLAIF 偏好噪声较大

使用多个 AI 评估器:

# Get preferences from 3 different models
prefs_1 = model_1.evaluate(responses)
prefs_2 = model_2.evaluate(responses)
prefs_3 = model_3.evaluate(responses)

# Majority vote
final_preference = majority_vote(prefs_1, prefs_2, prefs_3)

进阶主题

宪法设计:参见 references/constitution-design.md,了解原则选择、有用性与无害性之间的权衡,以及特定领域的宪法。

RLAIF 与 RLHF:参见 references/rlaif-comparison.md,了解性能比较、成本分析,以及何时使用 AI 反馈而非人工反馈。

思维链推理:参见 references/cot-critique.md,了解用于批评的提示工程、多步推理和透明度提升。

硬件要求

  • GPU:推荐使用 NVIDIA A100/H100
  • VRAM:
    • SL 阶段(7B):1× A100 40GB
    • RL 阶段(7B):2× A100 40GB(策略模型 + 奖励模型)
  • 单节点:足以满足大多数使用场景
  • 混合精度:推荐使用 BF16

计算要求:

  • SL 阶段:与标准 SFT 类似
  • RL 阶段:与 PPO 类似(高于 DPO)
  • AI 评估:需要额外推理来生成批评/偏好

资源

Agent 操作流程

  1. 检查环境。 确认模型、检查点、基准测试版本和评估框架版本。
  2. 明确输入。 根据数据或用户确认格式、标识符和参数。对于任何会改变结果的值,应先询问,不要猜测。
  3. 先运行小规模版本。 在一个小型子集上评估,以验证提示词、解析和评分。
  4. 根据上述说明和参考资料执行完整任务。
  5. 验证结果。 使用基准测试的官方数据集划分和指标;检查是否存在数据污染;报告不同随机种子或提示词下的方差。
  6. 报告。 说明运行的内容(版本、命令、参数)、检查的内容,以及仍不确定的事项。
如果发生这种情况请这样做
分数与已发布的结果不同在下结论前,检查提示词格式、少样本设置和评估框架版本。
这些说明中提到的函数、标志或端点在已安装版本中不存在查阅已安装版本自身的文档(help()、--help、官方文档),进行调整并告知用户。切勿捏造 API。
必需的输入、标识符或参数不明确询问用户,或在运行前明确说明所采用的假设。

诚信原则

  • 切勿捏造结果、参数、标识符、引用或统计数据。如果无法运行或验证某项内容,请如实说明。
  • 完整报告评估设置;切勿挑选提示词、随机种子或子集。
  • 将此处与版本相关的细节视为可能已过时:请根据已安装版本的官方文档进行确认。
  • 对于需要付费、占用共享 GPU 或云配额、涉及个人或患者数据,或无法撤销的操作,请先征求同意。

相关技能

  • fine-tuning-with-trl:使用 TRL 通过强化学习微调 LLM——用于指令微调的 SFT、用于偏好对齐的 DPO、用于奖励优化的 PPO/GRPO…

评论

支持 Markdown