31 · verl 与 Agentic RL:从 DataProto 到多轮工具调用
前三节讲的是算法,这一节讲工程骨架:verl 怎么把 Actor、Rollout、Reference、Critic 编排到同一批 GPU 上,
DataProto如何承载变长序列与多轮轨迹,以及 Agentic RL 里「奖励只出现在最后一轮」时该怎么分配优势。前置:28 · GRPO 与 RLOO、30 · 测试时计算与 MCTS。
1. verl 的三层结构
| 层 | 组件 | 职责 |
|---|---|---|
| 编排层 | Ray + RayPPOTrainer | 资源放置、worker 分组、训练循环 |
| 执行层 | WorkerGroup(actor / rollout / ref / critic / reward) | 每类 worker 一组 GPU,支持 colocate 或分离部署 |
| 数据层 | DataProto | 统一 batch 容器:张量字段 + meta_info + 非张量字段 |
最核心的设计是 HybridEngine:训练与推理共用同一份权重显存,rollout 时把 vLLM/SGLang 的 KV cache 权重唤醒、训练时再切回 FSDP/Megatron 分片,避免「两份 70B 权重」把显存吃穿。代价是每次切换要做权重重分片(reshard),因此训练循环通常按「一批 rollout → 多次 mini-batch 更新」组织,把切换摊薄。
import torch
class DataProto:
"""verl 的 batch 容器:张量字段 + meta_info(不参与切分的元数据)"""
def __init__(self, batch, meta_info=None):
self.batch = batch
self.meta_info = meta_info or {}
self.non_tensor = {}
def __len__(self):
return self.batch["input_ids"].shape[0]
def split(self, n):
"""按 batch 维切成 n 份,用于 mini-batch 更新"""
bs = self.batch["input_ids"].shape[0]
size = bs // n
chunks = []
for i in range(n):
sl = slice(i * size, (i + 1) * size)
chunks.append(DataProto({k: v[sl] for k, v in self.batch.items()}, dict(self.meta_info)))
return chunks
def union(self, others):
keys = self.batch.keys()
merged = {k: torch.cat([self.batch[k]] + [o.batch[k] for o in others], 0) for k in keys}
return DataProto(merged, dict(self.meta_info))
bs, seq = 6, 8
input_ids = torch.randint(1, 100, (bs, seq))
attention_mask = torch.ones(bs, seq, dtype=torch.long)
attention_mask[1, 5:] = 0 # 第 1 条只到第 5 个 token
attention_mask[4, 3:] = 0 # 第 4 条只到第 3 个 token
dp = DataProto({"input_ids": input_ids, "attention_mask": attention_mask},
meta_info={"temperature": 0.7, "global_step": 12})
print(f"原始 batch: input_ids {tuple(input_ids.shape)}, 有效 token {attention_mask.sum().item()} / {bs*seq}")
for i, ch in enumerate(dp.split(2)):
print(f" chunk{i}: {tuple(ch.batch['input_ids'].shape)}, 有效 {ch.batch['attention_mask'].sum().item()}, "
f"meta 共享 global_step={ch.meta_info['global_step']}")
c0, c1 = dp.split(2)
back = c0.union([c1])
print(f"切分再合并: {tuple(back.batch['input_ids'].shape)},与原始一致 = {torch.equal(back.batch['input_ids'], input_ids)}")
print("\n要点:meta_info 跟随每个 chunk(温度、步数不能丢),但非张量字段(如多轮 messages)不参与切分。")
2. Sequence Packing:把 padding 换成 cu_seqlens
变长序列若逐条 pad 到最长,短样本的算力就白烧了。Packing 把多条序列首尾相接拼成一条长序列,用累积长度 cu_seqlens 标记边界,配合 varlen attention 只让同一段内的 token 互相看见。
torch.manual_seed(0)
lens = [3, 5, 2]
packed = torch.cat([torch.randint(10, 99, (L,)) for L in lens]) # 多条变长序列首尾相接
cu = torch.tensor([0] + torch.cumsum(torch.tensor(lens), 0).tolist())
print("packed token:", packed.tolist())
print("cu_seqlens:", cu.tolist())
# 由 cu_seqlens 还原每条序列的 position_ids(每条都从 0 重新计)
pos = torch.cat([torch.arange(int(cu[i]), int(cu[i+1])) - cu[i] for i in range(len(lens))])
print("position_ids:", pos.tolist())
# 用 block-diagonal mask 表达「只允许段内互相看见」
n = len(packed)
seg = torch.bucketize(torch.arange(n), cu[1:-1], right=True)
mask = (seg[:, None] == seg[None, :]).long()
print("\n段内可见 mask(1 表示可见):")
for row in mask.tolist():
print(" " + " ".join(map(str, row)))
save = 1 - sum(lens) / (len(lens) * max(lens))
print(f"\npad 到最长需要 {len(lens)*max(lens)} 个位置,packing 只需 {sum(lens)},节省 {save:.0%}")
print("工程代价:attention 必须走 varlen kernel(FA2 的 cu_seqlens 接口),否则 block-diagonal mask 反而更慢。")
3. log-prob 重算与 mismatch:RL 训练最隐蔽的数值坑
Rollout 由推理引擎(vLLM/SGLang,多为 bf16)产生,而训练侧要在训练框架(FSDP/Megatron)里重新前向算一遍 log-prob。两条路径的 kernel、并行切分、精度都不同,同一个 token 的概率会有零点几的偏差;一旦 ratio 偏到 clip 区间外,这条样本的梯度就被截断成 0,等于白采样。
三类常见处理:重算并校验(recompute_log_prob 后统计 |ratio-1| 分布,超阈值样本丢弃)、importance sampling 修正(用 rollout 概率当行为策略)、TIS/截断(对极端 ratio 加权衰减)。
torch.manual_seed(0)
T, V, B = 40, 128, 512
logits = torch.randn(B, T, V)
tok = torch.randint(0, V, (B, T))
lp_fp32 = torch.log_softmax(logits, -1).gather(-1, tok[..., None]).squeeze(-1)
# 模拟推理引擎的 bf16 路径:logits 先降精度,再走一遍 softmax
lp_bf16 = torch.log_softmax(logits.to(torch.bfloat16), -1).float().gather(-1, tok[..., None]).squeeze(-1)
ratio = torch.exp(lp_bf16 - lp_fp32) # 行为策略 / 训练策略
dev = (ratio - 1).abs()
clip_lo, clip_hi = 0.8, 1.2
print(f"ratio 均值 {ratio.mean():.4f},标准差 {ratio.std():.4f}")
print(f"|ratio-1| 分位数: p50={dev.quantile(0.5):.4f} p99={dev.quantile(0.99):.4f} max={dev.max():.4f}")
print(f"落到 clip 区间 [{clip_lo}, {clip_hi}] 之外的 token 比例: "
f"{((ratio < clip_lo) | (ratio > clip_hi)).float().mean():.2%}")
for thr in (0.005, 0.01, 0.02):
print(f" 丢弃阈值 |ratio-1|>{thr:<5}: 丢掉 { (dev > thr).float().mean():.2%} 的 token")
print("\n结论一:bf16 重算本身就会制造 1e-2 量级的 ratio 抖动,因此 mismatch 阈值应放在 1e-2 量级,")
print("要求「完全相等」会把一半以上样本判死。")
# 对照:同一个 batch 内做了几次梯度更新(old policy 已过期),ratio 会明显偏出 clip
drift = 0.35
logits_new = logits + drift * torch.randn_like(logits)
lp_new = torch.log_softmax(logits_new, -1).gather(-1, tok[..., None]).squeeze(-1)
ratio2 = torch.exp(lp_new - lp_fp32)
print(f"\n策略漂移(噪声尺度 {drift})后:|ratio-1| p50={ (ratio2-1).abs().quantile(0.5):.4f} "
f"clip 外比例 {((ratio2 < clip_lo) | (ratio2 > clip_hi)).float().mean():.2%}")
print("前者是「重算误差」,几乎不影响训练;后者是「策略漂移」,会让大量样本梯度被截断——")
print("所以 verl 的 mini-batch 数量要与 rollout 新鲜度匹配,而不是一味加大 epoch。")
4. Agentic RL:多轮轨迹的优势分配
单轮 RL 里一条样本对应一个奖励;Agentic 场景里一条轨迹包含 轮「思考 → 调工具 → 读结果」,奖励往往只在最后出现。做法是把它退化成 MDP 的轨迹回报:
再用 GRPO 的思路把同题多条轨迹的回报做组内标准化。若中途有过程奖励(如工具调用格式正确 +0.2),可以逐轮累加,缓解「终局奖励稀疏」导致前几轮全部零梯度。
gamma = 0.9
turns = ["t1 读文件", "t2 改代码", "t3 跑测试"]
trajs = {
"A": [0.2, 0.0, 1.0], # 格式对、测试通过
"B": [0.0, 0.0, 0.0], # 全程失败
"C": [0.2, 0.2, 1.0], # 格式对 + 中间检查点也给分
}
def discounted(rewards):
G, out = 0.0, []
for r in reversed(rewards):
G = r + gamma * G
out.append(G)
return out[::-1]
G = {k: discounted(v) for k, v in trajs.items()}
print(f"{'轨迹':<6}" + "".join(f"{t + ' G / adv':<22}" for t in turns))
print("-" * 72)
adv = {}
for turn in range(3):
vals = [G[k][turn] for k in trajs]
m = sum(vals) / len(vals)
sd = (sum((v - m) ** 2 for v in vals) / len(vals)) ** 0.5 + 1e-8 # 同一 turn、跨轨迹标准化
adv[turn] = {k: (G[k][turn] - m) / sd for k in trajs}
for k in trajs:
row = f"{k:<6}"
for turn in range(3):
row += f"{G[k][turn]:>7.3f} / {adv[turn][k]:>+6.3f} "
print(row)
print("\n优势在「同一 turn 的多条轨迹之间」做标准化,而不是在一条轨迹内部——")
print("这样 turn1 的优势只由「同题不同轨迹」的相对表现决定,与终局奖励的绝对值解耦。")
5. 一份能跑起来的配置骨架
verl 的训练入口是 Hydra 风格的一组 YAML,关键字段如下(对齐 examples/ppo_trainer 与 recipe/dapo):
| 配置组 | 字段 | 含义 |
|---|---|---|
data | train_files / val_files / max_prompt_length / max_response_length | 数据集与长度上限 |
actor_rollout_ref.model | path / enable_gradient_checkpointing | 基座模型与显存优化 |
actor_rollout_ref.rollout | name: vllm, tensor_parallel_size, gpu_memory_utilization, n | 推理引擎与每题采样数 n(GRPO 的组大小) |
actor_rollout_ref.actor | ppo_mini_batch_size, kl_loss_coef, clip_ratio | 更新粒度与 PPO/KL 超参 |
algorithm | adv_estimator: grpo / gae, gamma, lam | 优势估计器选择 |
trainer | n_gpus_per_node, total_epochs, project_name | 资源与实验管理 |
Agentic 任务在此之上再加一层:rollout.mode: async 配合工具环境(sandbox/浏览器),把「一轮生成」扩展为「多轮 观测-动作」循环,DataProto 里除 input_ids 外还要带 loss_mask(只对模型自己生成的 token 计损失)与每轮的 turn_ids。
config = {
"data": {"train_files": "data/math/train.parquet", "max_prompt_length": 1024,
"max_response_length": 4096, "truncation": "error"},
"actor_rollout_ref": {
"model": {"path": "Qwen2.5-7B-Instruct", "enable_gradient_checkpointing": True},
"rollout": {"name": "vllm", "tensor_parallel_size": 2, "gpu_memory_utilization": 0.6, "n": 8},
"actor": {"ppo_mini_batch_size": 32, "kl_loss_coef": 1e-3, "clip_ratio": 0.2},
},
"algorithm": {"adv_estimator": "grpo", "gamma": 1.0, "lam": 1.0},
"trainer": {"n_gpus_per_node": 8, "total_epochs": 15, "project_name": "mydoc-rl"},
}
def flatten(d, prefix=""):
for k, v in d.items():
key = f"{prefix}.{k}" if prefix else k
if isinstance(v, dict):
yield from flatten(v, key)
else:
yield key, v
print(f"{'配置项':<52} | 值")
print("-" * 74)
for k, v in flatten(config):
print(f"{k:<52} | {v}")
n_prompts, n = 200, 8
tokens = n_prompts * n * (config["data"]["max_prompt_length"] + config["data"]["max_response_length"])
print(f"\n一批 rollout 规模:{n_prompts} 题 × n={n} = {n_prompts*n} 条轨迹,"
f"上限 {tokens/1e6:.1f}M token")
print("按 max_prompt+max_response 估算显存与时间时,这个数字比 batch size 更能反映真实开销。")
6. 框架选型
| 框架 | 并行后端 | 推理引擎 | 擅长 |
|---|---|---|---|
| verl | FSDP / Megatron | vLLM / SGLang / HF | 大规模多机 RL、Agentic 多轮 |
| TRL | Accelerate / DeepSpeed | 原生 generate | 单机小模型、PPO/DPO 快速实验 |
| OpenRLHF | DeepSpeed / vLLM | vLLM | 中等规模、代码简洁 |
| LLaMA-Factory | DeepSpeed | 原生 | SFT/DPO 全家桶、零代码 |
选型只看两条:rollout 占比与是否多轮。rollout 占 70% 以上就必须上 vLLM/SGLang 异步引擎;任务一旦需要工具调用与长轨迹,就只能选支持 loss_mask 与 async rollout 的框架。
站内关联与参考来源
- 前置:28 · GRPO 与 RLOO、30 · 测试时计算与 MCTS
- 延伸:18 · 推理加速、24 · 蒸馏
- 融合参考:
chunhuizhang/llm_rl的infra/verl/{verl_architecture,data_proto,hybrid_engine,sequence_packing,recompute_logprob}.ipynb、llm_aigc/tutorials/agents/{agentic_rl,multi_turn}.ipynb、llms_tuning/{grpo_verl,async_rollout}.ipynb。