我们如何使用 GRPO 训练 Shannon V1.5 进行思考
对群组相对策略优化(GRPO)的全面技术分析,用于在未经审查的 AI 红队模型中实现透明的思维链推理
1. 动机:为何需要思维模型?
对于AI 红队研究,理解如何AI 如何得出潜在有害的输出与研究输出本身同样重要。Shannon V1.5 的思维模型揭示了完整的思维链,使研究人员能够:
- 追踪导致...的推理路径未经审查的 AI 后续行为
- 识别护栏通常会在何处介入(展示AI 护栏的重要性)
- 开发更强大的安全机制,针对特定的推理模式
- 基于观察到的推理链创建更好的对抗性测试用例
研究价值:这种透明度使安全研究人员能够准确地看到放宽约束的模型与经过安全训练的模型在哪里以及为何出现分歧——这对于提高AI guardrail importance的理解。
2. 理解 GRPO
群组相对策略优化 (GRPO)是传统 RLHF 方法的改进,它能够更稳定、高效地训练推理能力。由 DeepSeek AI 开发,它已被证明对思维链训练特别有效。
为何 GRPO 优于传统 RLHF?
| Aspect | 传统 RLHF | GRPO |
|---|---|---|
| 奖励模型 | 需要单独的 RM 训练 | 使用群组相对比较 |
| 训练稳定性 | 易受奖励欺骗 | 更稳定的优化 |
| 计算效率 | 高 (单独的 RM + PPO) | 低 (统一训练) |
| 思维链质量 | 不一致的追踪 | 连贯的推理链 |
GRPO 数学基础
GRPO 通过比较群组内的响应来优化策略,而不是针对绝对奖励模型:
这种相对比较有几个优点:
- 归一化:自动调整不同提示的难度
- 稳定性:减少梯度估计的方差
- 效率:无需单独的奖励模型
def compute_grpo_loss(
policy_logprobs: torch.Tensor,
rewards: torch.Tensor,
group_size: int = 8
) -> torch.Tensor:
"""
Compute GRPO loss with group-relative reward normalization.
Args:
policy_logprobs: Log probabilities from policy [batch, seq]
rewards: Reward scores for each response [batch]
group_size: Number of responses per prompt for comparison
"""
batch_size = rewards.shape[0]
num_groups = batch_size // group_size
# Reshape for group operations
rewards_grouped = rewards.view(num_groups, group_size)
logprobs_grouped = policy_logprobs.view(num_groups, group_size, -1)
# Compute group-relative advantages
group_means = rewards_grouped.mean(dim=1, keepdim=True)
group_stds = rewards_grouped.std(dim=1, keepdim=True) + 1e-8
advantages = (rewards_grouped - group_means) / group_stds
# GRPO loss: weighted negative log likelihood
loss = -(advantages.unsqueeze(-1) * logprobs_grouped).sum(dim=-1).mean()
return loss
3. DeepSeek 蒸馏
为了引导 Shannon V1.5 的思维能力,我们从 DeepSeek 的推理模型中蒸馏了思维链模式。这为训练我们的思维头提供了高质量的思维链追踪。
DeepSeek 数据集构成
轨迹收集过程
我们收集了跨不同领域的思维轨迹,以确保全面的推理覆盖:
class DeepSeekDistiller:
"""Distill chain-of-thought traces from DeepSeek models."""
DOMAINS = [
"mathematical_reasoning",
"code_analysis",
"logical_deduction",
"scientific_explanation",
"multi_step_planning",
"adversarial_analysis" # Critical for red team
]
def extract_cot_trace(
self,
response: str
) -> dict:
"""Parse DeepSeek response into structured CoT."""
# DeepSeek uses ... tags
think_match = re.search(
r'(.*?) ',
response,
re.DOTALL
)
if not think_match:
return None
thinking = think_match.group(1)
final_answer = response.split('')[-1].strip()
# Parse individual reasoning steps
steps = self.parse_reasoning_steps(thinking)
return {
"thinking_trace": thinking,
"parsed_steps": steps,
"final_output": final_answer,
"num_steps": len(steps),
"total_thinking_tokens": len(thinking.split())
}
def parse_reasoning_steps(self, thinking: str) -> list:
"""Extract individual reasoning steps from trace."""
# Split on common step indicators
step_patterns = [
r'\n\d+\.', # "1. ", "2. "
r'\nStep \d+:', # "Step 1:"
r'\n(?:First|Next|Then|Finally),',
r'\n- ' # Bullet points
]
combined_pattern = '|'.join(step_patterns)
steps = re.split(combined_pattern, thinking)
return [s.strip() for s in steps if s.strip()]
对抗性轨迹:我们专门收集了用于对抗性/红队场景的 CoT 轨迹,其中 DeepSeek 的思维揭示了模型如何推理潜在有害请求——即使最终拒绝。这些数据教会 Shannon V1.5 使推理和输出透明。
4. 思维头架构
Shannon V1.5 模型包含一个专用的思维头在最终输出之前生成明确的推理轨迹。这种架构上的增加使得透明的 CoT 成为可能,而无需修改基础 Mixtral 架构。
输入编码
用户提示通过 Mixtral 编码器层处理
思维头激活
专用 Transformer 层使用 [THINK] 令牌生成推理轨迹
轨迹集成
思维输出连接到上下文以进行最终生成
响应生成
基础 Mixtral 根据思维轨迹生成最终响应
思维头实现
class ThinkingHead(nn.Module):
"""
Dedicated thinking module for Shannon V1.5.
Generates explicit chain-of-thought traces.
"""
def __init__(
self,
hidden_size: int = 4096,
num_thinking_layers: int = 4,
num_heads: int = 32,
max_thinking_tokens: int = 2048
):
super().__init__()
self.hidden_size = hidden_size
self.max_thinking_tokens = max_thinking_tokens
# Special tokens
self.think_start = nn.Parameter(torch.randn(1, 1, hidden_size))
self.think_end = nn.Parameter(torch.randn(1, 1, hidden_size))
# Thinking transformer layers
self.thinking_layers = nn.ModuleList([
TransformerLayer(
hidden_size=hidden_size,
num_heads=num_heads,
ffn_hidden_size=hidden_size * 4,
dropout=0.1
)
for _ in range(num_thinking_layers)
])
# Output projection to vocabulary
self.output_proj = nn.Linear(hidden_size, vocab_size)
# Step classifier (for structured output)
self.step_classifier = nn.Linear(hidden_size, 5) # 5 step types
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
generate_steps: bool = True
) -> dict:
"""
Generate thinking trace from input hidden states.
Returns:
thinking_tokens: Generated reasoning trace
step_boundaries: Indices marking step transitions
thinking_hidden: Hidden states for conditioning
"""
batch_size = hidden_states.shape[0]
# Prepend thinking start token
thinking_input = torch.cat([
self.think_start.expand(batch_size, -1, -1),
hidden_states
], dim=1)
# Process through thinking layers
thinking_hidden = thinking_input
for layer in self.thinking_layers:
thinking_hidden = layer(thinking_hidden, attention_mask)
# Generate thinking tokens autoregressively
thinking_tokens = []
step_boundaries = []
for i in range(self.max_thinking_tokens):
logits = self.output_proj(thinking_hidden[:, -1, :])
next_token = logits.argmax(dim=-1)
# Check for step boundaries
step_type = self.step_classifier(thinking_hidden[:, -1, :])
if step_type.argmax(dim=-1) != 0: # 0 = continue
step_boundaries.append(i)
thinking_tokens.append(next_token)
# Check for think_end
if next_token == self.think_end_token_id:
break
# Update for next iteration
# ... (autoregressive generation logic)
return {
"thinking_tokens": torch.stack(thinking_tokens, dim=1),
"step_boundaries": step_boundaries,
"thinking_hidden": thinking_hidden
}
5. 训练流程
阶段 1:思维头预训练
首先,我们使用标准交叉熵损失在 DeepSeek 蒸馏的 CoT 轨迹上预训练思维头:
# Thinking Head Pre-training Configuration
model:
base: shannon-ai/v1-deep # Start from GPT-5 distilled model
thinking_head:
num_layers: 4
hidden_size: 4096
max_tokens: 2048
training:
stage: thinking_pretrain
epochs: 5
batch_size: 64
learning_rate: 1e-4
freeze_base: true # Only train thinking head initially
data:
train_path: /data/deepseek_cot_train.jsonl
format: thinking_trace
fields:
input: prompt
thinking: thinking_trace
output: final_answer
阶段 2:GRPO 微调
预训练后,我们应用 GRPO 通过组相对比较来提高思维质量:
class GRPOTrainer:
"""GRPO trainer for thinking model optimization."""
def __init__(
self,
model: ThinkingModel,
group_size: int = 8,
kl_coef: float = 0.1
):
self.model = model
self.group_size = group_size
self.kl_coef = kl_coef
self.ref_model = copy.deepcopy(model)
self.ref_model.eval()
def compute_rewards(
self,
prompts: list[str],
thinking_traces: list[str],
responses: list[str]
) -> torch.Tensor:
"""
Compute rewards for thinking quality.
Multiple signals combined for comprehensive evaluation.
"""
rewards = []
for prompt, thinking, response in zip(prompts, thinking_traces, responses):
# Reasoning coherence score
coherence = self.evaluate_coherence(thinking)
# Step structure quality
structure = self.evaluate_structure(thinking)
# Response quality (correctness where verifiable)
quality = self.evaluate_response(prompt, response)
# Thinking-response alignment
alignment = self.evaluate_alignment(thinking, response)
# Combined reward
reward = (
0.3 * coherence +
0.2 * structure +
0.3 * quality +
0.2 * alignment
)
rewards.append(reward)
return torch.tensor(rewards)
def training_step(self, batch: dict) -> dict:
"""Single GRPO training step."""
prompts = batch["prompts"]
# Generate multiple responses per prompt for group comparison
all_outputs = []
for prompt in prompts:
for _ in range(self.group_size):
output = self.model.generate_with_thinking(
prompt,
temperature=0.8, # Diversity for comparison
do_sample=True
)
all_outputs.append(output)
# Compute rewards
rewards = self.compute_rewards(
prompts=[p for p in prompts for _ in range(self.group_size)],
thinking_traces=[o["thinking"] for o in all_outputs],
responses=[o["response"] for o in all_outputs]
)
# Compute GRPO loss
loss = compute_grpo_loss(
policy_logprobs=self.get_logprobs(all_outputs),
rewards=rewards,
group_size=self.group_size
)
# Add KL penalty against reference model
kl_div = self.compute_kl_divergence(all_outputs)
total_loss = loss + self.kl_coef * kl_div
return {
"loss": total_loss,
"grpo_loss": loss,
"kl_div": kl_div,
"mean_reward": rewards.mean()
}
阶段 3:红队专业化
最后,我们进一步针对对抗性场景进行调整,以确保思维轨迹正确揭示了以下方面的推理:未审查 AI 的后续分析:
对 AI 安全研究至关重要:此阶段专门训练模型在处理潜在有害请求时将其推理口头化——这正是AI 护栏重要性研究所需的透明度。
6. 结果与分析
思维质量指标
| 指标 | V1(无思维) | V1.5 平衡 | V1.5 深度 |
|---|---|---|---|
| CoT 连贯性 | N/A | 87.3% | 92.1% |
| 步骤结构 | N/A | 84.6% | 89.4% |
| 推理准确性 | 76.2% | 82.8% | 88.5% |
| 透明度分数 | 12% | 94.2% | 97.8% |
| 红队轨迹质量 | N/A | 91.5% | 96.3% |
主要发现
- 透明度显著提高:从 12% 到 97.8% 的推理现在被明确地口头化
- 推理准确性提高:明确的思维将最终答案质量提高了 12+ 分
- 红队价值得到证实:安全研究人员报告称,思维轨迹对于理解漏洞利用推理“无价”
- GRPO 优于 RLHF:与传统方法相比,连贯性分数提高了 15%
对 AI 安全研究的影响:Shannon V1.5 的透明思维使研究人员能够通过分析推理轨迹识别出 47 种新颖的攻击模式——这些模式在标准黑盒模型中是不可见的。这直接促进了对AI 护栏重要性.