← Back to Pull requests

[HybridEngineRollout] Add multi-turn tool-calling rollout, GRPO primitives and turn-level continuous batching #9037

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 08, 2026 23:55 UTC
Author

Implements stage 1 of the agentic RL proposal (#8942): HybridEngineRollout can roll out multi-turn, tool-calling trajectories for RL training, with the primitives a GRPO trainer needs.

  • Rollout records. RolloutRequest and RolloutBatch carry RolloutRecords: one prompt and its rollout across all turns, with loss_mask (0 on tool output), recorded log-probs, reward and status.

  • Multi-turn tool calling. With multi_turn=True, each turn's response is parsed for tool calls, the tools run, and their output is appended as tool messages. Tools subclass Tool; parse errors, unknown tools and exceptions go back to the model as text. Parsers for the Hermes/Qwen3 and Qwen3-Coder formats.

  • GRPO primitives. group_advantages, grpo_policy_loss (PPO-clip with clip-higher, optional k3 KL penalty, token-mean or sample-mean aggregation) and old_log_probs_from_rollout.

  • Unified generate path. A single-turn call is a rollout of one turn without tool calls, so every call runs one driver. Under it are static batching, and continuous batching with or without graph capture.

  • Turn-level continuous batching. Built on master's continuous-batching loops. A multi-turn trajectory is a request that comes back: a row is freed when its turn ends, a turn that called a tool waits in a ToolQueue while its tools run, and its next turn returns to the front of the pending queue.

  • Sampling for RL. temperature, top_k, top_p and repetition_penalty apply in generate()'s order on every path, and return_log_probs records each token's log-prob under the sampling distribution.

  • Data-parallel and AutoTP rollout. Each data-parallel rank rolls out its own prompts. Under AutoTP, ranks of a tensor-parallel group share their random state and run tools once, so they sample and append the same tokens.
  • Changes

    API

    | Change | Notes |
    |---|---|
    | RolloutRequest / RolloutBatch hold RolloutRecords instead of tensors | Breaking. RolloutRecord holds a series of states to manage trajectories across turns |
    | continuous_batch_size and return_log_probs move from SamplingConfig to HybridEngineRolloutConfig | 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 |
    | HybridEngineRolloutConfig gains multi_turn, max_turns, chat_template_kwargs, tool_call_parser; SamplingConfig gains max_new_tokens_per_turn | New |
    | SamplingConfig.max_tool_output_chars cuts 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's max_tool_response_length does; RolloutRecord counts the cuts in num_tool_outputs_truncated and the turns in num_turns | New, off by default. Without it, a tool output that would pass max_out_tokens is dropped and the trajectory ends TRUNCATED |
    | build_rollout(..., generation_engine=...) replaces student_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 HF generate(), for example Llama 3.1's <|eom_id|> after a tool call |
    | SamplingConfig.repetition_penalty is optional; None uses the model's generation_config | Same contract as generate() |
    | SamplingConfig validates its own options when created | Invalid values now raise at construction instead of at generate() |
    | deepspeed.runtime.rollout.tool and deepspeed.runtime.rollout.grpo | New modules |

    Generation paths

  • Static batching runs each turn for every active trajectory with HF generate, or on a captured decode graph.

  • Continuous batching keeps master's _generate_continuous and _generate_continuous_graph loops and ContinuousBatchScheduler, 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 a ToolQueue runs 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.

  • Without graph capture, all rows share master's write column, with compaction, align_decode_fronts and enable_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_capacity stays a memory cap for single-turn calls, and is raised to that bound, with a warning, for multi-turn rollouts.

  • With graph capture, each row keeps its own write position. An admission is prefilled in one padded batch, through the same prefill as the eager path, and only its real tokens are stored, from slot 0, so a returning turn's width does not matter. The captured graph is reused across calls as on master since #9009: an in-place weight update no longer captures it again, and 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, which max_out_tokens can 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 own torch.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 HF generate(), 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 accept logits_to_keep would 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):

  • All modes give the same records. For single-turn and multi-turn rollouts with a calculator tool, all modes (static and continuous batching, with and without graph capture, aligned decode fronts, cache trimming) give greedy records identical to static batching. Recorded log-probs differ by at most 3.4e-5.

  • Graph decode matches HF. Greedy graph decode matches HF generate on 205 of 205 tokens for a padded batch of 8 (bf16: 190 of 207; rows split on near-tied logits).

  • Recorded log-probs match a training forward. On tool-calling rollouts on every decode path, recorded log-probs differ from a full forward by at most 0.0002. In bf16, the largest gap is 0.49–0.68, in line with HF's own incremental decode, which differs from a full forward by 0.47–0.72 in earlier runs.

  • Tool output cap. On Qwen3-4B-Instruct-2507 with a calculator that also returns about 6,000 characters of log, every trajectory ends TRUNCATED after its first turn without the cap, since the output would pass max_out_tokens. With max_tool_output_chars=512, every trajectory completes its second turn on static, continuous and continuous graph batching, num_tool_outputs_truncated counts each cut output, and the chat template stays intact, with one assistant header per turn.

  • Response text. In every record of these runs, response equals 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):

  • Data parallel. Each rank rolls out its own prompts, of different counts and lengths, on static and continuous batching, with and without graph capture. Its greedy records match HF generate on 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.

  • AutoTP. Ranks seeded differently produce identical records, greedy and sampled, with and without graph capture, and across a sampled tool turn. Greedy output equals the unsharded model's, and a tool that returns its own rank gives both ranks the first rank's output.
  • 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_config EOS 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.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: delock Review duration: 31690m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 29.7% · Safe to merge
    29.7%