🧩 组件与 MP 分离
ms-swift 的命令行不是唯一使用入口。用户可以直接调用训练 recipe,也可以复用模型,数据,采样,loss,reward 等组件编写自己的训练流程,还可以在 TrainBench 画布上拖拽组件,连线后运行。三种入口最终使用同一套组件:底层组件由 twinkle 提供,ms-swift 负责模型与数据适配,配置解析和常用训练流程的组装。
本文介绍 Mechanism / Policy separation(M/P 分离):将算法决策与系统执行分离,使算法修改,组件替换与分布式放置尽量独立。Policy 指软件设计中的决策逻辑,不限于强化学习里的 policy model。然后列出代码组件与 TrainBench 拖拽组件两类组件的作用与输入输出,用一个组件化的 GRPO 训练脚本说明如何替换 loss,advantage 与 reward,最后说明 local,ray,训练服务三种执行方式下同一份代码需要修改的配置。
蓝色表示配置与控制,绿色表示训练数据流,虚线表示权重同步。命令行,Python 和 TrainBench 画布共用 ms-swift 的 Config,builders 与 recipe;twinkle 组件将计算交给 infra。infra 有 local,ray,训练服务三种形态,切换形态仅修改执行配置,组件代码不变。
📐 原理与边界
同一个训练流程包含两类不同的问题:
- Policy:选择什么目标,如何准备样本,先采样还是先更新,怎样计算 advantage,什么时候记录指标或保存模型。
- Mechanism:模型在哪些设备与进程上执行,张量如何分片,调用如何跨进程传输,权重如何同步,checkpoint 如何读写。
例如 GRPO 决定"对同一个 prompt 生成多个回答,根据相对奖励更新模型",这是算法决策;将训练模型和采样器放到不同 GPU,并将更新后的权重同步到采样器,是执行机制。
配置与数据
↓
SWIFT recipe:选择组件,定义目标,组织训练循环
↓
twinkle 组件:模型,数据,采样器,loss,reward,advantage
↓
twinkle 执行机制:设备放置,并行,远程调用,传输,权重同步与存储组件并不等于 Policy,也不等于基础设施。模型,loss,reward 等组件提供可复用能力;recipe 通过配置和调用顺序决定如何组合这些组件,组件内部则将分布式执行委托给相应机制。
| 层次 | 职责 | 用户通常修改的内容 |
|---|---|---|
| CLI / Config | 解析参数,处理默认值,校验组合。 | 模型,数据,训练超参数与并行配置。 |
| ms-swift Builders | 将配置转换为模型,模板,数据等组件。 | 组件适配,插件注册和构建方式。 |
| ms-swift Recipe | 组装组件,定义训练目标,组织更新和保存流程。 | 新算法,数据节奏,目标组合与训练循环。 |
| TrainBench session | 读取组件注册表,校验画布连线,按节点依赖调度执行。 | 画布上的组件选择与连线。 |
| twinkle 组件与基础设施 | 提供统一操作及其本地,分布式执行。 | 可复用组件,并行实现,传输或执行后端。 |
twinkle 使用 @remote_class,@remote_function 在组件上声明远程执行,数据分发和结果收集等信息,运行时通过 twinkle.initialize 配置执行方式。领域操作仍定义在组件自身,例如模型的 forward_backward 和采样器的 sample;recipe 调用这些操作,不管理 actor 通信细节。
分离的目的不是免除算法作者对分布式约束的理解,而是避免在每个算法中重复实现 Ray actor,GPU 放置和权重传输。
🧩 组件
组件分两类。代码组件是 Python 对象,在脚本里直接构建与调用;TrainBench 拖拽组件是画布上的节点,每个节点对应一个代码组件或一段 recipe 逻辑,通过连线将输出端口连接到下游节点的输入端口。两类组件的输入输出一致,画布保存后也可以导出为代码。
组件之间传递的数据结构如下表,下文两张组件表的输入输出列均使用表中的名称。名称指单个元素,成批传递时写作 list[名称];类型为 dict 时列出重要 key。只列训练主链使用的字段,完整定义见链接的源码。trajectory 是 TypedDict,运行时为 dict:数据集原始行,编码后的行与采样结果是同一形态,区别只在字段填充到哪个阶段。
| 名称 | 类型 | 重要 key | 说明 |
|---|---|---|---|
trajectory | Trajectory,TypedDict,继承 InputFeature | 原始行:messages,tools,user_data(标签列,如 solution),images / videos / audios。编码后追加:input_ids,labels,attention_mask,position_ids。采样后追加:response_token_ids,response_positions,rollout_logps,turns,stop_reason。评分后追加 rewards;优势估计后追加 advantages,returns,ref_logps,old_logps(响应帧字段长度恒等于响应 token 数)。身份:episode_id,group_key(同一 prompt 的一次生成组),policy_version。 | 全链路统一的样本结构,成批传递为 list[trajectory];TrainBench 上显示为 list[trajectory] |
score | dict,与 trajectory 逐行对齐,结构见 advantage/base.py 的 _call | rewards.orm(评分器名到分数),rewards.baseline,prm_segments(可选,分段过程分) | driver 随 list[trajectory] 一并交付,Advantage 读取;TrainBench 上显示为 list[score],select 与 advantage 节点的可选输入 |
model_output / reference_output / teacher_output / old_policy_output / value_output | ModelOutput,TypedDict,值为 tensor 或 list | logits,logps(每个 token 的 log 概率),values(critic 的逐 token 值),loss,num_tokens,embeddings。output_frame='response' 时附带 episode_ids,response_token_ids,field_frames(标记每个字段是响应帧,整序列还是逐行) | 模型前向结果,只含 output_fields 请求的字段。五个名称同一类型,按角色区分:model_output 为前向结果,reference_output 为参考策略的 logps(KL 用),teacher_output 为教师模型输出(蒸馏用),old_policy_output 为更新前策略的 logps,value_output 为 critic 的逐 token 值(gae 用) |
loss_output | LossOutput,TypedDict | loss(标量 tensor),num_tokens(loss 的归一化分母),channel_loss(按通道拆分的 loss 分量,用于日志) | Loss 的返回值 |
sample_response | SampleResponse,dataclass | sequences:SampledSequence 列表,每条含 tokens,logprobs,decoded,stop_reason,new_input_feature(prompt 与生成的回答拼接后的单个 trajectory);prompt_token_ids,prompt_logprobs | Sampler 的返回值,每条 prompt 一个,成批为 list[sample_response] |
metric | dict | values(指标名到 float 或 None),invalid_count(非有限值数量) | 指标摘要;代码中 calculate_metric() 的返回值,TrainBench 上显示为 metric |
step | dict | model_id,micro_step(已确认的 backward 微步数),global_step(已确认的 optimizer 总步数),optimizer_steps(本次完成数),batch_id,consumed | 一次 train_step 的完成回执;TrainBench 上显示为 step |
sync | dict | parameter_version(实际同步的参数版本),receivers(接收方 id 列表),confirmed(各接收方的完成结果) | 一次权重同步的完成回执;TrainBench 上显示为 sync |
artifact | dict | path(产物路径或发布 URI),format,manifest(可选) | 写出的模型,训练快照或报告;代码中 model.save() 返回 path,TrainBench 上显示为 artifact |
dataset_meta | DatasetMeta,dataclass | dataset_id(ms://,hf:// 标识或本地路径),subset_name,split,data_slice,data(内存中的行列表或列 dict) | 数据集描述,Dataset 的构造参数 |
then / after / source | 无载荷 | 无 | TrainBench 控制端口:表示前序节点已完成;source 是常驻游标的控制句柄,连接该端口不触发取数 |
🧩 代码组件
| 类别 | 组件 | 接口 | 作用 | 输入 | 输出 |
|---|---|---|---|---|---|
| 数据 | Dataset / PackingDataset | Dataset(DatasetMeta(...)) | 从 ModelScope 或 HuggingFace 加载数据集。PackingDataset 将多条短样本拼接为一条以提高 GPU 利用率。 | dataset_meta | 原始行阶段的 list[trajectory](含 messages 等列),支持下标访问与 len() |
| 数据 | Dataset / PackingDataset | set_template(template, **kwargs) | 绑定模板,encode 按该模板渲染。 | Template 实例,类名或注册名,构造参数 | 无返回,模板绑定到数据集实例 |
| 数据 | Dataset / PackingDataset | map(preprocessor) | 挂载预处理器,执行行级 ETL。 | Preprocessor 实例,类名或可调用 | 无返回,__getitem__ 返回的 trajectory 已应用该变换 |
| 数据 | Dataset / PackingDataset | encode(add_generation_prompt=False) | 按模板编码全部行。 | add_generation_prompt:末尾是否追加 assistant 起始 token,生成任务设 True | 无返回,每行追加 input_ids,labels,attention_mask,position_ids |
| 数据 | Template | encode(sample, add_generation_prompt=None) | 按模型的对话模板渲染 messages 并分词。 | 单个 trajectory 的 messages,或 chosen / rejected 对;add_generation_prompt 含义同上,None 表示按编码用途推断 | 单个 trajectory 的 token 字段(input_ids,labels,attention_mask,position_ids) |
| 数据 | Preprocessor | __call__(rows) | 行级 ETL,内置 SelfCognitionProcessor,AlpacaProcessor 等,也可通过继承自定义。 | 原始行阶段的 list[trajectory] | list[trajectory],列可增加或删除 |
| 数据 | DataLoader | __iter__ / __len__ / set_epoch(epoch) | 按 DeviceMesh 切分与分发数据,处理 shuffle,seed 与加载进程数。 | Dataset,batch_size,collate_fn(默认右侧 padding 并转为 tensor) | 每次 __next__ 交付 list[trajectory] 的一个 batch,只含当前数据并行 rank 的分片 |
| 模型 | Model | set_loss(loss_cls, **kwargs) | 设置训练目标。TransformersModel 与 MegatronModel 接口一致。 | 注册名(如 'grpo'),Loss 类或可调用;kwargs 是构造参数,如 epsilon,beta | 无返回,forward_backward 调用该 loss |
| 模型 | Model | set_optimizer(optimizer_cls, lr, weight_decay) / set_lr_scheduler(scheduler_cls, **kwargs) | 设置优化器与学习率调度。 | 优化器类名或类,lr,weight_decay;调度器类名或类,warmup_ratio 等构造参数;adapter_name 选参数组,默认 LoRA 参数 | 无返回,clip_grad_and_step 使用二者更新参数 |
| 模型 | Model | add_adapter_to_model(adapter_name, config_or_dir, task=...) | 添加 LoRA adapter 与任务头。 | adapter 名;LoRA 配置 dict 或 checkpoint 目录;task 为任务头类型 | 无返回,模型带 LoRA 参数参与前向与保存 |
| 模型 | Model | forward_only(inputs=..., output_fields=..., output_frame=...) | 只前向,不累积梯度。 | inputs:list[trajectory];output_fields:要返回的字段,如 ('logps',),('values',),('logits',);output_frame='response':token 级字段按响应帧返回,每条样本一个 list,否则返回整序列 tensor | model_output,只含请求的字段 |
| 模型 | Model | forward_backward(inputs=..., micro_batch_size=..., gradient_accumulation_steps=...) | 前向与反向,模型内部按 micro-batch 切分并累积梯度。 | inputs:list[trajectory],训练目标字段(advantages,ref_logps 等)已由 Advantage 写入;micro_batch_size:每次前向的行数;gradient_accumulation_steps:梯度累积份数 | model_output(loss,num_tokens,channel_loss);梯度累积在模型内 |
| 模型 | Model | clip_grad_and_step(max_grad_norm, gradient_accumulation_steps) | 梯度裁剪,优化器更新,学习率调度。 | max_grad_norm:梯度范数上限;norm_type:范数类型,默认 2;gradient_accumulation_steps:梯度除以该份数后更新 | 无返回;优化器前进一步,学习率调度前进一步 |
| 模型 | Model | calculate_metric(is_training) | 汇总累计的训练指标。 | is_training:True 取训练指标,False 取评估指标 | metric,含 loss,grad_norm,学习率 |
| 模型 | Model | save(name, output_dir) / load(name, output_dir) | 保存与加载。 | checkpoint 名与输出目录 | save 返回 artifact 的 path(产物目录),load 无返回 |
| 模型 | Loss | __call__(inputs, outputs, **kwargs) | 训练目标。model.set_loss 接注册名,类或可调用对象;注册表含 cross_entropy,grpo,ppo,dpo 等。 | inputs:当前 micro-batch 的 list[trajectory];outputs:同一批的 model_output(logps 等) | loss_output |
| 模型 | Metric | accumulate(inputs, outputs) / calculate() | 训练指标累计与汇总,例如 GRPOMetric。 | accumulate 收 list[trajectory] 与 model_output | calculate() 返回 metric;reset() 清零 |
| 生成 | Sampler | sample(inputs, sampling_params, adapter_name, num_samples=1) | 常驻生成引擎:vLLMSampler,SGLangSampler,TransformersSampler;支持按 adapter 加载 LoRA。 | inputs:prompt 已编码的 list[trajectory];sampling_params:temperature,max_tokens 等;adapter_name;num_samples:每条采样数 | list[sample_response],每条的 sequences 含 num_samples 条 |
| 生成 | Rollout | __call__(trajectories) / step(traj, episode_id) | 在环境 lease 内通过 sampler 与 tools 多轮生成样本(Sample)。 | 带工具与环境配置的 list[trajectory] | __call__ 返回 list[trajectory]:messages 追加完整多轮,response_token_ids,rollout_logps,turns,stop_reason 已写入;step 推进一轮,返回该轮行与 RolloutStatus |
| 生成 | CheckpointEngineManager | sync_weights(merge_and_sync=True) | 将训练后的权重同步到 sampler。 | merge_and_sync:True 将 LoRA 合并进基座后同步整体权重;False 首次同步基座,之后只同步 LoRA 权重 | 无返回;sampler 权重更新,policy_version 前移 |
| 算法 | Reward | __call__(trajectories, **kwargs) | 规则评分函数,内置 math,format,gsm8k 等;自定义时继承 RewardRule。 | list[trajectory],读取 messages 与标签列 | list[float],driver 写入 score 的 rewards.orm[评分器名] |
| 算法 | Advantage | __call__(trajs, scores=..., ref_out=..., value_out=...) | 优势估计:grpo,gae,rloo,remax,gpg 等;自定义时继承 GRPOAdvantage 覆写 _per_sequence。 | trajs:list[trajectory];scores:driver 交付的 list[score];ref_out(KL 用的参考 logps),teacher_out,old_out(更新前策略的 logps),value_out(gae 的 critic 值):均为 output_frame='response' 的 model_output,可选 | list[trajectory] 的副本,写入 advantages(gae 另写 returns);以及日志 dict |
🧩 TrainBench 拖拽组件
画布将上表的组件注册为可拖拽的节点。每个节点声明固定的输入端口与输出端口,拖线时前端只提示合法端口,后端用同一份注册表校验,因此画布上可构成的图均可运行。下表输入输出列的名称就是画布上端口显示的名称,与上表数据结构同名:轨迹口显示 list[trajectory],评分口显示 list[score],指标口显示 metric,前向口按角色显示 model_output,reference_output,teacher_output,old_policy_output,value_output。载荷契约见 swift/dev/webui/schema.py 的 CHANNEL_SCHEMAS。节点分四组:
| 组 | 节点 | 作用 | 输入端口 | 输出端口 |
|---|---|---|---|---|
| 资源 | model | 唯一的参数化函数;选 lora 或 full,选 hf,megatron 或 unsloth 后端,声明占卡数与并行规格。 | artifact(可选,权重来源) | model |
| 资源 | dataset | 原始数据来源与预处理配置。 | 无 | data |
| 资源 | sampler | 常驻生成引擎,engine 选 vllm,sglang 或 torch。 | 无 | sampler |
| 资源 | rollout | 多轮生成器,绑定工具与环境,max_turns 限制轮数。 | sampler,tools(可选),env(可选) | rollout |
| 资源 | sandbox_env | 沙箱环境池,kind 选 local,agentenv,openenv 或 openenv_client。 | 无 | env |
| 资源 | toolset | 工具插件来源。 | 无 | tools |
| 资源 | api_endpoint | 外部 API 连接,凭据只从环境变量读取。 | 无 | endpoint |
| 算法 | loss | 损失对象。kind 选注册名(grpo,ppo,dpo 等),或通过 code 自定义公式。 | 无 | loss |
| 算法 | scorer | 评分器。kind 选注册名(math,format 等),或通过 code 自定义评分。 | 无 | scorer |
| 算法 | group_rule | 完整组准入规则,例如零方差组重采。 | 无 | rule |
| 算法 | code_component | 自定义组件,自行声明入口名,端口与副作用。 | 自声明 | 自声明 |
| 算法 | challenger | 自动出题器,一次产出同批的出题与解题两路轨迹。 | backend,solver_rollout(可选),env,api(可选) | list[trajectory](questions 与 answers 两路),source |
| 算法 | generate | 仅生成样本(Sample),不评分也不筛选。 | list[trajectory],engine 或 episode | list[trajectory] |
| 算法 | score | 对连接的每个评分器计算分数,分数写回 trajectory 的 rewards。 | list[trajectory],scorers | list[trajectory],list[score],metric |
| 算法 | model_forward | 一次独立前向,outputs 声明要 logps,values,logits 还是 embeddings。 | model,list[trajectory] | model_output |
| 算法 | privileged_view | 按行内 teacher_prompt 重编码出教师视图,策略主 trajectory 不回写。 | list[trajectory] | list[trajectory] |
| 算法 | advantage | 优势估计,estimator 选 grpo,gae,rloo 等;gae 必须接 value_output。 | list[trajectory],list[score](可选),reference_output,teacher_output,old_policy_output,value_output(均可选) | list[trajectory],metric |
| 算法 | select | 样本筛选,规则选 threshold,top_k 或 best_of_n;成对与完整组不拆散。 | list[trajectory],list[score](可选),model_output(可选) | list[trajectory],list[score],model_output,metric |
| 算法 | train_step | 执行 forward_backward 与 optimizer step,配置优化器,学习率,调度器,梯度累积与裁剪。 | model,loss,list[trajectory],reference_output,teacher_output,model_output(均可选,model_output 为 lanes 路),after(可选) | step,model,metric,then |
| 运行 | dataloader | 常驻游标,管理 epoch 与随机种子。source 选 prompts(移除末轮 assistant 消息,供生成侧使用)或 rows(完整训练行)。 | data,after(可选) | list[trajectory],source |
| 运行 | streaming_driver | 流式采样的控制面:采样准入,最大滞后,背压与批次确认。连接 scorers 时逐样本评分。 | prompts,engine(可选),episode(可选),scorers(可选),groups(可选),after(可选) | list[trajectory],source |
| 运行 | weight_sync | 将训练后的权重同步到 sampler,cadence 设同步间隔,同步完成后才确认。 | model,targets,source(可选),step(可选),after(可选) | sync,then |
| 运行 | weight_average | 两个模型间的 copy 或 EMA。 | source,target,step | sync |
| 运行 | checkpoint | 保存模型权重(profile=model)或完整训练快照(profile=training,需接 step 与 source)。 | model,step(可选),source(可选),after(可选) | artifact |
| 产物 | merge | 将 LoRA 合并进基础权重。 | artifact(model) | artifact(model) |
| 产物 | quantize | 量化权重,可连接校准数据集。 | artifact(model),calib(可选) | artifact(model) |
| 产物 | infer | 从权重构建推理引擎并进行批量推理。 | model 或 artifact,data | list[trajectory],artifact(可选) |
| 产物 | eval | 评测,使用 sampler 或 endpoint。 | sampler 或 endpoint,data | metric,artifact(可选) |
| 产物 | deploy | 启动服务并等待就绪。 | artifact(model) | endpoint |
| 产物 | hub_push | 发布到 ModelScope 或 HuggingFace。 | artifact(model) | artifact(publication) |
连线的规则只有三条:
- 资源端口(
model,sampler,rollout,rule,env,tools,endpoint)沿连线共享给下游。上游只有一个同类资源时不连线也会自动解析,连线用于消歧或标记角色。 - 数据端口(
data,list[trajectory],list[score],model_output,metric,step,sync,artifact)必须连线,这些连线构成算法本身。其中list[trajectory]里的每个trajectory为同一对象沿流程逐步填充字段:raw → encoded → rollout(响应 token 与采样 logps)→ scored(rewards)→ train_ready(advantages,returns)。 - 控制端口(
then,source)仅在两个节点之间没有数据边表达先后关系时使用,表示"完成后再继续"。
运行语义:点击任意节点,运行该节点的全部前序节点,无依赖的节点并行执行(例如模型与数据集同时构建),有依赖的节点按连线顺序执行,直到被点击的节点。资源组节点在会话内构建一次,再次点击不会重建模型或数据集。运行完成的节点可查看实际输出,例如 streaming_driver 交付的轨迹,advantage 写回的优势值,train_step 的训练回执。
画布提供 GRPO,PPO,RFT,OPSD,RSI,SFT,DPO,KTO,Embedding,Reranker,SeqCls,Decision 脚手架,每个按训练类型(LoRA / 全参)生成两种拓扑。载入后可以增删节点或修改连线,等价于修改下文脚本中的某个组件或某行调用;离线算法的数据格式由 encode 节点的 format 参数显式声明,不按行形状推断。
🎯 组件化的 GRPO 训练
下面是一个完整的 LoRA GRPO 脚本,与 examples/v5/rl/grpo/grpo.sh 使用同样的参数,显式实现"采样 → 评分 → 优势估计 → 更新 → 权重同步"循环。可运行版本位于源码的 examples/v5/rl/grpo/grpo.py。先按快速启动安装 ms-swift,再运行 CUDA_VISIBLE_DEVICES=0,1 python grpo.py:
# Copyright (c) ModelScope Contributors. All rights reserved.
# GRPO with the whole training process written out: rollout -> reference logps -> advantage ->
# forward_backward + clip_grad_and_step -> weight publication, with the recipe's step metrics and
# checkpointing attached.
# Run (online RL runs on Ray): CUDA_VISIBLE_DEVICES=0,1 python examples/v5/rl/grpo/grpo.py
# Remote server: mode='remote' + server_base_url (+ server_api_key), and sampler_mode='disaggregated'.
import math
from twinkle.advantage import GRPOAdvantage
from swift.dev.builder import build_prompt_dataloader
from swift.dev.builder.optimizer import resolve_max_grad_norm
from swift.dev.config import (
CheckpointConfig,
DatasetConfig,
DistributedConfig,
GenerationConfig,
LoggingConfig,
ModelConfig,
RewardConfig,
RLConfig,
RolloutConfig,
TemplateConfig,
TrainConfig,
TunerConfig,
)
from swift.dev.config.process import policy_replay_count
from swift.dev.recipe.batching import micro_batch_config_from, optimizer_batch_slices
from swift.dev.recipe.configs import RecipeConfigs
from swift.dev.recipe.online import publish_policy, reclaim_training_devices
from swift.dev.recipe.policy.assembly import build_policy_driver, build_policy_objects, policy_group_requests
from swift.dev.recipe.policy.run_policy import PolicyMetrics, record_reward_metric
from swift.dev.recipe.utils import (
Checkpointer,
RolloutStepState,
close_driver_preserving_error,
finalize_rl_resources,
initialize_rl_devices,
prompt_rows_from_dataset,
rollout_batch_geometry,
)
from swift.dev.utils.naming import register_loss
from swift.dev.utils.scoring import copy_inputs
OUTPUT_DIR = 'output/grpo'
# CUSTOM LOSS (optional): subclass a registered twinkle loss and register the class by NAME so every
# transport (Ray worker, remote server) resolves the same class; `model.set_loss` below selects it.
# @register_loss('my_grpo')
# class MyGRPOLoss(GRPOLoss):
# ... # override the aggregation / clipping; constructor kwargs arrive via set_loss
# CUSTOM ADVANTAGE (optional): estimators are plain subclasses; `_per_sequence` is the group baseline.
# class MyAdvantage(GRPOAdvantage):
# def _per_sequence(self, rewards, num_generations=1, scale='group', **kwargs):
# ...
def build_configs() -> RecipeConfigs:
"""The run as typed Config objects: the same knob values as grpo.sh."""
return RecipeConfigs(
model=ModelConfig(model='Qwen/Qwen3.5-4B', task_type='causal_lm', torch_dtype='bfloat16', attn_impl='flash_attention_2'),
template=TemplateConfig(
template='qwen3_5', max_length=3072,
system='You are a helpful math assistant. Please reason step by step, and put your final answer within \\boxed{}.',
),
dataset=DatasetConfig(dataset=['AI-MO/NuminaMath-TIR#5000']),
# per_device_train_batch_size x gradient_accumulation_steps x dp = rows per optimizer update.
# max_steps > 0 is required here: the LR schedule and the loop below both read it.
train=TrainConfig(
num_train_epochs=1, per_device_train_batch_size=2, gradient_accumulation_steps=4, learning_rate=1e-4,
warmup_ratio=0.05, max_steps=20, gradient_checkpointing=True,
),
# THE ONLY SWITCH between execution modes: 'ray' (this machine: trainer and sampler are Ray
# actors) or 'remote' (a twinkle-server holds both; add server_base_url / server_api_key).
# Online RL does not run in mode='local'.
distributed=DistributedConfig(mode='ray', backend='hf', nproc_per_node=2),
checkpoint=CheckpointConfig(output_dir=OUTPUT_DIR, add_version=False, save_steps=10, save_total_limit=2),
tuner=TunerConfig(tuner='lora', lora_rank=8, lora_alpha=32, target_modules=['all-linear']),
logging=LoggingConfig(report_to=['tensorboard'], logging_steps=1),
# Algorithm knobs: one group = num_generations samples per prompt; beta is the KL weight
# against the reference model; epsilon is the PPO-style clip range of the GRPO loss.
rl=RLConfig(
rl_type='grpo', num_generations=8, advantage_estimator='grpo', epsilon=0.2, beta=0.04,
max_completion_length=2048,
),
# Reward rules by registered name, a RewardRule subclass, or a reward-model id.
reward=RewardConfig(orm=['accuracy']),
# colocate: trainer and sampler share the GPUs and switch by phase; disaggregated: separate
# GPUs. mode='remote' requires disaggregated (or leaving this unset).
rollout=RolloutConfig(sampler_mode='colocate', vllm_gpu_memory_utilization=0.5),
generation=GenerationConfig(temperature=1.0),
)
def main() -> None:
configs = build_configs()
train, rollout, rl = configs.train, configs.rollout, configs.rl
ga, repeats = train.gradient_accumulation_steps, policy_replay_count(rl)
# DATA: the prompt rows of the dataset (the assistant turn stripped) plus the label columns
# the reward rules read (here: `solution`).
prompt_rows, prompts, extras = prompt_rows_from_dataset(configs.dataset, system=configs.template.system)
# DEVICES: start the runtime, plan the placement of the trainer, the sampler and the reference
# model, and build the template. No GPU work happens in this process under 'ray'.
template, resource_plan, meshes = initialize_rl_devices(
configs, output_dir=OUTPUT_DIR, prompt_rows=prompt_rows,
group_requests=lambda: policy_group_requests(configs),
)
# BATCH SHAPE: one optimizer update = train_batch_size (= per_device x dp) x ga rows; one
# delivery batch fills whole updates; max_steps derives from the prompts x group size.
geometry = rollout_batch_geometry(
configs, resource_plan=resource_plan, num_prompts=len(prompts),
num_generations=rl.num_generations, num_iterations=repeats, recipe='grpo-example',
)
train_batch_size = geometry.train_batch_size
# COMPONENTS: trainer (loss, optimizer, LR schedule attached), sampler, rollout, weight-sync
# engine, reference model, reward scorers and the advantage estimator -- all from the configs.
resources = build_policy_objects(
configs, template, max_steps=geometry.max_steps, batch_size=geometry.batch_size,
resource_plan=resource_plan, auxiliary_meshes=meshes,
)
model, reference, advantage = resources.model, resources.reference, resources.advantage
# model.set_loss('my_grpo', epsilon=rl.epsilon, beta=rl.beta)
# advantage = MyAdvantage(num_generations=rl.num_generations, scale_rewards='group', remote_group=<the control group>)
# STREAM: prompt dataloader -> streaming driver. Each iteration samples one batch of
# trajectories with `orm` scoring applied and returns (rows, facts).
dataloader = build_prompt_dataloader(
prompts, extras, seed=configs.dataset.data_seed, shuffle=configs.dataset.train_dataloader_shuffle,
batch_size=geometry.generation_batch_size,
)
driver = build_policy_driver(
resources, configs, prompt_dataloader=dataloader, batch_size=geometry.batch_size,
num_train_epochs=geometry.epochs, max_steps=math.ceil(geometry.max_steps / geometry.steps_per_batch),
)
# STEP METRICS + CHECKPOINTS: the recipe's step cadence (loss / lr records to the logging
# backend, a checkpoint every save_steps and at the end) plus the rollout-level reward records.
metrics = PolicyMetrics(None, driver)
state = RolloutStepState(
model, train, padding_free=configs.template.padding_free, gradient_accumulation_steps=ga,
max_steps=geometry.max_steps, max_grad_norm=resolve_max_grad_norm(train),
logging_config=configs.logging, output_dir=OUTPUT_DIR, save_steps=configs.checkpoint.save_steps,
extra_metrics_fn=metrics.extra_metrics, extra_metrics_granularity='iteration',
)
ckpts = Checkpointer(
model, state, configs.checkpoint, configs.dataset, configs.distributed, configs.tuner,
output_dir=OUTPUT_DIR, component_states=lambda: {'training': {'micro_step': state.micro_step}},
)
ckpts.snapshot_initial_adapter()
temperature = float(resources.sampling_params.get('temperature', 1.0))
batching = micro_batch_config_from(train) # micro_batch_size + the dynamic-batching fields
lent = False
def mark_lent() -> None:
nonlocal lent
lent = True
def sync() -> None:
# WEIGHT PUBLICATION: push the policy weights to the sampler. Under colocate the publication
# wakes the sampler and it takes the GPUs; the trainer stays offloaded until reclaim().
publish_policy(resources.engine, rollout, colocate=resources.colocate, on_lend=mark_lent)
def reclaim() -> None:
# COLOCATE HANDOVER: sleep the sampler and reload the trainer for the update.
nonlocal lent
if lent:
reclaim_training_devices(model, resources.sampler, rollout)
lent = False
state.handler.on_train_begin()
try:
try:
sync() # INITIAL PUBLICATION: the sampler must start from the policy's weights.
for rows, facts in driver:
reclaim()
# REWARD METRIC: fold this batch's ORM scores into the reward aggregate.
record_reward_metric(facts, orm_weights=configs.reward.orm_weights, reward_metric=metrics.reward_metric)
# REFERENCE LOGPS: the KL term reads them. With LoRA and no separate ref_model the
# reference is the trainer itself with the adapter disabled.
ref = None
if reference is not None:
ref = reference.forward_only(
inputs=copy_inputs(rows), output_frame='response', output_fields=('logps',),
temperature=temperature, **batching,
**({'disable_lora': True} if reference is model else {}),
)
# ADVANTAGE: scores -> per-sample advantages, written onto copies of the rows.
targets, summary = advantage(rows, ref_out=ref, scores=facts['scores'], global_step=state.global_step)
metrics.fold(summary, facts, facts.get('version_spans') or ())
# UPDATE: whole optimizer-update windows of train_batch_size x ga rows (``repeats`` replays
# of the batch; the tail that cannot fill one update is dropped).
for lo, hi in optimizer_batch_slices(len(targets) * max(1, repeats), train_batch_size, ga):
if state.reached_max() or state.should_stop():
break
indices = [index % len(targets) for index in range(lo, hi)]
state.begin_step((hi - lo) // train_batch_size)
model.forward_backward(
inputs=copy_inputs([targets[index] for index in indices]),
gradient_accumulation_steps=1, temperature=temperature, **batching,
)
state.before_optimizer_step()
model.clip_grad_and_step(max_grad_norm=state.max_grad_norm, gradient_accumulation_steps=1)
state.record_rollout_training(indices)
state.rollout_memory_metrics()
state.end_step(save=ckpts.save)
sync() # the next rollouts come from the updated policy
print(f'step {state.global_step}: reward={summary}')
if state.reached_max() or state.should_stop():
break
finally:
# TEARDOWN in fixed order: close the driver and return the lent devices first (a cleanup
# error must not mask a training exception), then close the tracker, save the final
# checkpoint and release every actor the cluster owns.
state.stream_stats = close_driver_preserving_error(driver)
reclaim()
state.handler.on_train_end()
ckpts.final()
finally:
finalize_rl_resources(state, resources=resources, remote_run=False, driver=driver, recipe='GRPO-example')
print(f'GRPO finished: {state.global_step} optimizer steps; checkpoints under {OUTPUT_DIR}')
if __name__ == '__main__':
main()四个定制点对应四类常见修改:
- 换 loss:使用 twinkle 内置变体时修改
RLConfig(loss_type=...);自定义 loss 时继承GRPOLoss,用register_loss注册,再model.set_loss('my_grpo', ...)替换。 - 换 advantage:
advantage_estimator选择内置估计器 rloo,remax,gpg 等;自定义时继承GRPOAdvantage覆写_per_sequence,构造后赋给advantage。仅修改归一化方式时无需定义类,直接构造GRPOAdvantage(scale_rewards='none', ...)。 - 换 reward:
RewardConfig(orm=[...])接受规则名,RewardRule子类或奖励模型 id;多个 reward 的权重用orm_weights。注册方式为@PluginRegistry.register('reward', 'my_reward')。 - 改更新节奏:循环中
optimizer_batch_slices决定一次 optimizer update 使用的行数,clip_grad_and_step前后是插入自定义逻辑的位置。
该脚本未包含 recipe 中的 DP 负载均衡,动态采样,轨迹过滤,周期日志,保存与恢复。需要这些能力时复用 swift/dev/recipe/policy/run_policy.py 中的对应函数,或调用 run_policy(configs)。
🌍 local,ray,训练服务:同一份代码仅修改一处配置
上面的脚本只有一处与执行方式有关:DistributedConfig(mode=...)。三种形态下其余代码完全相同:
# local:当前进程持有 GPU。单卡直接使用 python 启动,多卡使用 torchrun --nproc_per_node=2 启动。
DistributedConfig(mode='local', backend='hf', nproc_per_node=2)
# ray:训练模型与采样器是 Ray actor,当前进程仅执行调度。nproc_per_node 必填,不从环境变量读取。
DistributedConfig(mode='ray', backend='hf', nproc_per_node=2)
# remote:twinkle-server 持有模型与采样器,当前进程是单进程 driver,不设置 nproc_per_node。
DistributedConfig(
mode='remote', backend='hf',
server_base_url='http://127.0.0.1:8000', # gateway 根地址,不带 /api/v1
server_api_key='<服务端签发的 token>', # 未启用认证时可省略
)直接运行时的改动清单:
- local → ray:只修改
mode='ray',设置nproc_per_node与CUDA_VISIBLE_DEVICES。安装 Ray 依赖后用python启动,不使用 torchrun。 - ray → remote:修改
mode='remote',设置server_base_url与server_api_key,去掉nproc_per_node。在线 RL 另有两处:RolloutConfig(sampler_mode='disaggregated')或不填(服务端采样器独占设备,没有共卡时的设备释放与回收流程);rollout_sampler保持默认的vllm(服务端采样接口目前只有 vLLM)。服务端先按训练服务(twinkle-server)启动,客户端需要ms-swift,两端的twinkle与twinkle-client版本要匹配。 - remote / ray → local:仅适用于不含在线采样的训练。SFT,DPO 这类训练与推理可以
mode='local';GRPO,PPO 等在线 RL 只在 ray 与训练服务下运行,mode='local'在校验阶段被拒绝。
三端一致的原因在于组件接口与执行方式无关:forward_backward,sample,sync_weights 在三种形态下签名相同,区别只在组件内部如何分发。因此自定义组件也须遵守同一规则:跨进程或服务边界的组件配置只传可序列化的规格,注册名或可导入的类名,不依赖客户端对远端模型内部对象的直接访问;自定义插件必须在执行侧可加载,客户端进程内的 monkey patch 不构成远端组件实现。远程接口有独立的能力边界,本机可用的参数组合不表示服务端同样支持,非法组合由配置校验拒绝。
🌍 不同扩展类型的实现位置
- 仅修改实验参数:使用 CLI 或 Config,不修改底层组件。
- 组合现有组件:在 TrainBench 画布上连线,或用
code_component节点接入一段自定义计算。 - 新增奖励,loss,模板或其他已支持的扩展点:实现插件,通过注册名选择。
- 修改算法或训练步骤:按上文方式在自定义循环中组合组件,复用数据,日志和保存能力。
- 多个算法都需要的执行能力:实现为可复用组件或 twinkle 机制,避免各 recipe 重复实现。