[HybridEngineRollout] Add multi-turn tool-calling rollout, GRPO primitives and turn-level continuous batching #9037
All Vouch review confidence checks passed
Residual risk 0.30 = Change Risk (0.52) × (1 − Review Confidence (0.43)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.344
Real PR Conversation Timeline
1 comments
"Review active on #9037"
general
weight: 0.35
delock
Implements stage 1 of the agentic RL proposal (#8942):
HybridEngineRolloutcan roll out multi-turn, tool-calling trajectories for RL training, with the primitives a GRPO trainer needs.RolloutRequestandRolloutBatchcarryRolloutRecords: one prompt and its rollout across all turns, withloss_mask(0 on tool output), recorded log-probs, reward and status.multi_turn=True, each turn's response is parsed for tool calls, the tools run, and their output is appended as tool messages. Tools subclassTool; parse errors, unknown tools and exceptions go back to the model as text. Parsers for the Hermes/Qwen3 and Qwen3-Coder formats.group_advantages,grpo_policy_loss(PPO-clip with clip-higher, optional k3 KL penalty, token-mean or sample-mean aggregation) andold_log_probs_from_rollout.ToolQueuewhile its tools run, and its next turn returns to the front of the pending queue.temperature,top_k,top_pandrepetition_penaltyapply ingenerate()'s order on every path, andreturn_log_probsrecords each token's log-prob under the sampling distribution.Changes
API
| Change | Notes |
|---|---|
|
RolloutRequest/RolloutBatchholdRolloutRecords instead of tensors | Breaking.RolloutRecordholds a series of states to manage trajectories across turns ||
continuous_batch_sizeandreturn_log_probsmove fromSamplingConfigtoHybridEngineRolloutConfig| Breaking. The row count sizes the KV cache and the captured graph, so it is an engine setting rather than a per-call one || The rollout caps each trajectory (prompt, responses and tool output) at
hybrid_engine.max_out_tokens, which must be set explicitly in the DeepSpeed config | Breaking. The hybrid engine's default would silently cap every trajectory ||
HybridEngineRolloutConfiggainsmulti_turn,max_turns,chat_template_kwargs,tool_call_parser;SamplingConfiggainsmax_new_tokens_per_turn| New ||
SamplingConfig.max_tool_output_charscuts each tool output longer than that many characters before it is added, keeping its"start","end"or"both"ends (tool_output_keep) with a...(truncated)marker, as verl'smax_tool_response_lengthdoes;RolloutRecordcounts the cuts innum_tool_outputs_truncatedand the turns innum_turns| New, off by default. Without it, a tool output that would passmax_out_tokensis dropped and the trajectory endsTRUNCATED||
build_rollout(..., generation_engine=...)replacesstudent_engine, which still works as a deprecated alias | Backward compatible || A turn ends on any EOS id from the tokenizer or the model's
generation_config| Matches the stop set of HFgenerate(), for example Llama 3.1's<|eom_id|>after a tool call ||
SamplingConfig.repetition_penaltyis optional;Noneuses the model'sgeneration_config| Same contract asgenerate()||
SamplingConfigvalidates its own options when created | Invalid values now raise at construction instead of atgenerate()||
deepspeed.runtime.rollout.toolanddeepspeed.runtime.rollout.grpo| New modules |Generation paths
generate, or on a captured decode graph._generate_continuousand_generate_continuous_graphloops andContinuousBatchScheduler, with three additions for multi-turn: each request carries its own token budget, a request returning from tools goes to the front of the pending queue, and aToolQueueruns tool calls on a background event loop while the other rows decode; the rollout ends each turn itself and resubmits a turn once its tools return. Both loops read EOS once per step for all rows, and record each step for the profile.align_decode_frontsandenable_cache_trimming. A returning turn whose context is longer than the space behind the column moves the column forward, and live rows mask the skipped columns. A single-turn call keeps master's sizing; a multi-turn rollout gets the longest context a turn can be admitted with (max_out_tokens, plus any left padding of pre-tokenized samples) plus one turn's budget, which trimming at full always leaves room for.continuous_cache_capacitystays a memory cap for single-turn calls, and is raised to that bound, with a warning, for multi-turn rollouts.shutdown()releases it.Parallelism
| Setup | Behavior |
|---|---|
| Data parallel, ZeRO 0–2, with or without optimizer offload | Supported on every path; ranks run independently |
| ZeRO-3 | Single-turn static batching on HF
generate. Ranks decode up to the same configured cap and stop together, through master's group-aware criterion from #8390, once every row on every rank has reached EOS or its own budget, whichmax_out_tokenscan make differ between ranks. A rank with no room joins with a placeholder row whose budget is 0, so it does not hold the others back. Multi-turn rollout, graph capture and continuous batching raise, since ranks would run different forwards || AutoTP | Every generate path, with and without graph capture. Every KV cache is sized from each rank's own prefill, as in #9008, ranks share their group's random state once per
generate()call, and tool calls run on the group's first rank, which broadcasts the output. A tool that draws from the accelerator RNG therefore advances only that rank's state, and the group samples different tokens from the next turn on; such tools should use their owntorch.Generator. In multi-turn continuous batching the first rank also decides when a turn returns from its tools: at each step where a row frees, it sends the finished tools' output to its group over a host-side Gloo group, so every rank admits the same turns at the same step. With a tied output head that AutoTP shards by vocabulary (VocabParallelLinear, which master enables automatically for tied-embedding models under Transformers 5.x), each rank's logits cover only its shard, so ranks picked different, wrong tokens (R-1 in RFC #8790); the head now gathers the full logits for the duration of each rollout call and returns rank-local logits to training afterwards. Risk: the gather covers whatever positions the forward returns. Every rollout path, and HFgenerate(), requests last-position logits only (logits_to_keep=1), so it gathers[B, V]per step, about 10 MB at 32 rows in bf16. A model whose forward does not acceptlogits_to_keepwould return logits for every prompt position, and the gather would then build the full[B, T, V]tensor at prefill (about 20 GB at 32 rows x 2048 tokens with a 152k vocabulary); current Hugging Face causal LMs accept it || Hybrid engine
inference_tp_size > 1| Raises: the rollout calls the module directly and skips the hybrid engine's input gather |Validation
Hardware and software: NVIDIA A100-SXM4-40GB (1 or 2 per run, driver 595.71.05) and NVIDIA A40, torch 2.14.1+cu130, CUDA 13.0, Python 3.12.15, Transformers 5.19.0 and 4.57.6.
| Check | Command | Result |
|---|---|---|
| Rollout, static cache and v1 rollout suites, including the 2- and 4-GPU tests, Transformers 5.19.0, 4× A100 |
pytest tests/unit/runtime/rollout tests/unit/utils/test_static_cache.py tests/unit/v1/test_hybrid_engine_rollout_v1.py| 272 passed, 1 skipped (the opt-in pretrained-model test), including the tied-head test on all four paths || Existing AutoTP tests, 4× A100 |
pytest tests/unit/v1/autotp/test_tp_plan_real_models.py tests/unit/v1/autotp/test_tp_plan_e2e.py| 17 passed || AutoTP on a tied-embedding model: Qwen3-4B-Instruct-2507, TP2, fp32, greedy, single- and multi-turn, 2× A100 | static, static graph, continuous and continuous graph, against static and against one GPU | Ranks identical and every mode equal to static in all 8 cases (log-prob gap at most 7.4e-5), with a tool call in all 8 multi-turn trajectories; TP2 static equal to one GPU, 5/5 single-turn and 8/8 multi-turn rows. Before the fix, ranks differed in all 8 cases |
| Cost of the gather: Qwen3-4B, bf16, TP2 | tok/s with the fix vs
tensor_parallel.vocab_parallel_lm_head: false| Within ±1.1% on all four paths || CPU suites |
DS_ACCELERATOR=cpu pytest tests/unit/runtime/rollout tests/unit/utils/test_static_cache.py| 192 passed, 4 skipped; the multi-rank classes run in the GPU suites ||
pre-commit|pre-commit run --files <changed files>| Passes || Docs build |
sphinx-build -b html docs/code-docs/source| Succeeds with the same 21 warnings as master || Same GPU suites, Transformers 4.57.6, 2× A40 | as above | 230 passed, 7 skipped, on the revision before the continuous-batching rewrite; to rerun |
Behavior checks with a real model (Qwen3-4B SFT checkpoint, stored in bf16; the equivalence checks load it in float32, so that rounding cannot flip near-tied tokens, and bf16 results are noted where run):
generateon 205 of 205 tokens for a padded batch of 8 (bf16: 190 of 207; rows split on near-tied logits).TRUNCATEDafter its first turn without the cap, since the output would passmax_out_tokens. Withmax_tool_output_chars=512, every trajectory completes its second turn on static, continuous and continuous graph batching,num_tool_outputs_truncatedcounts each cut output, and the chat template stays intact, with one assistant header per turn.responseequals a decode of all its response tokens at once, although it is built one turn and tool output at a time.Distributed tests added (2 GPUs):
generateon its own module, before and after an optimizer step, and the step changes them. Covered: ZeRO-2 on every path, ZeRO-2 with CPU optimizer offload and ZeRO-2 fp16 on graph capture, and ZeRO-3 on single-turn static batching.Generation speed against master, single-turn, path by path. Setup: Qwen3-4B in bf16 on one A100-SXM4-40GB; 32 chat prompts of varied length per call; 256 new tokens; 32 rows for continuous batching, as many as static batching decodes per call. Each cell is 2 timed calls after a warm-up, one round per tree, in tokens per second, master → branch. "Fixed length" disables EOS, including the model's
generation_configEOS ids, so both trees generate exactly the same tokens.| Path | Greedy, fixed length | Sampled, fixed length | Greedy, real EOS |
|---|---|---|---|
| Static (HF
generate) | 774 → 770 (−0.6%) | 772 → 770 (−0.3%) | 497 → 492 (−0.9%) || Static, graph capture | 1060 → 1054 (−0.6%) | 1055 → 1048 (−0.7%) | 675 → 669 (−0.8%) |
| Continuous | 674 → 667 (−1.0%) | 675 → 666 (−1.4%) | 416 → 425 (+2.2%) |
| Continuous, aligned fronts | 607 → 605 (−0.4%) | 608 → 603 (−0.9%) | 378 → 385 (+2.0%) |
| Continuous, cache trimming | 675 → 667 (−1.3%) | 674 → 664 (−1.5%) | 416 → 424 (+1.8%) |
| Continuous, graph capture | 998 → 1056 (+5.8%) | 1002 → 1056 (+5.4%) | 633 → 677 (+6.9%) |
| Continuous, graph capture, weights updated in place between calls | 1009 → 1071 (+6.1%) | 1002 → 1056 (+5.4%) | 633 → 677 (+6.9%) |
The weight-update row is the RL case. Neither tree captures the graph again after an in-place weight update (0 captures in the timed calls), so it runs at the speed of plain graph capture. In the real-EOS column, continuous graph capture on the branch generates 5,174 tokens per call against 5,242 on master and on every other continuous path, likely because its prefill rounds differently in bf16 and a few greedy rows split at near-tied logits; in float32 all modes give identical records. Peak extra memory matches master on every path except static graph decode, which needs about half as much (1.45 vs 2.72 GiB), because the prefill writes straight into the decode cache. Differences within about 2% are inside what one round with 2 timed calls can resolve.
Compatibility matrix
| Axis | Validated | Not validated |
|---|---|---|
| ZeRO stage | 0, 2, 3 (single-turn static only) | 1 |
| Offload | CPU optimizer offload, ZeRO-2 | NVMe, parameter offload |
| Precision | fp32, bf16, fp16 | fp8 / quantized |
| Parallelism | Data parallel (2 GPUs), AutoTP (2 GPUs) | Pipeline, sequence parallel, MoE, more than 2 GPUs |
| Accelerator | CUDA (A100, A40), CPU | ROCm, XPU, HPU and the rest |
| Transformers | 5.19.0, 4.57.6 | Other versions |
Companion PR
A DeepSpeedExamples PR adds a Qwen3 GRPO ReTool training example on this API. deepspeedai/DeepSpeedExamples#1023.
AI assistance
This PR was written with AI assistance (Claude Code). The submitter reviewed every changed line and ran the tests above.