异步参数
fully async
训推节点和副本数
节点
- trainer.nnodes:训练节点
- rollout.nnodes:推理节点
llm 推理副本数
推理 GPU:4 节点 × 8 卡 =
32 卡每个副本:rollout_tp = 2, (pp=dp=1),
占 2 卡推理副本数:
32 ÷ 2 = 16个 SGLang 副本
BatchSize 和 required_samples 样本数
Batch 和 required_samples 样本
ppo_mini_batch_size:ppo一次更新参数所需的bs,后续会乘以rollout.nrequire_batches:一次训练需要的batch数required_samples:一次训练需要的sample数,require_batches*ppo_mini_bs- 这里的samples,
是group的概念,后续才乘以rollout_n - fully_async 参数源代码笔记
- 这里的samples,
样本陈旧度
staleness_threshold:样本陈旧度,采样端领先训练端,1 + staleness
最大需要样本数
max_required_samples:required_samples* (1 + staleness) * trigger_sync_step- max_queue_size:结果队列容量 大小同 max_required_samples,已完成等待trainer消费
权重同步
- trigger_parameter_sync_step:trainer执行几轮后,向推理端同步 1 次更新权重。
rollout 并发度
llm 并发
concurrent_samples_per_replica:每个llm副本的最大group并发,默认为16- sample 为
group-level,实际轨迹需要 乘以 rollout_n
- sample 为
轨迹并发
max_concurrent_samples:min(llm 副本数 * 单副本并发数,max_required_samples)- total_train_steps:total_rollout_steps / (required_samples * trigger_sync_step)
3个samples参数对比
| 参数 | 含义 |
|---|---|
required_samples=128 | Trainer 每次取 128 组数据进行训练 |
max_concurrent_samples=256 | Rollout 同时最多执行 256 组任务 |
max_required_samples=384 | 限制 Rollout 提前生产的数据额度,防止旧策略数据过多 |
1. max_concurrent_samples 控制同时执行任务数
# 1. 初始化
正在执行 256 组
新任务 等待
# 2. 完成1组,进来做1组
完成 1 组
↓
正在执行变成 255 组
↓
启动新的一组
↓
正在执行恢复到 256 组2. max_reuired_samples 控制提前生产多少数据
- rollouter 可能很快,不能生产太多旧policy 数据。
- 陈旧度为2,128 -> 384组,最多生成 3个 batch的数量,Policy Lag=2
# step1,启动256组
正在执行 256 组
已完成 0 组
已使用生产额度 256 组
剩余生产额度 128 组
# step2,陆续完成128组,再补进128组
正在执行 256 组
累计完成 128 组
已使用生产额度 384 组
剩余生产额度 0 组
# step3,暂停启动新任务,直到 trainer 消费一批数据,此时rollouter可能等待
正在执行的任务继续完成
↓
运行中的任务越来越少
↓
等待权重更新、重新核算生产额度
# step4,新权重到来,恢复额度,reset_staleness
staleness_samples = 正在执行的组数 + 结果队列中等待消费的组数
正在执行 100 组
结果队列等待消费 156 组
重新核算后的占用 256 组
生产额度上限 384 组
可继续启动 128 组 简单样例
rollout_tp=2,4节点、8卡的推理配置,共32/2=16个 llm 副本,单副本并发系数 16
mini_bs=256,n=8,staleness=2,require_batches=1,同步间隔=1
| 控制项 | 采样samples (group级别) | 折算轨迹 (乘 rollout_n) |
|---|---|---|
| 每轮训练取样量 required_samples | 256 × 1 = 256 | 256 × 8 = 2048 |
| 采样任务预算上限 max_required_samples | 256 × 1 × (1+2) × 1 = 768 | 768 × 8 = 6144 |
| 采样任务并发上限 max_concurrent_samples | min(16个副本 × 并发16, 768) = 256 | 256 × 8 = 2048 |
| 已完成样本的队列容量 max_queue_size | 采样任务预算上限 = 768 | 768 × 8 = 6144 |
mini_bs=1024,n=1,staleness=2,require_batches=1,同步间隔=1
| 控制项 | 采样samples (group级别) | 折算轨迹 (乘 rollout_n) |
|---|---|---|
| 每轮训练取样量 required_samples | 1024 × 1 = 1024 | 1024 × 1 = 1024 |
采样任务预算上限max_required_samples | 1024 × 1 × (1+2) × 1 = 3072 | 3072 × 1 = 3072 |
采样任务并发上限max_concurrent_samples | min(16个副本 × 系数16, 3072) = 256 | 256 × 1 = 256 |
已完成样本的队列容量max_queue_size | 采样任务预算上限 = 3072 | 3072 × 1 = 3072 |
复杂样例
配置
| 名称 | 配置 |
|---|---|
| 训练资源 | 8 台 × 8 卡 = 64 卡 |
| Rollout 资源 | 4 台 × 8 卡 = 32 卡 |
| ppo_mini_batch_size / require_batches | 128 / 1 = 128个prompt |
| 每题采样数 | 16 条轨迹 |
| 每次更新的数据量 | 2048 条轨迹 |
| staleness | 2 |
| trigger_parameter_sync_step | 1 |
| Rollout 并行 | TP=2,PP=1,推理引擎内 DP=1 |
| Rollout LLM 副本并发 | concurrent_samples_per_replica=16 |
| Actor 并行 | TP=2,PP=2,CP=4,EP=4,ETP=1 |
| ppo_micro_batch_size | 1 |
| PPO epochs | 1 |
| 算法 | GRPO |
rollout 侧
llm 副本
- rollout,4节点,32卡,每个副本TP=2,一共 32/2=
16个副本
轨迹数量
required_samples=1 * 128=128组= 128 * 16 =2048 轨迹max_required_samples= required_samples * (1 + staleness) * sync_step =- 128 * (1+2) * 1 =
384组=6144 轨迹
- 128 * (1+2) * 1 =
- 2048轨迹,16个副本,
每个副本处理 2048/16=128 轨迹
rollout 并发
max_concurrent_samples:min(llm 副本数 * 单副本并发数,max_required_samples)- min (16*16, 384) =
256 组=4096 轨迹
- min (16*16, 384) =
- 最多
256组同时执行,此处可能受到环境的限制,即初始化环境需要等待。
| 参数 | 含义 |
|---|---|
required_samples=128 | Trainer 每次取 128 组数据进行训练 |
max_concurrent_samples=256 | Rollout 同时最多执行 256 组任务 |
max_required_samples=384 | 限制 Rollout 提前生产的数据额度,防止旧策略数据过多 |
训练侧
核心配置推算
train,8节点,64卡,tp=2, pp=2, cp=4,计算出 DP=4
2048条轨迹,有
4路数据并行,每路分到2048 / 4=512条轨迹micro_batch_size=1梯度累计,每路需要处理 512个 micro_batch这
512个 micro_batch梯度累计完成后,完成1次 optimizer 更新。
总结
64 训练卡,实际4 路数据并行,每路累积512 个 micro-batch 梯度归约4路梯度后,基于全部2048轨迹,完成一次全局参数更新。
Train 时间估计及监测指标
token 数量
- 轨迹数量:128 * 16 =
2048 - 平均prompt长度:1500;平均response长度:35000
- Batch 有效输入token:
2048 * (1500+35000)=7480万。 - 去除环境token,
参与 policy loss的有效token:2600万。
1. 等待 Rollout 数据:206秒,约3.5分钟;同步可能长达1小时。
- timing_s/
gen:取数据的时间 - fully_async/
trainer/idle_ratio - fully_async/
rollouter/idle_ratio
2. Actor 重算 old_log_probs:320秒,5.4分钟
- timing_s/old_log_prob
3. Refence 前向 计算ref_log_probs;273秒,约4.7分钟
- timing_s/ref 283秒,
4. 计算 reward/advantage:6秒
- 计算reward:在rollout里面计算过了。
- timing_s/
adv6秒钟
5. Actor 前向 反向 更新参数:928秒,15.4 分钟
timing_s/update_actor 1021, 17分钟
micro_batch 估算 batch 时间
每路512个micro_batch,粗算Actor时间,PP=2,分前后2步,因此用pp平均完成间隔
若观察:
平均micro_batch时间=1.81秒,则总计需要20分钟左右。
6. 同步权重到 rollouter:28秒
- timing_s/timing_s/param_sync
7. 其他开销(落盘):rollout落盘 23秒,存checkpoint 5分钟 (10个step存一次)
- timing_s/dump_rollout_generations 23秒
- timing_s/save_checkpoint 328秒,
5分钟,分摊到step=328/10=32秒
8. 整体一个step的时间:33分钟
- timing_s/step 1988s
| 阶段 | 平均实际耗时 |
|---|---|
| 等待、取得队列中的训练数据 | 206.8 秒,约 3.45 分钟 |
Actor 重算 old_log_probs | 320.5 秒,约 5.34 分钟 |
Reference 前向,计算 ref_log_prob | 273.4 秒,约 4.56 分钟 |
优势估计 advantage | 6.6 秒 |
| Actor 前向、反向及更新 | 925.8 秒,约 15.43 分钟 |
| 权重同步 | 28.0 秒 |
| Rollout 数据导出及其他开销 | 约 23.0 秒 |
| 本步合计 | 1784.1 秒,约 29.73 分钟 |
Rollout 轨迹时间估计
单条轨迹耗时
单轨迹耗时
一个group为1个sample,一组数据受限于组内的长尾轨迹。
1. 启动环境
- 整体时间:
mean 12分钟,p50 7分钟,p95 46分钟- swe6traintime/rollout_env_init_s_mean, _p95
排队开销:mean 12.4分钟,p50 7.19分钟,p95 46分钟- 设置 1台机器,最大100个容器。
环境启动:mean 3.25秒,p50 0.62秒,p95 14.73秒
2. LLM 生成
- LLM:p50
13.7分钟,mean17分钟,p9540.5分钟。 - swe6traintime/llm_s_mean,_p95
3. 环境工具执行
- 工具执行:p50
42 秒,mean108秒 / 1.8分钟,p95420秒 / 7分钟, 单action平均在 1.8秒左右- swe6traintime/env_step_s_mean,_p95
4. 评估(启动环境+跑测试)
- 整体评估:p50
0.4分钟 / 24秒, mean5.4 分钟 / 324秒, p9522分钟 / 1320秒 - 启动环境:p50
2.48 秒, mean4.5 分钟 / 271, p9521分钟 / 1278秒- swe6traintime/rollout_env_init_s_mean,_p95
- 跑测试:p50
10 秒, mean53秒 / 1分钟, p954分钟 / 1370秒- swe6traintime/eval_s_mean,_p95
5. 单条轨迹总耗时
- 单条轨迹:p50
28分钟,mean35分钟,p9580分钟 - swe6traintime/traj_s_mean,_p95
| 阶段 | 主要内容 | 平均耗时 | 平均占比 | P50 | P95 |
|---|---|---|---|---|---|
| 1. 环境初始化 | CPU 资源排队 | 12.4 分 | 34.5% | 7.2 分钟 | 46.23 分 |
| 1. 环境初始化 | 启动容器、初始化设置 | 3.3 秒 | 0.15% | 0.62 秒 | 14.73 秒 |
| 2. LLM 请求 | 排队、Prefill、Decode等 | 17 分钟 | 47.3% | 13.7 分钟 | 40.51 分 |
| 3. 工具执行 | 多轮 bash 执行 | 1.8 分 | 5.0% | 40.3 秒 | 7.13 分 |
| 4. 最终评测 | 环境初始化、执行评测 | 4.8 分钟 | 13.1% | 20.9 秒 | 21.03 分 |
| 其他开销 | - | 2.7 秒 | 0.12% | 1.4 秒 | 7.7 秒 |
| 整条轨迹 | - | 36 分 | 100% | 28 分 | 80 分钟 |
单步及Epoch时间
步数
- 假设 6000数据,bs=128,step=6000/128=46步。
- 假设 rollout 一批 需要
40分钟,训练需要32分钟。
同步共卡方案
2阶段
串行:比如 40+32=72分钟46*72=3312分钟=
55小时=2天7小时
异步分离方案
两阶段
充分重叠:比如 max(40,32)=40分钟,也就是训练32分钟,等数据8分钟,就是40分钟46*40=1840分钟=
30小时=1天6小时
参数理解
每回合生成最大token数
参考文章
最大模型长度 (Yarn配置见下文)
- rollout.
max_model_len= rollout.prompt_length+ rollout.response_length - 由rollout的
prompt+response长度决定
最大解码token数
- 以下2者
取小值- 最大回复长度配置:
rollout.response_length - 当前Prompt可用长度:
max_model_len-len(prompt_ids)- 1,
- 最大回复长度配置:
@ray.remote(num_cpus=1)
class SGLangHttpServer:
def __init__(
self,
config: RolloutConfig,
model_config: HFModelConfig,
rollout_mode: RolloutMode,
workers: list[ActorHandle],
replica_rank: int,
node_rank: int,
nnodes: int,
cuda_visible_devices: str,
):
print(f"SGLang http server: {rollout_mode=}, {replica_rank=}, {node_rank=}, {nnodes=}, {cuda_visible_devices=}")
os.environ["CUDA_VISIBLE_DEVICES"] = cuda_visible_devices
assert torch.cuda.is_available(), "SGLang http server should run on GPU node"
self.config: RolloutConfig = omega_conf_to_dataclass(config)
self.model_config: HFModelConfig = omega_conf_to_dataclass(model_config, dataclass_type=HFModelConfig)
self.config.max_model_len = self.config.prompt_length + self.config.response_length
self.rollout_mode = rollout_mode
self.workers = workers
self.replica_rank = replica_rank
self.node_rank = node_rank
self.nnodes = nnodes
# ....
async def generate(
self,
prompt_ids: torch.Tensor,
sampling_params: dict[str, Any],
request_id: str,
image_data: Optional[list[Any]] = None,
) -> TokenOutput:
"""Generate sequence with token-in-token-out."""
max_new_tokens = min(self.config.response_length, self.config.max_model_len - len(prompt_ids) - 1)
sampling_params["max_new_tokens"] = max_new_tokens
return_logprob = sampling_params.pop("logprobs", False)
request = GenerateReqInput(
rid=request_id,
input_ids=prompt_ids,
sampling_params=sampling_params,
return_logprob=return_logprob,
image_data=image_data,
)
output = await self.tokenizer_manager.generate_request(request, None).__anext__()
if return_logprob:
output_token_logprobs = output["meta_info"]["output_token_logprobs"]
log_probs, token_ids = zip(
*[(log_prob, token_ids) for log_prob, token_ids, _ in output_token_logprobs], strict=True
)
else:
token_ids = output["output_ids"]
log_probs = None
return TokenOutput(token_ids=token_ids, log_probs=log_probs)batch_size相关
简单总结
- data.train_batch_size
- 训练batch大小,
乘以rollout.n,得到real_train_batch_size
- 训练batch大小,
- actor.ppo_mini_batch_size
更新模型时,对real_train_batch划分为多个mini_batch1个real_train_batch更新多次;1个mini_batch更新1次
- actor.ppo_micro_batch_size_per_gpu
更新模型时,对mini_batch划分为多个micro_batch,依次计算,梯度累积- micro_batch_size=ppo_micro_batch_size_per_gpu
- rollout.log_prob_micro_batch_size_per_gpu
计算old_log_prob时,对real_train_batch划分为多个micro_batch,依次计算
- ref.log_prob_micro_batch_size_per_gpu
计算ref_log_prob时,对real_train_batch划分为多个micro_batch,依次计算
data.train_batch_size
含义
train_batch_size:训练集batch大小,用于数据迭代加载训练- val_batch_size:同理, 不再赘述
关键点
与rollout.n结合,构建出real_train_batch_size- real_train_batch_size = train_batch_size * rollout.n
参考笔记
加载训练数据,以train_batch_size遍历
self.train_dataloader = StatefulDataLoader(
dataset=self.train_dataset,
batch_size=self.config.data.get("gen_batch_size", self.config.data.train_batch_size),
num_workers=num_workers,
drop_last=True,
collate_fn=collate_fn,
sampler=train_sampler,
)后续所有rollout、update等,都是基于batch
for epoch in range(current_epoch, self.config.trainer.total_epochs):
for batch_dict in self.train_dataloader:
# ...
# ...
gen_batch = self._get_gen_batch(batch)
# pass global_steps to trace
gen_batch.meta_info["global_steps"] = self.global_steps
gen_batch_output = gen_batch.repeat(
repeat_times=self.config.actor_rollout_ref.rollout.n, interleave=True
)
# 其他操作...
# ....actor.ppo_mini_batch_size
前处理
- MegatronActorRolloutRefWorker 构造函数里
先自动放大n倍,再除以DP_world_size- 即:对
actor.ppo_mini_batch_size乘以rollout.n - 再:除以get_data_parallel_world_size()
DP=N_GPUS// (MP * CP) =N_GPUS// (TP*PP*CP)
- 即:对
含义
- update actor(或critic)时:对
real_train_batch进行划分 - 划分为
多个mini_batch- 大小为
ppo_mini_batch_size - 即
real_train_batch_size-> 多个ppo_mini_batch_size
- 大小为
- 每个mini_batch:
更新1次模型- 通常与
ppo_epochs结合使用,即rollout数据训练几次,重复使用几次。 - 在
1个real_train_batch内,分批次更新多次模型
- 通常与
Critic同理
- 参数为
critic.ppo_mini_batch_size
参考笔记
ActorRolloutRefWorker.update_actor,update_actor 主入口笔记
@register(dispatch_mode=make_nd_compute_dataproto_dispatch_fn(mesh_name="actor"))
@GPUMemoryLogger(role="update_actor", logger=logger)
@DistProfiler.annotate(color="red")
def update_actor(self, data: DataProto):
# ...
micro_batch_size = self.config.actor.ppo_micro_batch_size_per_gpu
data.meta_info["micro_batch_size"] = micro_batch_size
dataloader = self.actor.make_minibatch_iterator(data=data)
with Timer(name="update_policy", logger=None) as timer:
metrics = self.actor.update_policy(dataloader=dataloader)
# ...MegatronPPOActor.update_policy,update_policy 笔记
@GPUMemoryLogger(role="megatron actor", logger=logger)
def update_policy(self, dataloader: Iterable[DataProto]) -> dict:
for data in dataloader:
#在一个real_train_batch内,更新多次模型
# ...
self.actor_optimizer.zero_grad()
calculate_entropy = self.config.entropy_coeff != 0
micro_batch_size = self.config.ppo_micro_batch_size_per_gpu
max_token_len = None
if self.config.use_dynamic_bsz:
max_token_len = self.config.ppo_max_token_len_per_gpu * self.config.megatron.context_parallel_size
# ....
# 调用forward_backward_batch
metric_micro_batch = self.forward_backward_batch(
data,
calculate_entropy=calculate_entropy,
use_dynamic_bsz=self.config.use_dynamic_bsz,
micro_batch_size=micro_batch_size,
max_token_len=max_token_len,
mini_batch_size=self.config.ppo_mini_batch_size,
)
# ...
# 更新模型
update_successful, grad_norm, num_zeros_in_grad = self.actor_optimizer.step()
# ...CriticWorker.update_critic,CriticWorker.update_critic 笔记
@register(dispatch_mode=make_nd_compute_dataproto_dispatch_fn(mesh_name="critic"))
@DistProfiler.annotate(color="pink")
def update_critic(self, data: DataProto):
data = data.to(get_device_id())
# ...
dataloader = self.critic.make_minibatch_iterator(data)
with Timer(name="update_critic", logger=None) as timer:
metrics = self.critic.update_critic(dataloader=dataloader)
# ...MegatronPPOCritic.update_critic 同理,PPOCritic.update_critic 笔记
@GPUMemoryLogger("megatron critic", logger=logger)
def update_critic(self, dataloader: Iterable[DataProto]):
metrics = {}
for data in dataloader:
self.critic_optimizer.zero_grad()
micro_batch_size = self.config.ppo_micro_batch_size_per_gpu
max_token_len = None
if self.config.use_dynamic_bsz:
max_token_len = self.config.ppo_max_token_len_per_gpu * self.config.megatron.context_parallel_size
# 最核心部分
metric_micro_batch = self.forward_backward_batch(
data,
forward_only=False,
use_dynamic_bsz=self.config.use_dynamic_bsz,
micro_batch_size=micro_batch_size,
max_token_len=max_token_len,
mini_batch_size=self.config.ppo_mini_batch_size,
)
metric_micro_batch = metric_micro_batch["output"]
update_successful, grad_norm, num_zeros_in_grad = self.critic_optimizer.step()
# ...MegatronPPOActor.make_minibatch_iterator:make_mini_batch 代码笔记
def make_minibatch_iterator(self, data: DataProto) -> Iterable[DataProto]:
select_keys = [
"responses",
"input_ids",
"attention_mask",
"response_mask",
"position_ids",
"old_log_probs",
"advantages",
]
# ...
# ...
data = data.select(batch_keys=select_keys)
return data.make_iterator(
mini_batch_size=self.config.ppo_mini_batch_size,
epochs=self.config.ppo_epochs,
seed=self.config.data_loader_seed,
dataloader_kwargs={"shuffle": self.config.shuffle},
)actor.ppo_micro_batch_size_per_gpu (梯度累积)
背景
一次前向反向更新会OOM,因此拆分成多步。梯度累积:计算出梯度,但不清零,多步累积,最后一次性更新。
含义
- update actor(或critic)时,对当前
mini_batch进行划分- 划分为
多个micro-batchesmicro_batch_size=ppo_micro_batch_size_per_gpu
- 本质就是
梯度累积步数
- 划分为
real_train_batch_size->ppo_mini_batch_size->ppo_micro_batch_size_per_gpu
Critic同理
- 参数为
critic.ppo_mini_batch_size_per_gpu
以下3者有相似处
- rollout.log_prob_micro_batch_size_per_gpu
计算old_log_prob,划分real_train_batch
- ref.log_prob_micro_batch_size_per_gpu
计算ref_log_prob,划分real_train_batch
- actor.ppo_micro_batch_size_per_gpu
更新模型+梯度相关,划分mini-batch
- 这个值可能和
RL学习稳定性有关系,小的数值+大的学习率,可能会导致训练崩塌。 - 原因:
单次梯度计算依赖的样本数量。如果太小,可能导致梯度估算的方差大,噪声大,信噪比更低- 策略网络容易更新错误,被带偏了。
- 需观测相关指标:
pg_loss,kl_loss,entropy,advantages等等。
ActorRolloutRefWorker.update_actor,update_actor 主入口笔记
def update_actor(self, data: DataProto):
# ...
micro_batch_size = self.config.actor.ppo_micro_batch_size_per_gpu
data.meta_info["micro_batch_size"] = micro_batch_size
dataloader = self.actor.make_minibatch_iterator(data=data)
with Timer(name="update_policy", logger=None) as timer:
metrics = self.actor.update_policy(dataloader=dataloader)
# ...MegatronPPOActor.update_policy,update_policy 笔记
@GPUMemoryLogger(role="megatron actor", logger=logger)
def update_policy(self, dataloader: Iterable[DataProto]) -> dict:
metrics = {}
for data in dataloader:
self.actor_optimizer.zero_grad()
# ...
calculate_entropy = self.config.entropy_coeff != 0
if data.meta_info.get("micro_batch_size", None) is not None:
micro_batch_size = data.meta_info["micro_batch_size"]
else:
micro_batch_size = self.config.ppo_micro_batch_size_per_gpu
# 调用forward_backward_batch,具体内容见上文
metric_micro_batch = self.forward_backward_batch(
data,
calculate_entropy=calculate_entropy,
use_dynamic_bsz=self.config.use_dynamic_bsz,
micro_batch_size=micro_batch_size,
max_token_len=max_token_len,
mini_batch_size=self.config.ppo_mini_batch_size,
)
# 统计loss等其他指标
# ...
# 更新模型
update_successful, grad_norm, num_zeros_in_grad = self.actor_optimizer.step()
data = {"actor/grad_norm": grad_norm}
# ....MegatronPPOActor.forward_backward_batch,forward_backward_batch 笔记
def forward_backward_batch(
self,
data: DataProto,
forward_only=False,
use_dynamic_bsz=False,
micro_batch_size=None,
max_token_len=None,
mini_batch_size=None,
):
# broadcast from last pp rank to all other pp ranks
# ...
mini_batch = data
mini_batch.batch = mini_batch.batch.contiguous()
# ...
if use_dynamic_bsz:
# pass
else:
micro_batches = mini_batch.batch.split(micro_batch_size)
seq_len = micro_batches[0]["input_ids"].shape[1]
total_seqlen = micro_batch_size * seq_len
n_micro_batch = len(micro_batches)
forward_backward_func = get_forward_backward_func()
# batch should be a list of batches inside micro-batches
batch_generator = make_batch_generator(micro_batches, vpp_size=len(self.critic_module))
# TODO: we may use the new schedule instead
# for flash-attn: (seq_len, batch_size, hidden_size) = (mbs*seq_len, 1, hidden_size)
if mpu.get_pipeline_model_parallel_world_size() > 1:
losses_reduced = forward_backward_func(
forward_step_func=forward_step,
data_iterator=batch_generator,
model=self.critic_module,
num_microbatches=n_micro_batch,
seq_length=total_seqlen, # no use when input_shapes was set
micro_batch_size=1, # no use when input_shapes was set
forward_only=forward_only,
)
else:
losses_reduced = forward_backward_func(
forward_step_func=forward_step,
data_iterator=batch_generator,
model=self.critic_module,
num_microbatches=n_micro_batch,
seq_length=total_seqlen, # in use for pp = 1 #
micro_batch_size=1, # in use for pp = 1 #
forward_only=forward_only,
)
# loss_reduces contains the stats returned from loss_func
losses_reduced = {"output": losses_reduced}
if use_dynamic_bsz:
losses_reduced["indices"] = indices
return losses_reduced下一步具体见笔记
rollout.log_prob_micro_batch_size_per_gpu
含义
- rollout期间,计算log_prob时,对
real_train_batch 进行划分 - 划分为
多个micro-batchesmicro_batch_size=log_prob_micro_batch_size_per_gpureal_train_batch_size-> 多个log_prob_micro_batch_size_per_gpu
以下3者有相似处
- rollout.log_prob_micro_batch_size_per_gpu
计算old_log_prob,划分real_train_batch
- ref.log_prob_micro_batch_size_per_gpu
计算ref_log_prob,划分real_train_batch
- actor.ppo_micro_batch_size_per_gpu
更新模型+梯度相关,划分mini-batch
log_prob_micro_batch_size通常可以设置得比ppo_micro_batch_size大很多
ActorRolloutRefWorker.compute_log_prob,compute_log_prob 笔记
@register(dispatch_mode=make_nd_compute_dataproto_dispatch_fn(mesh_name="actor"))
@GPUMemoryLogger(role="compute_log_prob", logger=logger)
@DistProfiler.annotate(color="blue")
def compute_log_prob(self, data: DataProto):
data.meta_info["micro_batch_size"] = self.config.rollout.log_prob_micro_batch_size_per_gpu
# ...
# 核心部分,调用megatron_actor计算
output, entropys = self.actor.compute_log_prob(data=data, calculate_entropy=True)
# 返回格式
output = DataProto.from_dict(
tensors={"old_log_probs": output, "entropys": entropys},
meta_info={"temperature": self.config.rollout.temperature},
)
# ...
return outputMegatronPPOActor.compute_log_prob,PPOActor compute_log_prob 笔记
MegatronPPOActor.forward_backward_batch,forward_backward_batch 笔记
def forward_backward_batch(
self,
data: DataProto,
forward_only=False,
use_dynamic_bsz=False,
micro_batch_size=None,
max_token_len=None,
mini_batch_size=None,
):
# broadcast from last pp rank to all other pp ranks
# ...
mini_batch = data
mini_batch.batch = mini_batch.batch.contiguous()
# ...
if use_dynamic_bsz:
# pass
else:
micro_batches = mini_batch.batch.split(micro_batch_size)
seq_len = micro_batches[0]["input_ids"].shape[1]
total_seqlen = micro_batch_size * seq_len
n_micro_batch = len(micro_batches)
forward_backward_func = get_forward_backward_func()
# batch should be a list of batches inside micro-batches
batch_generator = make_batch_generator(micro_batches, vpp_size=len(self.critic_module))
# TODO: we may use the new schedule instead
# for flash-attn: (seq_len, batch_size, hidden_size) = (mbs*seq_len, 1, hidden_size)
if mpu.get_pipeline_model_parallel_world_size() > 1:
losses_reduced = forward_backward_func(
forward_step_func=forward_step,
data_iterator=batch_generator,
model=self.critic_module,
num_microbatches=n_micro_batch,
seq_length=total_seqlen, # no use when input_shapes was set
micro_batch_size=1, # no use when input_shapes was set
forward_only=forward_only,
)
else:
losses_reduced = forward_backward_func(
forward_step_func=forward_step,
data_iterator=batch_generator,
model=self.critic_module,
num_microbatches=n_micro_batch,
seq_length=total_seqlen, # in use for pp = 1 #
micro_batch_size=1, # in use for pp = 1 #
forward_only=forward_only,
)
# loss_reduces contains the stats returned from loss_func
losses_reduced = {"output": losses_reduced}
if use_dynamic_bsz:
losses_reduced["indices"] = indices
return losses_reducedref.log_prob_micro_batch_size_per_gpu
含义
- rollout期间,计算ref_log_prob时,对
real_train_batch进行划分 - 把
real_train_batch划分为多个micro-batchesmicro_batch_size=log_prob_micro_batch_size_per_gpureal_train_batch_size-> 多个log_prob_micro_batch_size_per_gpu
以下3者有相似处
- rollout.log_prob_micro_batch_size_per_gpu
计算old_log_prob,划分real_train_batch
- ref.log_prob_micro_batch_size_per_gpu
计算ref_log_prob,划分real_train_batch
- actor.ppo_micro_batch_size_per_gpu
更新模型+梯度相关,划分mini-batch
关键参数约束
max_token_len_per_gpu
含义
- 顾名思义,每个gpu生成的最大token长度。
作用
- 在forward_backward_batch里,计算total_seqlen
- total_seqlen = micro_batch_size * seq_len
- 但
实际这个不会生效,因为定好了shape做好了pad,forward_backward_batch 笔记
actor.ppo_max_token_len_per_gpu
# Max tokens per GPU in one PPO batch; affects gradient accumulation
# Typically it should be: n * ${data.max_prompt_length} + ${data.max_response_length}
# oc.select: the default val for ref.log_prob_max_token_len_per_gpu
ppo_max_token_len_per_gpu: 16384ref.log_prob_max_token_len_per_gpu
# the max token length per GPU
# same as actor_rollout_ref.actor.ppo_max_token_len_per_gpu if it exists, otherwise 16384
log_prob_max_token_len_per_gpu: ${oc.select:actor_rollout_ref.actor.ppo_max_token_len_per_gpu,16384}rollout.log_prob_max_token_len_per_gpu
# max token length for log_prob computation
# same as actor_rollout_ref.actor.ppo_max_token_len_per_gpu if it exists, otherwise 16384
log_prob_max_token_len_per_gpu: ${oc.select:actor_rollout_ref.actor.ppo_max_token_len_per_gpu,16384}参数约束
并行参数计算
实际训练bs
real_train_batch_size= data.train_batch_size * rollout.n
总GPU数量
n_gpus= n_gpus_per_node * nnodes
模型并行
mp=tp*ppmodel_parallel_size= tensor_model_parallel_size * pipeline_model_parallel_size
数据并行
dp=n_gpus// (mp*cp)megatron_dp= n_gpus // (model_parallel_size* context_parallel_size )
实际训练最小bs
mini_bs=dp*micro_bs_per_gpuminimal_bsz= megatron_dp * actor.ppo_micro_batch_size_per_gpu
rollout llm 副本数
rollout_replicas:n_gpus// rollout.tp*pp*dp- 每个副本最大并发:concurrent_samples_per_replica数
并行参数约束条件
实际train_bs被mini_bs整除
real_train_batch_size%minimal_bsz== 0
TP:注意力头数/GQA组数 整除
num_attention_heads%tp== 0num_query_groups%tp== 0,非常重要!!
PP:总层数整除
num_layers%pp== 0
EP:专家数量整除
num_moe_experts%ep== 0
EP分组:专家数量整除
num_moe_experts%moe_router_num_groups== 0
Expert DP:专家数据并行度,DP 整除EP
Expert DP=DP/EP
TP/PP/CP参数:GPU数量整除
n_gpus%mp*cp== 0 ,非常重要!!n_gpus%tp*pp*cp== 0
- TP:切分Attention/MLP
- TP越大:单卡KV Cache压力小,支持Context越长
- 缺点:受限于KV Heads数量;跨节点通信慢。
- EP:切分Experts
- EP越大:单价存单专家越少,静态显存占用低
- 缺点:引入All-to-All通信,动态显存变大。长文本下,EP太大,Buffer可能撑爆显存。
- 通信效率
- 节点内:适合TP和EP通信
- 节点间:适合DP通信,梯度同步,通信量小
- 尽量让TP和EP都在一台机器内,解决。
参数配置
SGLang+Yarn 配置
环境变量
- 如果环境变量未生效,可尝试ray stop后,再试试。
export SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1
+ray_kwargs.ray_init.runtime_env.env_vars.SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN='"1"'\模型配置
- 常规rope配置
+actor_rollout_ref.model.override_config.rope_scaling.type=yarn \
+actor_rollout_ref.model.override_config.rope_scaling.factor=1.5 \
+actor_rollout_ref.model.override_config.rope_scaling.original_max_position_embeddings=32768 \SGLang 配置
context_length
export SGLANG_OVERRIDE_ARGS='{"rope_scaling": {"type": "yarn", "factor": 1.5, "original_max_position_embeddings": 32768}}'
+actor_rollout_ref.rollout.engine_kwargs.sglang.context_length=49152
+actor_rollout_ref.rollout.engine_kwargs.sglang.json_model_override_args="'${SGLANG_OVERRIDE_ARGS}'"Megatron 重计算配置
具体见笔记:Transformer 显存关键参数-重计算
recompute_granularity=selective
recompute_modules='["core_attn", "mlp"]'
actor_rollout_ref.actor.megatron.override_transformer_config.recompute_granularity="${recompute_granularity}"
actor_rollout_ref.actor.megatron.override_transformer_config.recompute_modules="${recompute_modules}"Megatron + MoE
使用mbridge加载MoE模型
# 安装库,通过pip安装代码非最新,存储model时会报错。
pip install mbridge
# 选择从仓库安装
git clone https://github.com/ISEEKYAN/mbridge.git
pip uninstall mbridge && pip install --no-deps /path/mbridge
# 配置
actor_rollout_ref.actor.megatron.use_mbridge=True模型合并
官方文档:verl Using Checkpoints to Support Fault Tolerance Training
- 切记不要像官网一样使用
--tie-word-embedding这个参数,这会导致不存储lm_head.weight,这样会导致转换成hfmodel部署时,预测会出错,乱码、不停止。 - 保存后的tokenizer_config.json,没有
chat_template这个参数,原基模是有的,可以复制粘贴过来。
合并脚本如下:
local_dir="xxx"
target_dir="xxx"
python -m verl.model_merger merge \
--backend megatron \
--local_dir ${local_dir} \
--target_dir ${target_dir} \模型预测
部署成本地服务,参考sglang官方文档。
DEFAULT_SAMPLING_PARAMS='{"temperature": 0, "top_p": 1}'
model_path="xxx/hfmodel"
model_name="hmodel2"
python -m sglang.launch_server \
--model-path ${model_path} \
--host "127.0.0.1" \
--port 6380 \
--tensor-parallel-size 8 \
--served-model-name ${model_name} \
--preferred-sampling-params "${DEFAULT_SAMPLING_PARAMS}" \