🎯 Online Reinforcement Learning Explained
📖 Background
PPO-style RLHF has to maintain four sets of weights at the same time: the policy model, the reference model, the reward model, and the value model. Training the value model is sensitive to hyperparameters and costly in GPU memory and tuning. From 2024 to 2025, offline methods such as DPO avoided online RL by regressing on fixed preference pairs. GRPO, proposed by DeepSeekMath, removed the value model and replaced the reward model with rule-verifiable rewards, lowering the hardware threshold of RL training to a few GPUs. R1 verified the benefit of online training on this basis: the model learns on its own sampling distribution, the training signal covers paths of recovering from mistakes, while offline data provides only fixed correct paths.
The first half of this page covers the algorithm: the make-up of the GRPO objective and its known biases, what each 2025 variant changed, importance-sampling correction for training-inference mismatch, and MoE routing replay. The second half presents training regression curves, engineering constraints, and hyperparameter and reward design experience.
🎯 The GRPO principle
GRPO samples G replies for each prompt, with rewards R_1 to R_G. It uses the mean reward of the other replies in the group as the value baseline, and the advantage is
A_i = (R_i - mean(R_1..R_G)) / (std(R_1..R_G) + δ)All tokens of a reply share the same A_i. The objective keeps the clipped form of PPO and adds a KL penalty against the reference policy:
r_t = π_θ(token_t | history) / π_old(token_t | history)
L = -Σ_i (1/|o_i|) Σ_t min(r_t * A_i, clip(r_t, 1-ε, 1+ε) * A_i) + β * KL(π_θ || π_ref)The KL term uses Schulman's k3 estimator, of the form exp(logπ_ref - logπ_θ) - (logπ_ref - logπ_θ) - 1. It is non-negative, low-variance, and needs only the logp on sampled tokens.
Three terms in the objective need attention in implementation and tuning.
The denominator of the ratio is π_old, not π_ref. π_old is the weight at sampling time, and π_θ is the weight being updated. In synchronous training where a batch is updated only once, the two are equal, r_t is always 1, and clipping never triggers. In the logs clip_ratio is 0 and the loss is close to 0. This is normal for strictly on-policy training. r_t deviates from 1 only when the same batch is updated multiple times or there is a delay between sampling and training.
std normalization introduces a length bias. The loss of a reply is averaged over tokens by 1/|o_i|, and the advantage is then normalized by std, so the longer the reply, the smaller the gradient per token. Dr. GRPO points out that this bias makes the model tend to lengthen wrong replies and shorten correct ones, and gives a fix that removes std normalization and length normalization. The effect is especially obvious on math tasks, where a wrong reply is usually one that starts to go astray midway through the reasoning.
β decides how much room the model has to drift from the reference policy. When β is too large the model updates slowly. When it is too small the model drifts into the flaws of the reward function. R1 uses β for constraint in the early phase of training and removes it later. GSPO sets β to 0 by default, and the constraint is carried by sequence-level ratio clipping.
🎯 Variants
Most variants after GRPO change only one thing. Grouped by what they change:
| Variant | What it changes | The change |
|---|---|---|
| Dr. GRPO | Length bias | Removes std normalization and length averaging |
| DAPO | Exploration decay and noise | Raises the clip upper bound to 0.28, drops all-correct and all-wrong groups, token-level loss, soft penalty on overly long samples |
| GSPO | Unstable MoE training | Computes the ratio at sequence level, shrinks ε to 3e-4 |
| CISPO | Clipping discards the gradient of high-advantage tokens | Clips the IS weight and detaches it, keeps the gradient direction, upper bound can be set to 5 |
| RLOO | Group mean as baseline is biased | Uses the mean of the other leave-one-out replies as the baseline |
Clip-higher: DAPO changes the clip range to an asymmetric [1-ε_low, 1+ε_high], with ε_low 0.2 and ε_high 0.28. The ratio of a low-probability token easily reaches the upper bound 1.2, and once clipped it no longer gets an exploration gradient. The expert outputs of an MoE structure have high variance, so clip-higher and dynamic sampling are usually used together.
Dynamic sampling: when all replies in a group are correct or all are wrong, std is 0 and the advantage is 0. The group produces no gradient but consumes compute. DAPO keeps sampling until the batch has enough valid groups. In a 50-step run on a 122B model, the mean of advantage/zero_rows was 0.76, that is, three quarters of the groups produced no signal. That ratio is close to 1 both early in training (all wrong) and late (all correct), and only the middle phase has a higher share of valid samples. Throughput estimates need to count this overhead.
Sequence-level ratio: GSPO takes the geometric mean of the log-ratio over the whole sequence before clipping. The expert selection of an MoE is sensitive to tiny perturbations in bf16, the token-level ratio is noisy, and the sequence level is more stable. The cost is that ε has to shrink from 0.2 to the order of 3e-4, because the variance of the sequence-level ratio is itself smaller.
The CISPO detach: standard PPO clipping cuts off the gradient when the ratio goes out of bounds. MiniMax observed that what gets cut off is often the key tokens with a higher advantage. CISPO uses the clipped ratio as a weight rather than a differentiable term. The gradient direction is kept, the weight has an upper bound, and ε_high can be set to 5.
The changes above are mutually orthogonal. The implementation splits them into independent switches: loss normalization, clip lower and upper bounds, whether to drop zero-variance groups, ratio granularity, and handling of overly long samples. When reading about a new variant, first check which of these five it changes.
🧪 Training-inference mismatch and importance-sampling correction
GRPO assumes that the sampling policy and the training policy are the same model. That assumption does not hold once vLLM is used for sampling: the weights are fully synced, but the operator implementations and precision differ, so π_vLLM(y|x) ≠ π_θ(y|x). The difference is small on a single token and accumulates token by token over a long sequence.
GSPO decomposes the actual ratio into two factors:
π_θ(y_t) / μ(y_t) = [π_old(y_t) / μ(y_t)] × [π_θ(y_t) / π_old(y_t)]
└── training-inference difference ──┘ └── policy lag ──┘μ is the policy of the inference engine. In synchronous training the second term is 1 and the first is not, and the first is not removed by weight sync.
The fix is importance-sampling correction: multiply the loss by w = π_θ / μ so that the expectation returns to the training policy. When w is too large the gradient variance explodes, so it has to be controlled. Truncation limits w to [0, τ]: the sample is kept but its influence is bounded. Masking discards tokens or sequences whose w exceeds τ. Granularity is token level or sequence level, giving four combinations in total. In synchronous training with a small ε the difference is small, and training works without correction. In asynchronous training or on MoE models, the cost of not correcting usually shows up dozens of steps later as a grad_norm spike.
Two metrics decide whether to turn on correction: rollout_correction/k3_kl (the KL between the training policy and the sampling policy) and is_weight_mean with ess (the mean of the importance weights and the effective sample size). In the 122B synchronous training below, k3_kl stayed between 4.6e-4 and 6.8e-4 throughout with no grad_norm spike, and at that magnitude no correction is needed. The rule of thumb is 1e-3: if k3_kl stays above that value, or if ess falls below one third of the sample count after correction is turned on, it needs attention.
🔁 MoE routing replay
MoE models have an extra source of training-inference mismatch: expert routing. The router computes a softmax for each token and selects the top-k experts. When router logits are near a critical value, the numerical difference between the training engine and the inference engine in bf16 flips the expert selection. The same token passing through different experts gives completely different hidden states, and the difference is far larger than in a dense model.
Router Replay forces the training forward to use a fixed routing mask, computing the softmax only over the experts inside the mask, and the gradient still propagates to the router weights. R2 replays the routing computed by the training engine for the old policy, which removes the routing drift caused by policy lag but does not remove the training-inference difference. R3 replays the routing recorded by the inference engine at sampling time, which removes the training-inference difference at the source. It needs the inference engine to export the expert index per layer per token, supported on vLLM 0.14 and above.
Measurements give the applicability boundary. On the 35B-A3B model, with LoRA trained only on the attention layers and expert weights and router weights unchanged, R2 replay gives no difference from recomputing the routing, and routing replay is wasted overhead. The scenario where R2 helps is when experts or the router take part in training (full-parameter or all-linear LoRA). With R2 on the same model for 15 steps, reward rose from 0.59 to 0.975 and grad_norm stayed between 0.0006 and 0.047. The replay itself does not affect training stability.
📈 Training curves
The following data comes from training regressions on 4 and 8 H20 GPUs.
🎯 122B-A10B, 50 steps
Qwen3.5-122B-A10B, math task, LoRA, lr 5e-5. Startup took 27.8 minutes, 50 steps took 436.5 minutes in total, and the steady state is 492.7 seconds per step (minimum 444, maximum 594). Mean reward and completion_length per 5 steps:
| Steps | 1–5 | 6–10 | 11–15 | 16–20 | 21–25 | 26–30 | 31–35 | 36–40 | 41–45 | 46–50 |
|---|---|---|---|---|---|---|---|---|---|---|
| reward | 0.180 | 0.598 | 0.738 | 0.840 | 0.850 | 0.896 | 0.952 | 0.844 | 0.829 | 0.820 |
| completion_length | 7696 | 6431 | 5443 | 4554 | 4337 | 3872 | 3107 | 3241 | 3216 | 3059 |
First-step reward 0.057, last step 0.932, maximum 0.984. While reward rose, completion_length fell from 7696 to 3059: the model learned to reach the correct answer with shorter reasoning, the typical gain curve of RL on math tasks. Reward peaked in steps 31 to 35 and then fell back to 0.82, while length stayed basically unchanged. The fall-back is not model degradation. It more likely comes from prompt sampling variance: each step has one to two hundred replies, and the 5-step reward mean still has a sampling variance above 0.1. Judging a trend needs at least 20 steps.
Stability metrics: approx_kl stayed between 3.2e-4 and 1.1e-3 throughout, clip_ratio peaked at 4.5e-4, the share of tokens whose ratio left the clip range was below one thousandth, and grad_norm never exceeded 0.021. All are in the safe range, and lr 5e-5 suits LoRA training at this scale. trainer_idle_ratio averaged 0.355: the trainer spent one third of its time waiting for sampling, the typical ratio when sampling and training are on separate GPUs. Lowering it needs more sampling GPUs or turning on asynchrony.
🎯 Variance in small-scale training
4B and 35B-A3B trained with GRPO on 4 GPUs, 2 prompts per step. Reward went from 0.5 to 0.96 with large fluctuations in between. The fluctuation comes from sampling variance over 16 replies from 2 prompts and is not convergence. Re-running with the same configuration gives a different curve shape over the first 10 steps. Small-scale training needs three observations: whether the multi-step moving mean of reward trends up, whether completion_length shortens or grows abnormally, and whether grad_norm has spikes. The absolute value of a single-step reward carries no information.
🛠️ Engineering constraints and pitfalls
- For MoE LoRA, list
target_modulesexplicitly (attention projections) and do not use all-linear. Expert layers packed into a 3D tensor also get wrapped into the adapter, and the adapter size and the weight sync overhead on the sampling side grow out of control. - Compute the five blocks of GPU memory before starting: weights, optimizer state, gradients, activations, and KV cache. When no memory is left for the sampling-side KV cache, vLLM refuses to start outright (
No available memory for the cache blocks). Add TP or lower the memory utilization and the maximum length. When the master weights do not fit on a single GPU on the training side, shard with FSDP2. A framework rejecting an infeasible configuration at startup is the correct behavior. Do not bypass it. - The time limit of a reward function must be enforced from outside the reward process: put the verifier in a persistent subprocess with a hard wall-clock timeout. On timeout record 0 and write a log.
signal.alarmdoes not fire in a non-main thread of a Ray worker and cannot be used as timeout protection. - Keep one precision path: the forward of fp32 master weights (as in the PPO critic) has to go through autocast before entering FlashAttention. When NaN shows up in the bf16 backward, fix the data and seed, then swap attention implementations to bisect the problem.
- The k3 surrogate gradient contains the exponential term
exp(teacher_logp - student_logp), which amplifies tokens where teacher and student disagree strongly, and the lr tolerance is narrower than the JSD form. When grad_norm spikes, lower the lr first, then check for overly long or empty samples.
📚 Hyperparameter and reward design experience
- Start from an Instruct model rather than a base model: the format reward is satisfied faster, and RL is only responsible for pushing up accuracy. A base model should go through SFT first to learn the format and the chat template before RL.
- Length is cost: the larger
max_completion_lengthand the sampling-side maximum model length, the higher the GPU memory and the slower each step. Step time is roughly linear in the maximum generation length. Set the cap by task difficulty and monitorclipped_ratio. - Plan training with two formulas: total batch = process count × per-GPU batch × gradient accumulation. Total steps = epochs × data size ×
num_generations÷ total batch. Set the lr schedule and warmup by total steps. - lr and the KL weight beta are twin stability knobs: the larger, the faster the convergence but the more prone to oscillation. A usable starting point for math tasks is lr 5e-7 and beta 1e-3. lr 1e-6 with beta 0.04 once produced an oscillation at about 200 steps where reward and the format score dropped sharply. beta is a construction argument of the GRPO loss (
set_loss('grpo', beta=...)). When oscillating, lower both together. - Layer the reward function: use the built-in
formatfor the format reward and a custom ORM plugin for task correctness. Arguments other than completions are passed through by dataset column name, so a task change only touches the dataset and the reward. Record 0 on parse failure or exception instead of raising and aborting the whole batch. - Read the curves: a
reward_stdthat does not converge over the long run means there is still room to improve. A highfrac_reward_zero_stdmeans the prompt difficulty does not match the current model. Acompletion_lengththat first falls and then rises is usually a change of thinking strategy rather than degradation. For metric definitions see "Monitoring metrics and evaluation".
🌐 Deployment layouts and per-step time
The per-step time of GRPO consists of three parts: sampling, training, and weight sync. The deployment layout decides how the three overlap.
35B-A3B on 4 H20 GPUs. With training and sampling on shared GPUs (colocate: offload the optimizer during training, put vLLM to sleep and wake it up for sampling) the full cycle takes 40.9 seconds per step. With 2 GPUs each for sampling and training, 19.9 seconds per step. With sampling and training on different nodes and remote weight sync, 27.1 seconds per step. The shared-GPU setup is twice as slow because every step has to move weights between the two roles and pay the fixed cost of sleep and wake-up, not because compute is reduced.
A common statistical mistake is comparing the pure compute time of the trainer with the full-cycle time of another system. On 4B the trainer compute is 1.12 seconds per step and the full cycle of one colocate implementation is 26.7 seconds. Dividing directly gives 24x. The two numbers measure different things. When comparing, use the full cycle or the pure compute segment for both, and state whether sampling and sync are included.
⏱️ Asynchrony and data freshness
In synchronous training, training starts only after sampling finishes. The sampling GPUs are idle during training, and the training GPUs are idle during sampling. Asynchrony overlaps the two, at the cost that the training data comes from an older weight version.
one_step_off samples one batch ahead, with a fixed version gap of 1. fully_async samples continuously and training takes the latest available data. The version gap fluctuates with the speed ratio of sampling to training and is capped by max_staleness.
Metrics for judging the benefit of asynchrony: policy_version (the weight version number of the training data), version_span_mean (the mean span of version numbers within one batch), partial_ratio (the share of batches that are incomplete because of a timeout), and dropped_stale (the amount of data dropped for being too old). In the 122B synchronous training, policy_version went from 1 to 50 adding one per step, and version_span_mean, partial_ratio, dropped_stale, and no_slot were 0 throughout, the normal shape for synchronous mode. After turning on asynchrony, if version_span_mean exceeds 2 or dropped_stale grows, sampling is slower than the training consumption rate, and the speed-up from asynchrony is offset by stale data.
📏 Monitoring metrics and evaluation
Reward: the moving mean of reward, each reward component, reward_std, and frac_reward_zero_std. A high value of the last one means the prompt difficulty distribution does not match the current model.
Length: the mean of completion_length and clipped_ratio. When length drops sharply and reward falls, check whether the reward is being gamed. When length grows sharply and clipped_ratio rises, check whether max_completion_length is too small.
Stability: grad_norm, approx_kl (relative to the reference policy), clip_ratio, and lr. When grad_norm spikes, first check the data for overly long or empty samples, then check the lr.
Efficiency: trainer_idle_ratio, advantage/zero_rows, and per-step time broken down into sampling, training, and sync.
Evaluation uses a held-out task set with fixed sampling temperature and maximum generated tokens, scored by the same scorer as in training. A training-set reward of 0.95 does not mean the held-out score reaches 0.95. The gap depends on the coverage of the prompt set.
The following code comes from examples/v5/rl/grpo/grpo.py. The script writes the four stages of rollout, scoring, advantage, and update in one loop, and each stage maps to one replaceable component: the loss is the twinkle Loss selected by model.set_loss, the advantage is a GRPOAdvantage instance, the reward is a rule name listed in RewardConfig(orm=[...]), the update is forward_backward plus clip_grad_and_step, and placement is decided by RolloutConfig.sampler_mode and DistributedConfig.mode.
🛠️ Configuration
from swift.dev.config import (
CheckpointConfig, DatasetConfig, DistributedConfig, GenerationConfig, LoggingConfig, ModelConfig,
RewardConfig, RLConfig, RolloutConfig, TemplateConfig, TrainConfig, TunerConfig,
)
from swift.dev.recipe.configs import RecipeConfigs
def build_configs() -> RecipeConfigs:
return RecipeConfigs(
model=ModelConfig(model='Qwen/Qwen3.5-4B', task_type='causal_lm',
torch_dtype='bfloat16', attn_impl='flash_attention_2'),
# system matches the requirement used at data generation time: the reply must contain \\boxed{}
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']), # the solution column is read by the reward rule
# per_device_train_batch_size x gradient_accumulation_steps x dp = number of trajectories per update
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),
# Online RL has only two execution modes, ray and remote; there is no local
distributed=DistributedConfig(mode='ray', backend='hf', nproc_per_node=2),
checkpoint=CheckpointConfig(output_dir='output/grpo-component', add_version=False,
save_steps=100, save_total_limit=2),
# For MoE models, list ['q_proj', 'k_proj', 'v_proj', 'o_proj'] explicitly instead of all-linear
tuner=TunerConfig(tuner='lora', lora_rank=8, lora_alpha=32, target_modules=['all-linear']),
logging=LoggingConfig(report_to=['tensorboard'], logging_steps=1),
# num_generations is the group size G, beta is the KL weight against the reference policy, and epsilon is the clip range
rl=RLConfig(rl_type='grpo', num_generations=8, advantage_estimator='grpo',
epsilon=0.2, beta=0.04, max_completion_length=2048),
reward=RewardConfig(orm=['accuracy']), # a registered rule name, a RewardRule subclass, or a reward model id
# colocate: training and sampling share GPUs and switch by stage; disaggregated: separate GPUs
rollout=RolloutConfig(sampler_mode='colocate', vllm_gpu_memory_utilization=0.5),
generation=GenerationConfig(temperature=1.0),
)How the configuration items map to the experience above: sampler_mode corresponds to the deployment layout section. The per-step time difference between shared and separate GPUs is switched by this item. vllm_gpu_memory_utilization and nproc_per_node correspond to the GPU memory budget section. Sampling-side TP and utilization and the training-side sharding follow from them. target_modules corresponds to the MoE section, attn_impl to the attention kernel section, and num_generations=8 with max_completion_length to the metric definitions of the dynamic sampling and length monitoring sections.
🎯 Training loop
from swift.dev.builder import build_prompt_dataloader
from swift.dev.builder.optimizer import resolve_max_grad_norm
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.batching import optimizer_batch_slices
from swift.dev.recipe.utils import initialize_rl_devices, prompt_rows_from_dataset
from swift.dev.utils.scoring import copy_inputs
configs = build_configs()
train, rl, rollout = configs.train, configs.rl, configs.rollout
max_grad_norm = resolve_max_grad_norm(train)
# Data: the prompt rows of the dataset with assistant turns removed, plus the label column read by the reward rule (solution)
prompt_rows, prompts, extras = prompt_rows_from_dataset(configs.dataset, system=configs.template.system)
# Devices: start the runtime and estimate the placement of trainer, sampler and reference; in ray mode this process does no GPU compute
template, resource_plan, meshes = initialize_rl_devices(
configs, output_dir=OUTPUT_DIR, prompt_rows=prompt_rows,
group_requests=lambda: policy_group_requests(configs))
# Components: trainer (loss, optimizer and LR schedule attached), sampler, weight sync engine,
# reference, reward scorer and advantage estimator
resources = build_policy_objects(configs, template, max_steps=train.max_steps, batch_size=batch_size,
resource_plan=resource_plan, auxiliary_meshes=meshes)
model, sampler, reference, advantage = resources.model, resources.sampler, resources.reference, resources.advantage
colocate = resources.colocate
# Flow: prompt dataloader -> streaming driver; each iteration yields one batch of trajectories and scores
dataloader = build_prompt_dataloader(prompts, extras, seed=configs.dataset.data_seed, batch_size=generation_batch_size)
driver = build_policy_driver(resources, configs, prompt_dataloader=dataloader, batch_size=batch_size)
publish_policy(resources.engine, rollout, colocate=colocate) # the initial weights enter the sampler
for rows, facts in driver: # 1. rollout + scoring: facts['scores'] comes from RewardConfig
if colocate:
reclaim_training_devices(model, sampler, rollout) # shared GPUs: GPU memory is handed back to the trainer after sampling
ref_out = None
if reference is not None: # 2. reference logp: read by the KL term
ref_out = reference.forward_only(
inputs=copy_inputs(rows), output_frame='response', output_fields=('logps',),
temperature=temperature, micro_batch_size=micro_batch_size,
**({'disable_lora': True} if reference is model else {})) # disable the adapter when LoRA has no separate ref
targets, summary = advantage(rows, ref_out=ref_out, scores=facts['scores'], global_step=global_step) # 3. A_i
for lo, hi in optimizer_batch_slices(len(targets), train_batch_size, ga): # 4. update
model.forward_backward(inputs=copy_inputs(targets[lo:hi]), gradient_accumulation_steps=ga,
micro_batch_size=micro_batch_size, temperature=temperature)
model.clip_grad_and_step(max_grad_norm=max_grad_norm, gradient_accumulation_steps=ga)
global_step += 1
publish_policy(resources.engine, rollout, colocate=colocate) # 5. weight syncHow the loop maps to the metrics: facts['scores'] is the source of the reward components. summary['zero_advantage_rows'] is advantage/zero_rows, where all-correct or all-wrong groups are counted. summary['rollout_correction'] is the source of the rollout_correction/* metrics. When reference is None, beta must be 0, otherwise the KL term has no input. publish_policy is the weight sync segment of the per-step time. In asynchronous mode, metrics such as version_span_mean are recorded by the driver when it produces a batch. In the 122B training trainer_idle_ratio was 0.355, which is the time for rows, facts in driver spends waiting for sampling to return.
🎯 Variant switches
The changes between variants are mutually orthogonal. At the component level, the change is replacing the loss class or the advantage estimator, and the loop stays the same. set_loss accepts a registered name and construction arguments, which are passed through Ray to the worker that holds the model. The equivalent configuration-level form is RLConfig(loss_type=..., epsilon_high=...):
# DAPO: clip upper bound relaxed to 0.28, KL removed; token-level aggregation is bnpo
model.set_loss('bnpo', epsilon=0.2, epsilon_high=0.28, beta=0.0)
# GSPO: sequence-level ratio, epsilon shrunk to 3e-4; 'gspo' is an alias for importance_sampling_level='sequence'
model.set_loss('gspo', epsilon=3e-4, beta=0.0)
# CISPO: the clipped IS weight is detached and multiplied onto the policy gradient, upper bound 5
model.set_loss('cispo', epsilon=0.2, epsilon_high=5.0)
# Dr. GRPO: removes std normalization (scale_rewards='none'), loss normalized by batch x max_completion_length
from twinkle.advantage import GRPOAdvantage
from swift.dev.builder.streaming import CONTROL_GROUP
advantage = GRPOAdvantage(num_generations=rl.num_generations, scale_rewards='none', remote_group=CONTROL_GROUP)
model.set_loss('dr_grpo', epsilon=0.2, beta=0.0, max_completion_length=rl.max_completion_length)Correction for training-inference mismatch is switched on the loss as well: GRPOLoss(rollout_importance_sampling_mode=..., rollout_importance_sampling_threshold=2.0) controls token-level or sequence-level truncation and masking, and log_rollout_offpolicy_metrics=True outputs the rollout_correction/* metrics. In synchronous training, keep it off while rollout_correction/k3_kl stays below 1e-3.
To write a custom aggregation: inherit GRPOLoss, override _aggregate_loss or _compute_per_token_loss, register with @register_loss('my_grpo'), and select it with model.set_loss('my_grpo', **kwargs). The within-group baseline of the advantage lives in GRPOAdvantage._per_sequence. Override that method to replace the baseline.
🏅 Reward rules and timeouts
A reward rule inherits RewardRule. __call__ receives a batch of trajectories and returns a list of floats of the same length. self.completion(traj) returns the text of the latest assistant message. After registration, it enters RewardConfig(orm=[...]) by name, or the class object can be put into the list directly:
from typing import Any, List
from swift.dev.reward.reward import RewardRule
from swift.dev.utils.plugin import PluginRegistry
from twinkle.reward.gsm8k import _HardTimeoutMathScorer
@PluginRegistry.register('reward', 'boxed_accuracy')
class BoxedAccuracy(RewardRule):
def __init__(self, args=None, timeout: float = 5.0, **kwargs):
super().__init__(args) # plugins are all constructed as cls(args=...), where args is the Config of the current run
# verification runs in a persistent subprocess with a wall-clock limit per call; arguments are serialized by Ray to the reward worker
self.scorer = _HardTimeoutMathScorer(timeout=timeout, precision=1e-6, try_extract_without_anchor=True, tail_chars=0)
def __call__(self, trajectories: List[Any], **kwargs: Any) -> List[float]:
scores = []
for traj in trajectories:
completion = self.completion(traj)
gold = self.column(traj, 'solution') # dataset label column; it does not enter the prompt visible to the student
if '\\boxed' not in completion:
scores.append(0.0) # a reply without a conclusion does not go to the verifier
continue
scores.append(1.0 if self.scorer.score(completion, gold) else 0.0) # a timeout returns None, counted as 0 in this example
return scoresThe structure of _HardTimeoutMathScorer corresponds to the reward timeout constraint in "Engineering constraints and pitfalls". Verification runs in a subprocess started with mp.get_context('spawn'). The parent process sends (completion, gold) over a Pipe, then _conn.poll(self._timeout) waits for the result. On timeout, _kill_worker terminates the subprocess and rebuilds it on the next call. That entry returns None (no signal, not counted as 0) and writes a warning log. signal.alarm does not fire in a non-main thread of a Ray worker and cannot be used in this scenario.
🔗 References
For training scripts see examples/v5/rl/grpo. For timing and regression data see Performance. For the offline-path counterpart see Offline distillation.
⚗️ Offline Distillation Explained
The distillation principle from one-hot labels to the teacher distribution, the trade-off between output distillation and logits distillation, the engineering constraints of each stage of the offline distillation data pipeline, and an analysis of a set of training regression curves.
🤖 Agentic Training
Multi-turn online RL - per-sample scheduling in StreamingDriver, heterogeneous placement and colocate, four kinds of env, harness, the ORM/PRM reward channels, portability across Ray and the training service, automatic resource scaling, and a complete AgentENV RL program.