Skip to Content
MS-SWIFT ร— TWINKLE
๐Ÿงฎ Algorithms in Depth
DOCUMENTATION5.0.0.dev

๐Ÿค– Agentic Training

Agentic training is a kind of online RL: the current policy executes tasks in an environment, calling tools, reading observations, and deciding what to do next, and the trainer updates the policy from the rewards the environment returns. For the GRPO algorithm itself see Online learning. This page covers the scheduling of multi-turn rollouts, placement, environments, reward channels, and how they run on Ray and on the training service.

๐Ÿงฉ Components and data flow

Components and data flow of agentic training: Ray and the training service

Labels 1-5 above mark five logical stages: admission, multi-turn interaction, scoring and readiness, policy update, and weight sync. They do not imply serial execution. The animation illustrates asynchrony with async_mode=fully_async and sampler_mode=disaggregated: many samples advance independently, complete groups enter the ready queue, training on the previous batch overlaps with sampling new ones. The moving dashed lines show the data flow. Weights are published periodically, and the policy version gap is bounded by max_staleness.

The animation shows Ray first, then the remote training service (--mode remote). Node labels indicate where each part executes. Under Ray, StreamingDriver runs in a control CPU actor. Under the training service, scheduling, rollout, tools, and advantage estimation run in the local driver, while the model and the sampling engine run on the remote twinkle-server. The purple dashed box marks the server-side nodes. Replica adjustment and GPU lending by ClusterAdapter are optional features of Ray adaptive mode, not required steps of the asynchronous execution shown.

  • Policy: the model held by the trainer. Every turn of every sample is generated by the sampler with the current weights.
  • Tool: has a name, a parameter schema, and an execution interface. Tools come in two kinds. Shared tools (calculator, search API, etc.) live in ToolManager and each sample gets its own copy. Env tools (run_command / write_file / read_file) are bound to that sample's env session, so the model can only operate inside the sample's own workspace.
  • Env: manages a sample's working directory and the lifecycle of its process or microVM. reset opens a session, step executes a tool, close ends the session and optionally returns an environment reward.
  • Rollout (MultiTurnRollout): one step performs one turn of "generate โ†’ tool call โ†’ write observation back". It keeps a token-level record: tokens generated by the model go into labels, tokens of tool observations are set to -100, and history is never decoded and re-encoded (see token-in-token-out below).
  • StreamingDriver: reads prompts, expands each row into num_generations samples, advances them one by one, scores them one by one, and hands complete groups of batch_size rows to the training loop once they are ready.
  • Reward: ORM (outcome reward) scores a sample when it finishes. PRM (process reward) scores each closed segment. The environment can also score by itself.
  • Recipe: assembles the objects above and runs the training loop. Parallelism and remote execution are handled by twinkle, and the recipe itself is written as a single-machine program.

๐Ÿงญ StreamingDriver: scheduling per sample, not per batch

Batch scheduling generates a batch of prompts at once and waits for the slowest one to finish before training. Trajectory lengths in multi-turn rollouts vary a lot (submitting after 1 turn versus using up max_turns can differ by 10x), so waiting per batch leaves the sampler idle for long stretches. StreamingDriver schedules per sample instead:

  • Per-sample admission: the driver keeps a bounded window of (max_staleness + 1) ร— parameter_sync_step ร— batch_size rows. Whenever a slot is free it takes the next row from the dataloader and submits it immediately, without waiting for the current batch to fill up.
  • Each sample advances independently: one rollout.step is one remote call. When it returns, the completion callback puts the sample back into the event queue. The driver thread only consumes the queue, so its cost does not grow with the number of in-flight samples.
  • Scored as soon as it finishes: when a sample ends it is submitted to all ORMs. If a PRM is configured, each closed segment is scored immediately. The on_step hook can read the PRM scores and decide whether to continue that sample.
  • Handed to the training loop only when the whole group is ready: a group enters the ready queue only when all num_generations samples of a prompt have scores. __next__ takes out batch_size rows and returns them together with the metadata facts (lengths, turn counts, policy versions, and per-row aligned score columns). Under Ray the trajectories themselves are always ObjectRefs, and the driver never opens them.
  • Per-member fault tolerance: a failed sample only regenerates its own slot (up to max_group_regenerations times), and the already-scored members of the same group are kept. A member that exceeds max_staleness is dropped and regenerated on its own, without affecting the whole group. When the env has no free session, step returns a no-slot marker immediately with session_wait=0. That member retries with exponential backoff, which counts neither as a failure nor against the regeneration budget.
  • Group-level callback: on_group reads the RolloutStatus of the whole group (metadata and scores only). It can return a new trajectory set to replace the group (dynamic sampling), or return a baseline trajectory (ReMax).

The driver is the only global single point in the whole RL job, but it carries little load. It only maintains the admission window and the ready queue. In the return value of a rollout.step the trajectory is passed through as an ObjectRef (stash), the driver never opens the trajectory content, and the completion callback only puts the status back into the event queue. Routing and load balancing are done by infra, and neither the driver nor the recipe knows about replicas:

  • Sticky routing: rollout.step declares sticky_key as the sample id, so all turns of the same sample land on the same rollout replica, which holds the sample's state and TurnLedger. When rollout calls sampler.sample it passes session_id=episode_id. The sampler's sample is also declared sticky, so the multi-turn generation of the same sample lands on the same vLLM DP replica. Token-in-token-out keeps the prefix identical token by token, so the prefix cache of that replica hits directly. The binding table lives in the caller's process (LRU, expiring when idle), and bindings are rebuilt when a replica goes down.
  • Load balancing: a new key without a binding is assigned by infra to the replica with the fewest in-flight requests (_PoolView.assign). One call lands on exactly one replica and is never fanned out to all of them. --rollout_num_workers and the number of sampler DP replicas scale with the number of concurrent samples, throughput grows linearly with the number of replicas, and the driver's cost grows only with the number of completion events.

This scheduling is what async_mode is implemented on: none corresponds to max_staleness=0, where the window is only used to generate ahead; one_step_off / fully_async relax the version constraint so that the sampler keeps generating the next batch during training.

๐Ÿงญ The driver only schedules

The driver only schedules: it reads the dataloader, submits steps, submits scoring, and assembles batches. None of the following happens inside the driver:

  • Scoring: ORM/PRM are separate scorer handles (rules run in the CPU group, reward models in their own DeviceGroup), and the driver only holds Futures.
  • Advantage computation, baseline (reference logps), and dynamic-sampling regeneration all run in the training loop as separate Stages (advantage, reference.forward_only).
  • Weight sync is done by CheckpointEngineManager, and the driver only reads the version number through checkpoint_manager.version().

As a result the driver's memory and CPU usage do not depend on trajectory length, and scheduling does not stall because of a slow reward model or an advantage computation.

๐Ÿงช Training-inference consistency

The GRPO ratio is the logprob of the training policy on a token divided by the logprob at sampling time. The two terms must be computed under the same conditions. Otherwise the ratio mixes in the difference between two engines rather than a policy difference: the token sequence differs (re-encoding shifts positions), and MoE models route to different experts (the training forward re-routes, and a tiny numerical difference in bf16 is enough to send a token to another expert). We use two mechanisms to remove these two kinds of difference: token-in-token-out guarantees that the tokens trained on are the tokens returned by the sampler, and routing replay guarantees that the training forward uses the MoE routing from sampling time (--router_replay_mode R3|R2). Both work on Ray and on the training service, with one limitation on the training service: R2 is not supported.

๐Ÿงช token-in-token-out

If a multi-turn rollout re-encodes messages on every turn, the training data goes out of alignment. How the tokenizer encodes a string depends on the preceding text (BPE merge boundaries cross messages), and the whitespace produced by template rendering differs from what the model actually generated. After re-encoding, the positions of historical tokens have changed while the logprobs returned by the sampler still correspond to the old positions. Training then proceeds as usual without any error.

The implementation has two parts, policy and record-keeping. MultiTurnRollout is responsible for policy (number of turns, how tools are called, stopping condition). The tokens of each sample are recorded by TurnLedger (twinkle_agentic/rollout/ledger.py). The principle is that the tokens used for training are the tokens returned by the sampler, with no post-hoc re-encoding. Recording a sample consists of four actions:

  1. open: the only encode in the whole sample. The system prompt and the first user message are encoded by the template into input_ids (if the trajectory already carries input_ids, they are used directly). The same sample uses this one template from start to end, because two templates may handle special tokens differently and the difference would land in the middle of the trajectory.
  2. record: sampled tokens are recorded as-is. On every turn the current input_ids are handed to the sampler directly as the prompt (sampler.sample([ledger.input_feature])), and the engine continues from the token ids. The returned SampledSequence carries tokens, per-token logprobs, and new_input_feature, which is produced by Template.append_completion appending tokens to the original feature (labels follow the tokens, and one assistant message is appended to messages). The record adopts it as a whole and validates the prefix: input_ids must equal the old prefix + tokens, and the newly added segment of labels / completion_mask must be marked trainable, otherwise an error is raised.
  3. observe: tool observations encode only the increment. The tool result and the next turn's generation prompt are appended as a bridge: template.render_delta renders two texts, "existing messages" and "existing messages + new messages", and only the tokens after the common prefix are taken. A diff against tokenizer.decode(input_ids) is deliberately avoided, because whitespace differences between template rendering and model generation would make startswith alignment fail, and alignment only has to hold for the new part. The bridge's labels are set to -100 and completion_mask to 0. When the bridge does not fit (it exceeds the template's --max_length), it returns False, the record stops at the last state that fit, and the sample ends as truncated with all sampled turns kept intact. --max_trajectory_tokens is another cap: it is checked after every generation, and the sample ends as soon as it is reached, with no further tool calls.
  4. merge and audit: deliver the training view. audit requires the number of logprobs to equal the number of positions selected by (labels != -100) & completion_mask. merge outputs response_token_ids, response_positions (the scored positions under the shifted-labels contract), and rollout_logps (the old_logps of GRPO), then calls validate_trajectory. The contract is asserted where the trajectory is produced, instead of surfacing later in a training batch.

Related details:

  • Budget: the output of a single turn is limited by the sampler's max_tokens (--max_completion_length). The length of the whole sample is checked before every turn (unfit). If even the first turn does not fit, that turn's budget is capped (capped_turn_params), which yields a truncated partial reply instead of a zero-token sample.
  • Multimodal: the training-side input_ids and the engine-side engine_input_ids are recorded separately (image placeholders are projected into a different number of tokens on the engine side), and a prefix check is done for each.
  • The harness is decoupled from the record-keeping: an external agent program does not call any rollout interface. It only gets an OpenAI-shaped base URL. MultiTurnRollout opens a PolicyEndpoint for each sample, and the API key identifies the sample. Each request the program sends is parsed into an EndpointRequest and handed to that sample's TurnLedger, going through the same four actions as the tool loop: when the conversation in the request is an extension of the recorded conversation, only the increment is encoded (observe). When a reply is truncated by length and the program asks to continue after echoing it, generation continues from the current record instead of opening a new segment (_continue_generation). This is where harness independence comes from: the record-keeping does not know or care what language the program is written in, how it manages tools and loops, or whether it compresses the context. The program only has to follow the OpenAI protocol.
  • Context compression: after the program compresses the context, the request is no longer an extension of the recorded conversation, so it cannot be appended, and re-encoding would misalign. --segment_policy decides where the pre-compression record goes: drop (default) trains only on the last segment. collect freezes the current record as one row at every compression boundary (segment_index marks the segment order), the post-compression conversation starts a new record, and all rows are delivered together when the sample ends. They are encoded independently and share the same sample identity and outcome reward. The advantage is computed once per sample and broadcast to all rows, and --segment_discount can discount earlier rows. This matches the training method of Context-Folding (arXiv 2510.11967): segments before compression and the continuation after compression are both trained on. If the summary is generated by the model (through an endpoint request), it is recorded as the last reply of the segment before compression, so summary generation itself is within the training scope. Under collect, --prm is unavailable, because PRM segment accounting is per sample and does not map to multiple rows.

๐Ÿ” MoE routing replay: R3 and R2

An MoE model recomputes routing in the training forward. Numerical differences from the sampling engine (vLLM / SGLang) in bf16 are enough to send individual tokens to different experts, so the logprob computed in training is not the logprob under the routing that produced the token. Routing replay makes the training forward use the expert selection from sampling time directly. There are two modes, by where the routing comes from:

  • R3: replay the routing exported by the sampler. The vLLM engine records the top-k experts selected per layer for each token during generation and returns them with SampledSequence.routed_experts. They are written into the trajectory at record merge together with replay_mask (labels != -100 & completion_mask, only trainable tokens are replayed). The policy recipe (recipe/policy/run_policy.py, shared by GRPO and PPO as one training path) checks in _prepare_routing_replay before training that routed_experts exists for every trajectory, and raises an error if it is missing instead of degrading. The training forward consumes it with REPLAY, and the backward automatically switches to the matching replay mode. No extra forward is needed.
  • R2: replay the routing captured by the training model itself. Used when the sampler does not export routing. After weight sync, one forward_only(router_replay_mode='R2') pass is run over the whole batch of trajectories, the training model's routing under those weights is recorded into each trajectory's routed_experts, and then training proceeds. The cost is one extra full-sequence forward. With Megatron, record rebuilding under R2 raises an error outright when PP > 1 or VPP is used.

Shared constraints: --router_replay_mode is available for GRPO and PPO (both go through the same policy recipe, and validation admits them by POLICY_RL_TYPES). The policy loss of both compares the training logprob with the sampling logprob (the clipped ratio of GRPO, the clipped surrogate of PPO). Routing replay is set up once, after advantage and before the parameter update (_prepare_routing_replay), and the policy forward of every optimizer step replays the routing carried by the trajectory. The value / reference / teacher forwards do not receive this argument. The losses of other algorithms do not compare training and sampling logprobs (RFT is an SFT loss, GKD/OPSD/MOPD are KL-style distillation), and config validation rejects them explicitly instead of silently having no effect. It is mutually exclusive with --chord_sft_dataset. The model must be built with enable_router_replay=True (on the Megatron side this is translated into mcore's moe_enable_routing_replay, and in a remote deployment it is written into the model application arguments on the server). The routing tensor covers all transformer layers (including dense layers) with shape [bs, seq, layers, topk], and each backend takes the slice for its own PP / CP / SP rank.

๐ŸŒ Support under Ray and the training service

Mechanism--mode ray--mode remote
token-in-token-outSupportedSupported. Rollout runs in the client process, and HTTPSampler sends the full trajectory with input_ids to the server engine. The client rebuilds new_input_feature with the same template, and the recording logic is unchanged (requires --rollout_sampler vllm)
R3SupportedSupported. The routing exported by the sampler is sent back over the protocol and replayed on the server model. The server model must be deployed with enable_router_replay=True
R2SupportedNot supported. The workflow for capturing and collecting routing is only implemented between local actors. Under --mode remote, configuring R2 is rejected by validate with a hint to use R3 or disabled instead

๐Ÿ—บ๏ธ Heterogeneous placement and colocate: trainer and sampler are two kinds of actor

RL builds the trainer and the sampler as two independent kinds of actor, each with its own parallel layout. The trainer is described by --parallel_spec (or the dp/dp tp derived from nproc_per_node). The sampler is described by --vllm_tensor_parallel_size / --vllm_data_parallel_size (or --sglang_tp_size / --sglang_dp_size). The two can have different widths and different replica counts. The training backend can be Megatron or transformers, and the sampling engine can be vLLM or SGLang. The reward model channel has its own --orm_parallel_spec. This is what the documentation means by heterogeneous: one training loop, with no requirement that training and sampling use the same GPUs or the same sharding.

On top of that there are two placement modes:

sampler_modeGPUWeight syncStage switchUse case
disaggregated (default)Trainer and sampler occupy disjoint GPUsNCCL / sharded patchNoneEnough GPUs. Can be combined with one_step_off / fully_async
colocateSampler shares the trainer's DeviceGroupCUDA-IPCDuring rollout the sampler stays resident and the trainer is offloaded. During training the sampler sleeps and the trainer is reloadedNot enough GPUs. Requires async_mode none and parameter_sync_step 1

Switching parameters for colocate: --sleep_level (0 releases nothing, 1 unloads weights and drops the KV cache, 2 drops both) controls the sampler. --offload_model / --offload_optimizer control the trainer. The two are independent. resource_mode estimate|adaptive overrides the placement request according to the GPU memory budget: when the budget is insufficient, colocate is placed on disjoint GPUs even if requested. In code, read the actual placement through effective_colocate(rollout_config, resource_plan) rather than the request.

Whichever placement is used, weight_sync_backend decides how weights are synchronized: full transfers the full weights, and delta_sharded transfers only the changed elements (full on the first time). delta_sharded requires disaggregated placement and vLLM.

๐ŸŒ Environments: local / agentenv / openenv / openenv_client

--tools sandbox turns on the environment, --sandbox_kind selects the environment family, and the rest is controlled by --sandbox_*:

sandbox_kindWhere it runsIsolationRequired argumentsUse case
local (default)Subprocess inside the training processNone (only RLIMIT_AS and timeouts)NoneQuick validation. --sandbox_workspace_root sets the workspace root
agentenvStandalone Firecracker microVMmicroVM (KVM)--sandbox_templateReal operating-system semantics: writing files, installing packages, subprocesses, SWE-style tasks
openenvOpenEnv environment package embedded in the training processNone--sandbox_env_namePure computation environments (board games, text games), no deployment needed
openenv_clientConnects to a running OpenEnv server (WebSocket)Process / container--sandbox_env_name + --sandbox_api_url (or the environment variable OPENENV_BASE_URL)Needs to execute code but the standard library is enough. Far less resource overhead than a microVM

Common parameters:

  • --sandbox_num_envs: the upper bound on sessions held at the same time across all replicas, that is, the maximum number of concurrent samples. --sandbox_num_workers: the number of Ray CPU replicas the environment runs on, each holding ceil(num_envs / num_workers) sessions. Only Ray placement shards them. In the client process (remote) there is always one replica.
  • --sandbox_command_timeout: timeout of a single command (shared by local and agentenv). --sandbox_memory_limit_gb only takes effect on the address-space cap of local. --sandbox_timeout is the idle timeout of the agentenv sandbox.
  • --max_turns: turns on multi-turn and limits the number of turns. --max_completion_length limits the output of a single turn. --max_trajectory_tokens limits the whole trajectory. The three are independent.
  • --rollout_num_workers: the number of CPU replicas of rollout itself. Samples are routed by id to a fixed replica, which holds that sample's state. Increase it when tool execution is heavy.

Isolation boundary: local and embedded openenv do not provide security isolation against malicious code. The agentenv service itself has no authentication. A reachable port means arbitrary code execution is reachable, so it should be bound to an internal address and protected by a security-group whitelist. By default the sandbox egress blocks internal network ranges and cloud metadata addresses. The system prompt must describe the backend semantics faithfully (whether state is kept across turns, which modules are available, the turn budget). Otherwise the model writes code on wrong premises.

๐Ÿงฉ harness: let an external agent program drive the sample

In the default mode the model outputs tool calls directly and rollout executes the tool loop. --harness codex|ms_agent|<custom> switches to another mode: each sample starts an external CLI agent program in its own env session. The program sends requests to the model entry point provided by rollout (PolicyEndpoint), and rollout records every token it generates into the trajectory. The program manages tools and its loop by itself, so --harness is mutually exclusive with every --tools value other than sandbox (the environment is kept, and the program runs inside the session). --segment_policy drop|collect decides what happens to the written-out segments when the program compresses the context: they are dropped (only the last segment is trained on), or each is frozen into a row (multiple rows of the same sample share one advantage).

A harness plugin only needs to implement HarnessPlugin.build() returning a CliAgent (command and noise_reply). See Plugins.

๐Ÿ… Reward channels: ORM / PRM and environment rewards

GRPO/PPO needs at least one reward channel, otherwise the advantage of every group is NaN or zero. There are three kinds of channel, and they can be combined:

  1. ORM (outcome reward): each item of --orm can be a registered rule name (accuracy, format, repetition, soft_overlong, code_execution), a plugin name registered through --external_plugins, or a frozen reward model ID. --orm_weights weights and sums them, with equal weights by default. A model ID can be configured with --orm_task_type seq_cls (scalar head), --orm_template, and --orm_parallel_spec.
  2. PRM (process reward): --prm has the same syntax as above. It scores every closed segment and blends into the reward of each response token through --prm_orm_mix (mix ร— process + (1 - mix) ร— orm). If --prm is set and prm_orm_mix is less than 1, --orm must be set as well. How segments are split is decided by --prm_scorer turn|delimiter (multi-turn defaults to splitting by assistant turn, single-turn defaults to splitting by --prm_step_delimiter).
  3. Environment reward: the checks column of the data row runs in the same sandbox when the sample ends, before the env session is closed, and the score is written into rewards.check. The score returned by the env's own step / close is written into rewards.env (local and agentenv do not score). --env_reward_weight controls whether this kind of reward counts toward training (1.0 counts, 0.0 only records to metrics). Configuring --tools sandbox counts as already having a reward channel.

checks is programmatic verification. It does not go through a judge model, and the same trajectory always gets the same score:

{"messages": [{"role": "user", "content": "ๅœจไป“ๅบ“้‡Œๅฎž็Žฐ utils/parse.py ็š„ parse_config ๅ‡ฝๆ•ฐ๏ผŒๅนถ้€š่ฟ‡ tests/test_parse.pyใ€‚"}], "checks": [{"kind": "shell", "code": "python -m pytest tests/test_parse.py -q", "timeout": 120}, {"kind": "file_exists", "path": "utils/parse.py", "weight": 0.2}]}

Supported kind values: file_exists, file_absent, file_contains, file_equals, file_json, shell, python, answer_contains, answer_equals, answer_regex. The score is the pass ratio weighted by weight.

A successful tool execution is not the same as a completed task. Rewarding only "called a tool" encourages useless calls, and a format-only reward does not guarantee correctness either. When combining task correctness, format, and failure penalties, record each item separately and watch the reward trend, task success rate, tool error rate, trajectory length, timeouts, grad_norm, and KL. Identical rewards within a group produce zero advantage, so adjust the difficulty or the reward discrimination.

๐ŸŒ One code base on Ray and on the training service

The code of the driver, rollout, env, and scorer is exactly the same under --mode ray and --mode remote. The only difference is where they are placed:

--mode ray--mode remote
Trainer, reference model, reward modelLocal Ray actors, each occupying a DeviceGroupServed models on the training service. The training loop holds client handles
samplerLocal Ray actor (vLLM / SGLang)Engine already deployed on the server, accessed through HTTPSampler
StreamingDriverOne actor in the control CPU groupInside the client process
MultiTurnRollout / EnvReplicas in the rollout / env CPU groupsInside the client process (rollout_num_workers / sandbox_num_workers do not shard)
Weight syncCheckpointEngine (NCCL / IPC / sharded patch)Save LoRA โ†’ hand adapter_uri to the server to load

Under the training service only the parts that truly depend on the local actor structure are rejected: sampler_mode colocate, resource_mode adaptive, weight_sync_backend delta_sharded, --tuner full (the sync channel is the adapter), --sync_ref_model, router_replay_mode R2, --enable_sampling_replay, and resume_from_checkpoint for PPO. Multi-turn tools, harness, and all four kinds of environment are usable on the training service.

๐ŸŒ Code written as a single-machine program

As a result the training loop has the same shape as a single-machine program:

for trajs, facts in driver:            # iterable in the same way when the driver lives in another process
    ...
    trajs, _ = cluster.advantage(trajs, ref_out=ref_out, scores=facts['scores'])
    cluster.model.forward_backward(inputs=..., micro_batch_size=...)
    cluster.model.clip_grad_and_step(max_grad_norm=...)
cluster.engine.sync_weights()

Across processes only serializable specs, class names, and scalars are passed, and mocks/patches cannot take effect across a process boundary. This is also the premise for composing new algorithms by dragging components together.

โšก Speed optimizations and automatic resource scaling

The time of multi-turn RL is mostly spent waiting: waiting for the slowest trajectory, waiting for the env, waiting for weight sync. The scheduling layer adds the following optimizations:

  • Per-sample admission and whole-group delivery: long trajectories do not block the generation of other prompts. Groups that finish first go into training first.
  • Asynchronous window: --async_mode one_step_off|fully_async and --max_staleness let the sampler keep generating during training, and --parameter_sync_step K lowers the sync frequency.
  • Incremental weight sync: --weight_sync_backend delta_sharded transfers only the changed LoRA elements.
  • CPU sharding: --rollout_num_workers and --sandbox_num_workers spread tool execution and env calls over multiple processes, so the GIL and a single core do not become the bottleneck. vLLM's prefix caching hits directly for the num_generations trajectories of the same group that share a prompt.
  • DP lane balancing: the training batch is split across DP ranks by token load, with whole groups kept intact (the within-group normalization of GRPO needs the complete block), and then balanced a second time by micro-batch.
  • No blocking when no session is free: when the env has no free session, the scheduling thread does not block on reset but backs off and retries, while other samples keep advancing.

At the resource level there are three --resource_mode levels:

resource_modeBehavior
manual (default)Layout follows the parallel arguments given by the user exactly
estimateReads the shapes and dtypes from the HF config and the p50/p95/p99 of prompt lengths (at most 2048 rows sampled), computes the minimum parallel width for the trainer and the sampler respectively, the number of sampler replicas, and vllm_max_num_seqs from --resource_gpu_memory_gib and the engine GPU memory ratio, writes them back into the config, and then starts with the static plan
adaptiveOn top of estimate, ClusterAdapter adjusts the sampling replicas during training. Requires at least one of --offload_model or --offload_optimizer to be on, and --sleep_level only accepts 0/1

adaptive makes three kinds of adjustment, all triggered by the driver on weight version changes and while waiting for a batch:

  1. Migrate replicas by load (adjust): after every weight sync, read pressure() of each role (sampler, reward model pool) and average over the last --resource_window_steps syncs. When the busiest role exceeds the idlest role by 1.5x, migrate one replica-width of GPUs to it. The flex pool reserved by --resource_flex_gpus is used first. Otherwise one replica is removed from the idlest role (it cannot be the last one). The new replica first loads the current weights through checkpoint_manager.warm before taking requests. After every migration it waits --resource_min_hold_steps syncs, and stops once the ratio falls below 1.2x.
  2. Trainer GPU lending (lend / reclaim): while the driver waits for the next batch, if the trainer's waiting-time share over the last step exceeds 0.3 and the current wait is expected to exceed the measured cost of recent lend/reclaim cycles, the trainer model is offloaded to CPU and temporary sampling replicas are started on those GPUs. Once the batch is ready the replicas are removed and the trainer is reloaded before the batch is handed to the training loop. If an OOM caused by leftover trainer GPU memory happens during the lending, the trainer is restored automatically and the lending is skipped.
  3. Fixed trainer layout: the trainer's communication groups are decided at startup and do not scale up or down at run time. All adjustments happen only on the sampler and reward-model side.

๐ŸŽฏ Complete example: code-task GRPO on AgentENV

The task: the model reads files, writes code, and runs tests inside a microVM. checks runs pytest in the same microVM, and the pass ratio is the reward. First prepare the data swe_tasks.jsonl (format as in the checks example above), deploy AgentENV, and build a template (dependencies are preinstalled in the template, and no pip install runs at run time). Then:

CUDA_VISIBLE_DEVICES=0,1 swift rl \
    --rl_type grpo \
    --model Qwen/Qwen3.5-4B \
    --dataset ./swe_tasks.jsonl \
    --system 'You are a coding agent. Each command runs in a fresh process; make every snippet self-contained. Finish by passing the tests.' \
    --mode ray \
    --nproc_per_node 2 \
    --sampler_mode colocate \
    --rollout_sampler vllm \
    --vllm_gpu_memory_utilization 0.5 \
    --sleep_level 1 \
    --tuner lora --lora_rank 8 --lora_alpha 32 --target_modules all-linear \
    --tools sandbox \
    --max_turns 8 \
    --max_completion_length 1024 \
    --max_trajectory_tokens 8192 \
    --sandbox_kind agentenv \
    --sandbox_template swift-code \
    --sandbox_api_url http://10.0.1.20:8000 \
    --sandbox_timeout 900 \
    --sandbox_command_timeout 120 \
    --sandbox_num_envs 16 \
    --sandbox_num_workers 4 \
    --env_reward_weight 1.0 \
    --num_generations 8 \
    --generation_batch_size 4 \
    --per_device_train_batch_size 2 \
    --gradient_accumulation_steps 4 \
    --learning_rate 1e-4 \
    --beta 0.04 \
    --max_steps 200 \
    --logging_steps 1 \
    --output_dir output/agentenv-grpo

--sandbox_num_envs 16 requires the AgentENV host to have 16 ร— template memory + 8 GB of memory. The number of concurrent sandboxes equals the number of in-flight samples, and that number is bounded by it.

The same pipeline implemented with components, with the training loop fully visible:

import math
import os

from swift.dev.builder import build_prompt_dataloader
from swift.dev.builder.optimizer import resolve_max_grad_norm
from swift.dev.builder.streaming import CONTROL_GROUP
from swift.dev.config import (
    CheckpointConfig, DatasetConfig, DistributedConfig, GenerationConfig, LoggingConfig, ModelConfig, RewardConfig,
    RLConfig, RolloutConfig, TemplateConfig, TrainConfig, TunerConfig,
)
from swift.dev.config.process import normalize_rl_type, policy_replay_count
from swift.dev.metric import CompletionLog
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.scoring import copy_inputs

OUTPUT_DIR = 'output/agentenv-grpo'


def build_configs() -> RecipeConfigs:
    return RecipeConfigs(
        model=ModelConfig(model='Qwen/Qwen3.5-4B', torch_dtype='bfloat16', attn_impl='flash_attention_2'),
        template=TemplateConfig(
            max_length=12288,
            system='You are a coding agent. Each command runs in a fresh process; make every snippet '
                   'self-contained. Finish by passing the tests.',
        ),
        dataset=DatasetConfig(dataset=['./swe_tasks.jsonl']),
        # per_device_train_batch_size x gradient_accumulation_steps x dp = number of samples per optimizer 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=200, gradient_checkpointing=True,
        ),
        distributed=DistributedConfig(mode='ray', nproc_per_node=2),
        checkpoint=CheckpointConfig(output_dir=OUTPUT_DIR, save_steps=50, 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),
        rl=RLConfig(
            rl_type='grpo', num_generations=8, advantage_estimator='grpo', epsilon=0.2, beta=0.04,
            max_completion_length=1024, log_completions=True,
        ),
        # Rewards come from the ``checks`` column of the dataset (rewards.check, executed inside the same sandbox session); no ORM is configured
        reward=RewardConfig(env_reward_weight=1.0),
        # Sandbox tools are bound to the AgentENV microVM; max_turns limits the number of tool-call rounds per episode,
        # max_trajectory_tokens limits the whole trajectory, and sandbox_num_envs decides the number of concurrent environments
        rollout=RolloutConfig(
            sampler_mode='colocate', vllm_gpu_memory_utilization=0.5, sleep_level=1,
            tools=['sandbox'], max_turns=8, max_trajectory_tokens=8192,
            sandbox_kind='agentenv', sandbox_template='swift-code', sandbox_api_url='http://10.0.1.20:8000',
            sandbox_timeout=900, sandbox_command_timeout=120, sandbox_num_envs=16, sandbox_num_workers=4,
            generation_batch_size=4),
        generation=GenerationConfig(temperature=1.0),
    )


def main() -> None:
    configs = build_configs()
    train, rollout, rl = configs.train, configs.rollout, configs.rl
    normalize_rl_type(rl)
    ga, repeats = train.gradient_accumulation_steps, policy_replay_count(rl)

    # 1. prompts: the prompt rows of the dataset with assistant turns removed, plus the label columns read by the reward
    prompt_rows, prompts, extras = prompt_rows_from_dataset(configs.dataset, system=configs.template.system)

    # 2. twinkle initialize, the template, and the device grouping of each role (trainer, sampler, reference)
    template, resource_plan, meshes = initialize_rl_devices(
        configs, output_dir=OUTPUT_DIR, prompt_rows=prompt_rows,
        group_requests=lambda: policy_group_requests(configs),
    )
    geometry = rollout_batch_geometry(
        configs, resource_plan=resource_plan, num_prompts=len(prompts),
        num_generations=rl.num_generations, num_iterations=repeats, recipe='agentenv-grpo',
    )
    train_batch_size = geometry.train_batch_size

    # 3. Components: trainer (loss, optimizer, LR schedule), sampler, rollout, weight sync engine,
    #    reference, reward scorer and advantage, all built from 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

    # 4. prompt dataloader -> streaming driver; each iteration returns a batch of trajectories and scores
    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),
    )

    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)
    completion_log = CompletionLog(remote_group=CONTROL_GROUP) if rl.log_completions else None
    completions_path = os.path.join(OUTPUT_DIR, 'completions.jsonl')
    lent = False

    def mark_lent() -> None:
        nonlocal lent
        lent = True

    def sync() -> None:
        # publish the current policy weights to the sampler; under colocate the sampler then takes over the GPUs and the trainer stays offloaded until reclaim()
        publish_policy(resources.engine, rollout, colocate=resources.colocate, on_lend=mark_lent)

    def reclaim() -> None:
        # colocate handover: put the sampler to sleep 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()  # first publication: the sampler must start sampling from the policy weights
            for rows, facts in driver:
                reclaim()
                if completion_log is not None:
                    completion_log(rows, step=state.global_step + 1, scores=facts.get('scores'), path=completions_path)
                record_reward_metric(facts, orm_weights=configs.reward.orm_weights, reward_metric=metrics.reward_metric)
                # reference logps are read by the KL term; with LoRA and no separate ref_model, the reference is the trainer with its 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 advantage, written onto copies of the trajectories
                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: each time take one full optimizer update window of train_batch_size x ga rows
                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 batch of rollouts uses the updated policy
                if state.reached_max() or state.should_stop():
                    break
        finally:
            # close the driver first and return lent GPUs; a cleanup exception must not mask a training exception
            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='agentenv-grpo')


if __name__ == '__main__':
    main()

To switch environments, change only the sandbox_* fields of rollout_config. To connect to a deployed training service, set distributed_config.mode='remote' and drop the colocate-related fields. The training loop stays the same.

๐Ÿค– Tool-trajectory SFT

The tool-call format and a basic policy can first be learned by SFT on high-quality tool trajectories, followed by online RL. A training row stores the user question, the tool definitions, the calls, and the observations. For example, in OpenAI format:

{"messages": [{"role": "user", "content": "่ฎก็ฎ— 17ร—23"}, {"role": "assistant", "content": null, "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "calculator", "arguments": "{\"expression\":\"17*23\"}"}}]}, {"role": "tool", "tool_call_id": "call_1", "content": "391"}, {"role": "assistant", "content": "็ป“ๆžœๆ˜ฏ 391ใ€‚"}], "tools": [{"type": "function", "function": {"name": "calculator", "description": "่ฎก็ฎ—ๆ•ฐๅญฆ่กจ่พพๅผ", "parameters": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}}}]}
CUDA_VISIBLE_DEVICES=0 swift sft \
    --model Qwen/Qwen3.5-4B \
    --attn_impl flash_attention_2 \
    --torch_dtype bfloat16 \
    --dataset ./agent_train.jsonl \
    --tuner lora \
    --max_length 4096 \
    --learning_rate 1e-4 \
    --num_train_epochs 3 \
    --output_dir output/agent-sft

SFT replays existing trajectories and does not execute tools during training. Training and deployment must use the same tool schema and template conventions. Tool messages belong to the context. Only the action and reply tokens generated by the model take part in the update. For the data format see Custom datasets. For component examples see train/agentic.

๐Ÿงฉ Custom tools

A tool plugin inherits ToolPlugin, and build() returns a list of tools. Load it through --external_plugins and select it with --tools <registered name> (it can be listed alongside sandbox). Env tools are bound by rollout to the sample's session, and a custom tool that holds mutable state must also be isolated per sample. For the full contract see Plugins. For inference-time examples see infer/agentic. For RL examples with the local sandbox and OpenEnv see rl/agentic.

For deploying remote model and sampling services see Server and client. For the GRPO algorithm see Online learning.