๐งฉ Components and M/P Separation
The ms-swift command line is not the only entry point. Users can call training recipes directly, reuse the model, data, sampling, loss and reward components to write their own training loop, or drag components onto the TrainBench canvas, connect them and run. All three entry points end up using the same set of components: the low-level components come from twinkle, and ms-swift handles model and data adaptation, config parsing and the assembly of common training loops.
This page introduces Mechanism / Policy separation (M/P separation): algorithm decisions are separated from system execution so that algorithm changes, component replacement and distributed placement stay as independent as possible. Policy refers to decision logic in software design and is not limited to the policy model in reinforcement learning. The page then lists the roles and inputs/outputs of the two component kinds, code components and TrainBench drag-and-drop components, uses a component-based GRPO training script to show how to replace loss, advantage and reward, and finally describes the config changes the same code needs across the three execution modes: local, ray and the training service.
Blue stands for configuration and control, green for the training data flow, and dashed lines for weight sync. The command line, Python and the TrainBench canvas share ms-swift's Config, builders and recipes; twinkle components hand computation to infra. infra has three forms: local, ray and the training service. Switching forms only changes the execution config; component code stays the same.
๐ Principles and boundaries
A single training loop contains two different kinds of questions:
- Policy: which objective to choose, how to prepare samples, whether to sample or update first, how to compute advantage, and when to record metrics or save the model.
- Mechanism: which devices and processes the model runs on, how tensors are sharded, how calls travel across processes, how weights are synchronized, and how checkpoints are read and written.
For example, GRPO decides to "generate several answers for the same prompt and update the model from the relative rewards". That is an algorithm decision. Placing the training model and the sampler on different GPUs and syncing the updated weights to the sampler is the execution mechanism.
Config and data
โ
SWIFT recipe: select components, define the objective, organize the training loop
โ
twinkle components: model, data, sampler, loss, reward, advantage
โ
twinkle execution mechanism: device placement, parallelism, remote calls, transport, weight sync and storageA component is neither the same as Policy nor the same as infrastructure. Components such as the model, loss and reward provide reusable capabilities; the recipe decides how to combine them through configuration and call order, and the inside of a component delegates distributed execution to the corresponding mechanism.
| Layer | Responsibility | What users usually change |
|---|---|---|
| CLI / Config | Parse arguments, handle defaults, validate combinations. | Model, data, training hyperparameters and parallelism config. |
| ms-swift Builders | Turn the config into model, template, data and other components. | Component adaptation, plugin registration and how they are built. |
| ms-swift Recipe | Assemble components, define the training objective, organize the update and save flow. | New algorithms, data cadence, objective combinations and the training loop. |
| TrainBench session | Read the component registry, validate canvas connections, schedule execution by node dependencies. | Component selection and connections on the canvas. |
| twinkle components and infrastructure | Provide unified operations and their local and distributed execution. | Reusable components, parallel implementations, transport or execution backends. |
twinkle uses @remote_class and @remote_function to declare remote execution, data distribution and result collection on components, and configures the execution mode at runtime through twinkle.initialize. Domain operations are still defined on the components themselves, such as the model's forward_backward and the sampler's sample; the recipe calls these operations and does not manage actor communication details.
The point of the separation is not to spare algorithm authors from understanding distributed constraints, but to avoid reimplementing Ray actors, GPU placement and weight transport in every algorithm.
๐งฉ Components
Components come in two kinds. Code components are Python objects that are built and called directly in a script. TrainBench drag-and-drop components are nodes on the canvas; each node corresponds to one code component or a piece of recipe logic, and connections wire output ports to the input ports of downstream nodes. Both kinds have the same inputs and outputs, and a saved canvas can also be exported as code.
The data structures passed between components are listed in the table below, and the input/output columns of the two component tables further down use these names. A name refers to a single element; batches are written list[name], and for type dict the important keys are listed. Only the fields used by the main training chain are listed; see the linked source for the full definitions. trajectory is a TypedDict and is a dict at runtime: the raw dataset row, the encoded row and the sampling result have the same shape, and the only difference is which stage has filled in which fields.
| Name | Type | Important keys | Description |
|---|---|---|---|
trajectory | Trajectory, TypedDict, inherits InputFeature | Raw row: messages, tools, user_data (label columns such as solution), images / videos / audios. Added after encoding: input_ids, labels, attention_mask, position_ids. Added after sampling: response_token_ids, response_positions, rollout_logps, turns, stop_reason. rewards is added after scoring; advantages, returns, ref_logps and old_logps are added after advantage estimation (the length of a response-frame field always equals the number of response tokens). Identity: episode_id, group_key (one generation group for the same prompt), policy_version. | The unified sample structure for the whole chain, passed in batches as list[trajectory]; shown on TrainBench as list[trajectory] |
score | dict, aligned row by row with trajectory; structure in _call of advantage/base.py | rewards.orm (scorer name to score), rewards.baseline, prm_segments (optional, per-segment process scores) | Delivered by the driver together with list[trajectory] and read by Advantage; shown on TrainBench as list[score], an optional input of the select and advantage nodes |
model_output / reference_output / teacher_output / old_policy_output / value_output | ModelOutput, TypedDict, values are tensors or lists | logits, logps (per-token log probability), values (per-token values from the critic), loss, num_tokens, embeddings. When output_frame='response', also episode_ids, response_token_ids, field_frames (marks each field as response frame, whole sequence or per row) | Model forward result; contains only the fields requested through output_fields. The five names share one type and are distinguished by role: model_output is the forward result, reference_output is the reference policy's logps (for KL), teacher_output is the teacher model's output (for distillation), old_policy_output is the logps of the policy before the update, value_output is the critic's per-token values (for gae) |
loss_output | LossOutput, TypedDict | loss (scalar tensor), num_tokens (normalization denominator of the loss), channel_loss (loss components split by channel, for logging) | Return value of Loss |
sample_response | SampleResponse, dataclass | sequences: list of SampledSequence, each containing tokens, logprobs, decoded, stop_reason, new_input_feature (a single trajectory with the prompt and the generated answer concatenated); prompt_token_ids, prompt_logprobs | Return value of Sampler, one per prompt, batched as list[sample_response] |
metric | dict | values (metric name to float or None), invalid_count (number of non-finite values) | Metric summary; the return value of calculate_metric() in code, shown on TrainBench as metric |
step | dict | model_id, micro_step (confirmed backward micro steps), global_step (confirmed total optimizer steps), optimizer_steps (number completed this time), batch_id, consumed | Completion receipt of one train_step; shown on TrainBench as step |
sync | dict | parameter_version (the parameter version actually synced), receivers (list of receiver ids), confirmed (completion result of each receiver) | Completion receipt of one weight sync; shown on TrainBench as sync |
artifact | dict | path (artifact path or publication URI), format, manifest (optional) | A written model, training snapshot or report; model.save() returns path in code, shown on TrainBench as artifact |
dataset_meta | DatasetMeta, dataclass | dataset_id (ms://, hf:// identifier or local path), subset_name, split, data_slice, data (in-memory list of rows or column dict) | Dataset description; constructor arguments of Dataset |
then / after / source | No payload | None | TrainBench control ports: indicate that a preceding node has finished; source is the control handle of a resident cursor, and connecting to this port does not trigger a fetch |
๐งฉ Code components
| Category | Component | Interface | Role | Input | Output |
|---|---|---|---|---|---|
| Data | Dataset / PackingDataset | Dataset(DatasetMeta(...)) | Load a dataset from ModelScope or HuggingFace. PackingDataset concatenates several short samples into one to raise GPU utilization. | dataset_meta | list[trajectory] at the raw-row stage (with columns such as messages); supports subscripting and len() |
| Data | Dataset / PackingDataset | set_template(template, **kwargs) | Bind a template; encode renders according to it. | Template instance, class name or registered name, constructor arguments | No return; the template is bound to the dataset instance |
| Data | Dataset / PackingDataset | map(preprocessor) | Mount a preprocessor and perform row-level ETL. | Preprocessor instance, class name or callable | No return; the trajectory returned by __getitem__ has the transform applied |
| Data | Dataset / PackingDataset | encode(add_generation_prompt=False) | Encode all rows with the template. | add_generation_prompt: whether to append the assistant start token at the end; set to True for generation tasks | No return; each row gains input_ids, labels, attention_mask, position_ids |
| Data | Template | encode(sample, add_generation_prompt=None) | Render messages with the model's chat template and tokenize. | The messages of a single trajectory, or a chosen / rejected pair; add_generation_prompt means the same as above, and None means infer from the encoding purpose | Token fields (input_ids, labels, attention_mask, position_ids) of a single trajectory |
| Data | Preprocessor | __call__(rows) | Row-level ETL; SelfCognitionProcessor, AlpacaProcessor and others are built in, and custom ones can be added by subclassing. | list[trajectory] at the raw-row stage | list[trajectory]; columns may be added or removed |
| Data | DataLoader | __iter__ / __len__ / set_epoch(epoch) | Split and distribute data by DeviceMesh; handle shuffle, seed and the number of loading processes. | Dataset, batch_size, collate_fn (right padding and conversion to tensors by default) | Each __next__ delivers one batch of list[trajectory], containing only the shard of the current data-parallel rank |
| Model | Model | set_loss(loss_cls, **kwargs) | Set the training objective. TransformersModel and MegatronModel share the same interface. | Registered name (such as 'grpo'), Loss class or callable; kwargs are constructor arguments such as epsilon and beta | No return; forward_backward calls this loss |
| Model | Model | set_optimizer(optimizer_cls, lr, weight_decay) / set_lr_scheduler(scheduler_cls, **kwargs) | Set the optimizer and learning rate scheduler. | Optimizer class name or class, lr, weight_decay; scheduler class name or class, constructor arguments such as warmup_ratio; adapter_name selects the parameter group, defaulting to LoRA parameters | No return; clip_grad_and_step uses both to update parameters |
| Model | Model | add_adapter_to_model(adapter_name, config_or_dir, task=...) | Add a LoRA adapter and a task head. | Adapter name; LoRA config dict or checkpoint directory; task is the task head type | No return; the model carries LoRA parameters into forward passes and saving |
| Model | Model | forward_only(inputs=..., output_fields=..., output_frame=...) | Forward only, without accumulating gradients. | inputs: list[trajectory]; output_fields: fields to return, such as ('logps',), ('values',), ('logits',); output_frame='response': token-level fields are returned per response frame, one list per sample, otherwise whole-sequence tensors are returned | model_output, containing only the requested fields |
| Model | Model | forward_backward(inputs=..., micro_batch_size=..., gradient_accumulation_steps=...) | Forward and backward; the model splits by micro-batch internally and accumulates gradients. | inputs: list[trajectory], with training-target fields (advantages, ref_logps, etc.) already written by Advantage; micro_batch_size: rows per forward pass; gradient_accumulation_steps: number of gradient accumulation parts | model_output (loss, num_tokens, channel_loss); gradient accumulation happens inside the model |
| Model | Model | clip_grad_and_step(max_grad_norm, gradient_accumulation_steps) | Gradient clipping, optimizer update, learning rate scheduling. | max_grad_norm: upper bound on the gradient norm; norm_type: norm type, default 2; gradient_accumulation_steps: the gradient is divided by this number before the update | No return; the optimizer steps once and the learning rate scheduler steps once |
| Model | Model | calculate_metric(is_training) | Aggregate accumulated training metrics. | is_training: True returns training metrics, False returns evaluation metrics | metric, containing loss, grad_norm and the learning rate |
| Model | Model | save(name, output_dir) / load(name, output_dir) | Save and load. | Checkpoint name and output directory | save returns the path of an artifact (the artifact directory); load has no return |
| Model | Loss | __call__(inputs, outputs, **kwargs) | Training objective. model.set_loss accepts a registered name, class or callable; the registry includes cross_entropy, grpo, ppo, dpo and others. | inputs: the list[trajectory] of the current micro-batch; outputs: the model_output of the same batch (logps, etc.) | loss_output |
| Model | Metric | accumulate(inputs, outputs) / calculate() | Accumulate and aggregate training metrics, for example GRPOMetric. | accumulate receives list[trajectory] and model_output | calculate() returns metric; reset() zeroes it |
| Generation | Sampler | sample(inputs, sampling_params, adapter_name, num_samples=1) | Resident generation engine: vLLMSampler, SGLangSampler, TransformersSampler; supports loading LoRA per adapter. | inputs: list[trajectory] with the prompt encoded; sampling_params: temperature, max_tokens, etc.; adapter_name; num_samples: number of samples per prompt | list[sample_response], each with num_samples entries in sequences |
| Generation | Rollout | __call__(trajectories) / step(traj, episode_id) | Generate samples (Sample) over multiple turns through the sampler and tools inside an environment lease. | list[trajectory] with tool and environment config | __call__ returns list[trajectory] with the full multi-turn messages appended and response_token_ids, rollout_logps, turns, stop_reason written; step advances one turn and returns that turn's row and RolloutStatus |
| Generation | CheckpointEngineManager | sync_weights(merge_and_sync=True) | Sync the trained weights to the sampler. | merge_and_sync: True merges LoRA into the base model and syncs the whole weight; False syncs the base model the first time and only LoRA weights afterwards | No return; the sampler's weights are updated and policy_version moves forward |
| Algorithm | Reward | __call__(trajectories, **kwargs) | Rule-based scoring function; math, format, gsm8k and others are built in; subclass RewardRule to customize. | list[trajectory], reading messages and the label columns | list[float]; the driver writes it into rewards.orm[scorer name] of score |
| Algorithm | Advantage | __call__(trajs, scores=..., ref_out=..., value_out=...) | Advantage estimation: grpo, gae, rloo, remax, gpg and others; subclass GRPOAdvantage and override _per_sequence to customize. | trajs: list[trajectory]; scores: list[score] delivered by the driver; ref_out (reference logps for KL), teacher_out, old_out (logps of the policy before the update), value_out (critic values for gae): all model_output with output_frame='response', optional | A copy of list[trajectory] with advantages written (gae also writes returns); plus a logging dict |
๐งฉ TrainBench drag-and-drop components
The canvas registers the components in the table above as draggable nodes. Each node declares fixed input ports and output ports. While dragging a wire, the frontend only suggests valid ports, and the backend validates with the same registry, so every graph that can be built on the canvas can run. The names in the input/output columns of the table below are the port names shown on the canvas, and they match the data structures above: the trajectory port shows list[trajectory], the score port shows list[score], the metric port shows metric, and the forward port shows model_output, reference_output, teacher_output, old_policy_output or value_output by role. The payload contract is in CHANNEL_SCHEMAS of swift/dev/webui/schema.py. Nodes fall into four groups:
| Group | Node | Role | Input ports | Output ports |
|---|---|---|---|---|
| Resource | model | The only parameterized function; choose lora or full, choose the hf, megatron or unsloth backend, and declare the number of GPUs occupied and the parallelism spec. | artifact (optional, weight source) | model |
| Resource | dataset | Raw data source and preprocessing config. | None | data |
| Resource | sampler | Resident generation engine; engine selects vllm, sglang or torch. | None | sampler |
| Resource | rollout | Multi-turn generator; binds tools and the environment, and max_turns limits the number of turns. | sampler, tools (optional), env (optional) | rollout |
| Resource | sandbox_env | Sandbox environment pool; kind selects local, agentenv, openenv or openenv_client. | None | env |
| Resource | toolset | Source of tool plugins. | None | tools |
| Resource | api_endpoint | External API connection; credentials are read only from environment variables. | None | endpoint |
| Algorithm | loss | Loss object. kind selects a registered name (grpo, ppo, dpo, etc.), or define a custom formula through code. | None | loss |
| Algorithm | scorer | Scorer. kind selects a registered name (math, format, etc.), or define custom scoring through code. | None | scorer |
| Algorithm | group_rule | Whole-group admission rule, for example resampling zero-variance groups. | None | rule |
| Algorithm | code_component | Custom component; declare its own entry name, ports and side effects. | Self-declared | Self-declared |
| Algorithm | challenger | Automatic problem generator; produces question and answer trajectories for the same batch in one go. | backend, solver_rollout (optional), env, api (optional) | list[trajectory] (questions and answers), source |
| Algorithm | generate | Only generates samples (Sample); does not score or filter. | list[trajectory], engine or episode | list[trajectory] |
| Algorithm | score | Computes scores for every connected scorer and writes them back to rewards of the trajectory. | list[trajectory], scorers | list[trajectory], list[score], metric |
| Algorithm | model_forward | One standalone forward pass; outputs declares whether logps, values, logits or embeddings are wanted. | model, list[trajectory] | model_output |
| Algorithm | privileged_view | Re-encodes a teacher view from the in-row teacher_prompt; the policy's main trajectory is not written back. | list[trajectory] | list[trajectory] |
| Algorithm | advantage | Advantage estimation; estimator selects grpo, gae, rloo, etc.; gae must be connected to value_output. | list[trajectory], list[score] (optional), reference_output, teacher_output, old_policy_output, value_output (all optional) | list[trajectory], metric |
| Algorithm | select | Sample filtering; rule selects threshold, top_k or best_of_n; pairs and whole groups are not split apart. | list[trajectory], list[score] (optional), model_output (optional) | list[trajectory], list[score], model_output, metric |
| Algorithm | train_step | Runs forward_backward and the optimizer step; configures the optimizer, learning rate, scheduler, gradient accumulation and clipping. | model, loss, list[trajectory], reference_output, teacher_output, model_output (all optional; model_output has lanes channels), after (optional) | step, model, metric, then |
| Runtime | dataloader | Resident cursor; manages epochs and random seeds. source selects prompts (the last assistant message removed, for the generation side) or rows (complete training rows). | data, after (optional) | list[trajectory], source |
| Runtime | streaming_driver | Control plane of streaming sampling: sampling admission, maximum lag, backpressure and batch confirmation. Scores sample by sample when scorers are connected. | prompts, engine (optional), episode (optional), scorers (optional), groups (optional), after (optional) | list[trajectory], source |
| Runtime | weight_sync | Syncs the trained weights to the sampler; cadence sets the sync interval, and the sync is confirmed only after it completes. | model, targets, source (optional), step (optional), after (optional) | sync, then |
| Runtime | weight_average | Copy or EMA between two models. | source, target, step | sync |
| Runtime | checkpoint | Saves model weights (profile=model) or a complete training snapshot (profile=training, requires step and source). | model, step (optional), source (optional), after (optional) | artifact |
| Artifact | merge | Merges LoRA into the base weights. | artifact (model) | artifact (model) |
| Artifact | quantize | Quantizes weights; a calibration dataset can be connected. | artifact (model), calib (optional) | artifact (model) |
| Artifact | infer | Builds an inference engine from weights and runs batch inference. | model or artifact, data | list[trajectory], artifact (optional) |
| Artifact | eval | Evaluation; uses a sampler or an endpoint. | sampler or endpoint, data | metric, artifact (optional) |
| Artifact | deploy | Starts a service and waits until it is ready. | artifact (model) | endpoint |
| Artifact | hub_push | Publishes to ModelScope or HuggingFace. | artifact (model) | artifact (publication) |
There are only three rules for connections:
- Resource ports (
model,sampler,rollout,rule,env,tools,endpoint) are shared with downstream nodes along the wire. When upstream has only one resource of that kind, it is resolved automatically even without a wire; wires are used to disambiguate or to mark roles. - Data ports (
data,list[trajectory],list[score],model_output,metric,step,sync,artifact) must be wired; these wires make up the algorithm itself. Eachtrajectoryinlist[trajectory]is the same object being filled in stage by stage along the flow: raw โ encoded โ rollout (response tokens and sampling logps) โ scored (rewards) โ train_ready (advantages,returns). - Control ports (
then,source) are used only when no data edge between two nodes expresses their order. They mean "continue after completion".
Run semantics: clicking any node runs all of its preceding nodes. Nodes without dependencies run in parallel (for example, the model and the dataset are built at the same time), and nodes with dependencies run in wire order up to the clicked node. Resource-group nodes are built once per session; clicking again does not rebuild the model or dataset. The actual output of a finished node can be inspected, for example the trajectories delivered by streaming_driver, the advantage values written back by advantage, or the training receipt of train_step.
The canvas provides GRPO, PPO, RFT, OPSD, RSI, SFT, DPO, KTO, Embedding, Reranker, SeqCls and Decision scaffolds, each generating two topologies by training type (LoRA / full-parameter). After loading, nodes can be added or removed and wires can be changed, which is equivalent to changing one component or one call line in the script below. For offline algorithms, the data format is declared explicitly through the format argument of the encode node and is not inferred from the row shape.
๐ฏ Component-based GRPO training
Below is a complete LoRA GRPO script. It uses the same arguments as examples/v5/rl/grpo/grpo.sh and explicitly implements the "sample โ score โ advantage estimation โ update โ weight sync" loop. A runnable version is in examples/v5/rl/grpo/grpo.py in the source tree. First install ms-swift following Quick start, then run 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()The four customization points correspond to four common kinds of changes:
- Swap the loss: to use a twinkle built-in variant, change
RLConfig(loss_type=...); for a custom loss, subclassGRPOLoss, register it withregister_loss, then replace it withmodel.set_loss('my_grpo', ...). - Swap the advantage:
advantage_estimatorselects a built-in estimator such as rloo, remax or gpg; to customize, subclassGRPOAdvantage, override_per_sequence, and assign the instance toadvantageafter construction. To change only the normalization, no class is needed: constructGRPOAdvantage(scale_rewards='none', ...)directly. - Swap the reward:
RewardConfig(orm=[...])accepts rule names,RewardRulesubclasses or reward model ids; the weights of multiple rewards are set withorm_weights. Registration is@PluginRegistry.register('reward', 'my_reward'). - Change the update cadence: in the loop,
optimizer_batch_slicesdecides how many rows one optimizer update uses, and the lines before and afterclip_grad_and_stepare where custom logic can be inserted.
The script does not include the DP load balancing, dynamic sampling, trajectory filtering, periodic logging, or save and resume found in the recipe. When those capabilities are needed, reuse the corresponding functions in swift/dev/recipe/policy/run_policy.py, or call run_policy(configs).
๐ local, ray, training service: one config change for the same code
Only one place in the script above depends on the execution mode: DistributedConfig(mode=...). The rest of the code is identical across the three forms:
# local: the current process holds the GPUs. Start with python directly on a single GPU, or with torchrun --nproc_per_node=2 on multiple GPUs.
DistributedConfig(mode='local', backend='hf', nproc_per_node=2)
# ray: the training model and the sampler are Ray actors, and the current process only schedules. nproc_per_node is required and is not read from environment variables.
DistributedConfig(mode='ray', backend='hf', nproc_per_node=2)
# remote: twinkle-server holds the model and the sampler, the current process is a single-process driver, and nproc_per_node is not set.
DistributedConfig(
mode='remote', backend='hf',
server_base_url='http://127.0.0.1:8000', # gateway root address, without /api/v1
server_api_key='<token issued by the server>', # may be omitted when authentication is not enabled
)Change list when running directly:
- local โ ray: change only
mode='ray', and setnproc_per_nodeandCUDA_VISIBLE_DEVICES. After installing the Ray dependencies, start withpython, not torchrun. - ray โ remote: change
mode='remote', setserver_base_urlandserver_api_key, and dropnproc_per_node. Online RL has two more: setRolloutConfig(sampler_mode='disaggregated')or leave it unset (the server-side sampler owns the devices exclusively, so there is no device release and reclaim flow for shared GPUs); keeprollout_samplerat the defaultvllm(the server-side sampling interface currently supports only vLLM). Start the server first following Training service (twinkle-server). The client needsms-swift, and thetwinkleandtwinkle-clientversions on both ends must match. - remote / ray โ local: only applies to training without online sampling. Training and inference such as SFT and DPO can use
mode='local'; online RL such as GRPO and PPO runs only under ray and the training service, andmode='local'is rejected during config validation.
The three ends stay consistent because component interfaces are independent of the execution mode: forward_backward, sample and sync_weights have the same signature in all three forms, and the only difference is how the component distributes work internally. Custom components must therefore follow the same rule: component configuration that crosses a process or service boundary should only pass serializable specs, registered names or importable class names, and must not rely on direct client access to objects inside the remote model. Custom plugins must be loadable on the execution side; a monkey patch inside the client process does not constitute a remote component implementation. The remote interface has its own capability boundary: an argument combination that works locally does not mean the server supports it, and invalid combinations are rejected by config validation.
๐ Where to implement each kind of extension
- Only changing experiment arguments: use the CLI or Config; do not modify low-level components.
- Composing existing components: wire components on the TrainBench canvas, or connect a piece of custom computation through a
code_componentnode. - Adding rewards, losses, templates or other supported extension points: implement a plugin and select it by registered name.
- Changing the algorithm or training steps: compose components in a custom loop as described above, and reuse the data, logging and save capabilities.
- Execution capabilities needed by several algorithms: implement them as reusable components or twinkle mechanisms, and avoid duplicating them across recipes.
๐ Plugins
How to register and load rewards, process reward segmentation, callbacks, parameter grouping, tools, harnesses, samplers, models, chat templates, Agent templates, datasets, format converters, storage formats, loss_scale policies and losses.
๐ก Server and Client
Deploy twinkle-server, train remotely through the Twinkle client, the Tinker-compatible client or ms-swift, and manage multi-tenancy and checkpoints.