mcpField
C
constitutional-ai

constitutional-ai

github.com/kalarislabs開発9657 回インストール3 日前に更新
リポジトリ

constitutional-ai について

自己批評とAIフィードバックでモデルを学習させるConstitutional AIのガイドです。人手ラベルを使わず原則に基づく安全性調整を目指すチーム向けに、教師あり修正とRLAIFの手順を扱います。

主な機能

  1. 01自己批評と応答の修正
  2. 02教師あり学習の手順
  3. 03RLAIFによる選好学習
  4. 04憲法原則とプロンプトの指針
  5. 05評価と誠実性の手順

活用シーン

  1. 01応答を安全原則に沿って調整
  2. 02修正応答から学習データを作成
  3. 03AIフィードバックで選好モデルを学習

インストール

コマンドをコピーしてターミナルで実行します。

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

インストール後、Claude Code で/constitutional-aiを入力して読み込まれたか確認します。

詳細

Constitutional AI - AI フィードバックによる無害性

クイックスタート

Constitutional AI(CAI)は、有害な出力に対する人間のラベルを必要とせず、自己批評と AI フィードバックを通じてモデルに無害性を学習させます。

主要な概念:モデルは「憲法」(原則の集合)を使って、自身の応答を批評し、修正することを学びます。

2 つのフェーズ:

  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:Chain-of-thought による批評

推論の透明性を高める:

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:人間の選好(より正確ですが、コストが高い)
  • 自己批評:反復的な改善
  • Chain-of-thought:推論の透明性

代わりに以下を使用してください:

  • 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 の比較:性能比較、コスト分析、AI フィードバックと人間のフィードバックの使い分けについては、references/rlaif-comparison.md を参照してください。

Chain-of-thought 推論:批評のためのプロンプトエンジニアリング、多段階推論、透明性の向上については、references/cot-critique.md を参照してください。

ハードウェア要件

  • GPU:NVIDIA A100/H100 を推奨
  • VRAM:
    • SL フェーズ(7B):A100 40GB × 1
    • RL フェーズ(7B):A100 40GB × 2(ポリシー+報酬モデル)
  • 単一ノード:ほとんどのユースケースで十分
  • 混合精度:BF16 を推奨

計算要件:

  • SL フェーズ:標準的な SFT と同程度
  • RL フェーズ:PPO と同程度(DPO より高い)
  • AI 評価:批評/選好の生成に追加の推論が必要

リソース

エージェントの運用手順

  1. 環境を確認します。 モデル、チェックポイント、ベンチマークのバージョン、評価ハーネスのバージョンを確認します。
  2. 入力を特定します。 データまたはユーザーから、形式、識別子、パラメーターを確認します。結果を左右する値を推測せず、質問してください。
  3. まず小規模に実行します。 小さなサブセットで評価し、プロンプト、解析、スコアリングを検証します。
  4. 上記の手順と参考資料を使用して、タスク全体を実行します。
  5. 結果を検証します。 ベンチマークの公式の分割とメトリクスを使用し、汚染がないか確認して、シードやプロンプトによる分散を報告します。
  6. 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、未解決の点を明記します。
次のことが起きた場合対応
スコアが公開済みの数値と異なる結論を出す前に、プロンプト形式、少数ショットの設定、ハーネスのバージョンを確認します。
この手順に記載された関数、フラグ、エンドポイントが、インストール済みのバージョンに存在しないインストール済みバージョンのドキュメント(help()、--help、公式ドキュメント)を確認して対応し、ユーザーに伝えます。APIを決して捏造しないでください。
必須の入力、識別子、パラメーターが曖昧ユーザーに確認するか、実行前に前提を明示します。

インテグリティに関するルール

  • 結果、パラメーター、識別子、引用、統計を決して捏造しないでください。実行または検証できないことは、率直に伝えます。
  • 評価設定をすべて報告し、プロンプト、シード、サブセットを都合よく選ばないでください。
  • ここに記載されたバージョン固有の情報は古くなっている可能性があるものとして扱い、インストール済みバージョンの公式ドキュメントで確認します。
  • 費用が発生する場合、共有GPUやクラウドのクォータを消費する場合、個人データや患者データを扱う場合、または取り消せない操作を行う場合は、事前に確認してください。

関連スキル

  • fine-tuning-with-trl:TRL を使用した強化学習による LLM のファインチューニング。指示チューニング向けの SFT、選好アライメント向けの DPO、報酬最適化向けの PPO/GRPO…

コメント