Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
cd2694a
feat(rollout): multi-turn tool-calling rollout and GRPO primitives
anyadontfly Nov 5, 2026
ba8598a
refactor(rollout): make continuous_batch_size and return_log_probs en…
anyadontfly Nov 7, 2026
8a0c281
refactor(rollout): check finished rows every decode step
anyadontfly Nov 8, 2026
bab51d5
docs(rollout): shorten tool docstrings and drop references to other p…
anyadontfly Nov 8, 2026
f723c7f
test: drop the graph position regression test carried over from #8602
anyadontfly Nov 8, 2026
4c33fb1
test(rollout): enable graph capture in the static graph flash_attenti…
anyadontfly Nov 8, 2026
9bdcf1b
refactor(rollout): run every generate call through one driver
anyadontfly Nov 8, 2026
c34408c
test(rollout): cover data-parallel rollout before and after a trainin…
anyadontfly Nov 8, 2026
0ef98fb
Merge origin/master into multi-turn-rollout
anyadontfly Nov 8, 2026
bb5660f
test(rollout): cover ZeRO-2 offload, fp16 and ZeRO-3 in the data-para…
anyadontfly Nov 8, 2026
e7107cb
fix(rollout): address review findings on context caps, padding and to…
anyadontfly Nov 9, 2026
a3a715d
refactor(rollout): move pad and penalty helpers to utils, stop paddin…
anyadontfly Nov 10, 2026
c09b6f3
refactor(rollout): trim RolloutRecord to the fields rollout uses
anyadontfly Nov 10, 2026
92b1207
refactor(rollout): read engine settings through engine accessors, cle…
anyadontfly Nov 10, 2026
0fcc948
feat(rollout)!: split HybridEngineRolloutConfig from RolloutConfig, c…
anyadontfly Nov 10, 2026
c2da157
refactor(rollout): validate attention and sync AutoTP random state on…
anyadontfly Nov 10, 2026
87d9bc7
refactor(rollout): add _TokenSelector with the repetition penalty bui…
anyadontfly Nov 10, 2026
0ea1e34
perf(rollout): compute token log-probs only when return_log_probs is set
anyadontfly Nov 10, 2026
db96f58
refactor(rollout): reuse _hf_sampling_kwargs on the eager static path
anyadontfly Nov 10, 2026
df1be51
refactor(rollout): naming and comment cleanup
anyadontfly Nov 10, 2026
1e8a7f7
refactor(rollout): drop the prompt-token check and unused locals in c…
anyadontfly Nov 11, 2026
e9be696
fix(rollout): end turns on every EOS id
anyadontfly Nov 11, 2026
2d57b6f
fix(rollout): accept build_rollout's student_engine keyword as a depr…
anyadontfly Nov 11, 2026
cde4cb7
docs(rollout): note that Qwen3-Coder null parameters become None for …
anyadontfly Nov 11, 2026
da3d161
refactor(rollout): run continuous batching on master's loops with a t…
anyadontfly Nov 11, 2026
178f41b
test(rollout): restore master's graph-state, capture and cache-estima…
anyadontfly Nov 11, 2026
b3f2a6b
test(rollout): move the on-device rollout tests to the v1 suite
anyadontfly Nov 11, 2026
8858de9
docs(rollout): describe continuous-batching sizing, graph reuse and p…
anyadontfly Nov 11, 2026
4f5e2d0
Merge master into multi-turn-rollout
anyadontfly Nov 12, 2026
b677f3e
chore(rollout): drop an unused prefill argument, document max_out_tok…
anyadontfly Nov 12, 2026
d0feab9
feat(rollout): support AutoTP in multi-turn continuous batching
anyadontfly Nov 13, 2026
a2b6e0d
refactor(rollout): stop ZeRO-3 rollout on each row's budget, pass the…
anyadontfly Nov 13, 2026
74e5af6
refactor(rollout): run static multi-turn tool calls through ToolQueue
anyadontfly Nov 13, 2026
bca99b4
fix(rollout): count tensor-parallel ranks when the group is the world…
anyadontfly Nov 13, 2026
8673dc6
fix(rollout): gather vocabulary-parallel output-head logits during Au…
anyadontfly Nov 14, 2026
3c55b97
refactor(rollout): requeue finished tool turns from the tool queue
anyadontfly Nov 14, 2026
064897e
refactor(rollout): rename ToolQueue to PostTurnRouter and move rollou…
anyadontfly Nov 14, 2026
1f903d1
refactor(rollout): check model support up front and share the continu…
anyadontfly Nov 14, 2026
66c1c0a
refactor(rollout): end turns in the rollout and keep ToolQueue to too…
anyadontfly Nov 14, 2026
b2ee8bb
feat(rollout): cap each tool output by characters
anyadontfly Nov 14, 2026
3aa67ab
refactor(rollout): place the rollout's new methods beside the code th…
anyadontfly Nov 14, 2026
4afaa33
Merge origin/master into multi-turn-rollout
anyadontfly Nov 14, 2026
ad555e4
test(rollout): drop tests that other tests already cover
anyadontfly Nov 14, 2026
e43e814
fix(rollout): address review findings on ZeRO-3, GRPO, CCL, profiles …
anyadontfly Nov 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions deepspeed/comm/ccl.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@ def reduce_scatter(self, output, input_list, op=ReduceOp.SUM, group=None, async_
def reduce(self, tensor, dst, op=ReduceOp.SUM, group=None, async_op=False):
return self.run_collective(name="reduce", tensor=tensor, dst=dst, op=op, group=group, async_op=async_op)

def new_group(self, ranks):
return super(CCLBackend, self).new_group(ranks)
def new_group(self, ranks, backend=None):
return super(CCLBackend, self).new_group(ranks, backend=backend)

def _new_group(self, ranks, group):
size = len(ranks)
Expand Down
6 changes: 4 additions & 2 deletions deepspeed/comm/comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,13 @@ def destroy_process_group(group: Optional[Any] = None) -> None:
return result


def new_group(ranks):
def new_group(ranks, backend=None):
global cdb
assert cdb is not None and cdb.is_initialized(
), 'DeepSpeed backend not set, please initialize it using init_process_group()'
return cdb.new_group(ranks)
if backend is None:
return cdb.new_group(ranks)
return cdb.new_group(ranks, backend=backend)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Forward backend through the CCL new_group override

When cdb is CCLBackend and multi-turn AutoTP initializes host_tensor_parallel_group(), this dispatch passes backend="gloo", but deepspeed/comm/ccl.py still overrides new_group(self, ranks) without accepting that keyword. The rollout therefore raises TypeError before generation on the CCL path; update that override to accept and forward the backend while preserving its subgroup bookkeeping.

AGENTS.md reference: AGENTS.md:L40-L40

Useful? React with 👍 / 👎.



def is_available() -> bool:
Expand Down
4 changes: 2 additions & 2 deletions deepspeed/comm/torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,9 +578,9 @@ def is_initialized(self):
def get_backend(self, group=None):
return torch.distributed.get_backend(group=group)

def new_group(self, ranks):
def new_group(self, ranks, backend=None):
_ensure_gloo_subgroup_split()
return torch.distributed.new_group(ranks)
return torch.distributed.new_group(ranks, backend=backend)

def get_global_rank(self, group, group_rank):
if hasattr(torch.distributed.distributed_c10d, "get_global_rank"):
Expand Down
46 changes: 38 additions & 8 deletions deepspeed/runtime/rollout/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,77 @@
- :class:`RolloutEngine` — abstract base class
- :class:`RolloutRequest`, :class:`RolloutBatch`, :class:`SamplingConfig` — dataclasses
- :class:`ResponseTokenBatch` — response-only causal training targets
- :func:`group_advantages`, :func:`grpo_policy_loss` — GRPO advantages and PPO-clip policy loss
- :class:`HybridEngineRollout` — concrete implementation using DeepSpeed hybrid engine
- :class:`Tool`, :class:`ToolSet`, :func:`parse_hermes_tool_calls`, :func:`parse_qwen3_coder_tool_calls` — tools
for multi-turn rollout
- :func:`build_rollout` — factory that selects the engine from config
"""

import warnings

from deepspeed.runtime.rollout.base import (
RolloutBatch,
RolloutConfig,
RolloutEngine,
RolloutRequest,
SamplingConfig,
)
from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout
from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout, HybridEngineRolloutConfig
from deepspeed.runtime.rollout.grpo import (GRPOLossOutput, group_advantages, grpo_policy_loss,
old_log_probs_from_rollout)
from deepspeed.runtime.rollout.opsd import JSDLossOutput, ResponseTokenBatch, generalized_jsd_loss
from deepspeed.runtime.rollout.tool import Tool, ToolCall, ToolSet, parse_hermes_tool_calls, parse_qwen3_coder_tool_calls

__all__ = [
"GRPOLossOutput",
"HybridEngineRollout",
"HybridEngineRolloutConfig",
"JSDLossOutput",
"RolloutBatch",
"RolloutConfig",
"RolloutEngine",
"RolloutRequest",
"ResponseTokenBatch",
"SamplingConfig",
"Tool",
"ToolCall",
"ToolSet",
"build_rollout",
"generalized_jsd_loss",
"group_advantages",
"grpo_policy_loss",
"old_log_probs_from_rollout",
"parse_hermes_tool_calls",
"parse_qwen3_coder_tool_calls",
]


def build_rollout(rollout_cfg, student_engine=None, tokenizer=None, **kwargs):
def build_rollout(rollout_cfg, generation_engine=None, tokenizer=None, tools=None, **kwargs):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the public student_engine keyword

For callers using the prior public form build_rollout(cfg, student_engine=engine, tokenizer=tok), the renamed argument is now swallowed by **kwargs, leaving generation_engine as None and raising the misleading "needs both" error; positional callers alone continue to work. Retain student_engine as a deprecated alias (or explicitly translate it from kwargs) so this factory signature remains backward compatible.

AGENTS.md reference: AGENTS.md:L40-L40

Useful? React with 👍 / 👎.

"""Factory: construct the rollout engine specified by ``rollout_cfg.engine``.

Args:
rollout_cfg: :class:`RolloutConfig` (or any object with an ``engine``
attribute set to ``"hybrid_engine"``).
student_engine: DeepSpeed engine wrapping the student model.
rollout_cfg: The backend's config, a subclass of :class:`RolloutConfig` whose ``engine`` names the
backend: :class:`HybridEngineRolloutConfig` for ``"hybrid_engine"``.
generation_engine: DeepSpeed engine wrapping the student model.
tokenizer: HuggingFace tokenizer.
tools: Tools the model may call in multi-turn rollout: a
:class:`ToolSet` or a list of :class:`Tool`.
student_engine: Deprecated alias of ``generation_engine``.
"""
if "student_engine" in kwargs:
if generation_engine is not None:
raise TypeError("build_rollout got both generation_engine and its deprecated alias student_engine")
warnings.warn("build_rollout(student_engine=...) is deprecated; use generation_engine",
DeprecationWarning,
stacklevel=2)
generation_engine = kwargs.pop("student_engine")
engine_name = rollout_cfg.engine
if engine_name == "hybrid_engine":
if student_engine is None or tokenizer is None:
raise ValueError("hybrid_engine rollout needs both student_engine and tokenizer")
return HybridEngineRollout(engine=student_engine, tokenizer=tokenizer, cfg=rollout_cfg)
if generation_engine is None or tokenizer is None:
raise ValueError("hybrid_engine rollout needs both generation_engine and tokenizer")
if tools is not None and not isinstance(tools, ToolSet):
tools = ToolSet(tools)
return HybridEngineRollout(engine=generation_engine, tokenizer=tokenizer, cfg=rollout_cfg, tools=tools)

raise ValueError(f"Unknown rollout engine {engine_name!r}; choose from 'hybrid_engine'")
110 changes: 70 additions & 40 deletions deepspeed/runtime/rollout/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,85 +9,115 @@
"""

from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional

import torch
from dataclasses import dataclass, field
from enum import Enum
from typing import Literal, Optional, get_args


@dataclass
class RolloutConfig:
"""Configuration for the rollout engine."""
"""Selects the rollout backend; each backend's config subclasses this with its own settings."""
engine: str = "hybrid_engine"

# Use CUDA graph capture for decode acceleration.
use_graph_capture: bool = False

# The ends of a tool output that SamplingConfig.max_tool_output_chars keeps.
ToolOutputKeep = Literal["start", "end", "both"]


@dataclass
class SamplingConfig:
"""Sampling knobs that the trainer passes to ``generate`` each step.

``top_k <= 0`` disables top-k filtering.
``top_k <= 0`` disables top-k filtering. ``repetition_penalty=None`` uses the
value in the model's ``generation_config``; 1.0 disables the penalty.

``max_tool_output_chars`` cuts each tool output longer than that many characters before it is added to the
conversation, keeping its ``"start"``, ``"end"`` or ``"both"`` ends (``tool_output_keep``) with a
``...(truncated)`` marker at the cut; None leaves tool output whole.
"""

max_new_tokens: int
max_new_tokens_per_turn: Optional[int] = None
temperature: float = 1.0
top_p: float = 1.0
top_k: int = -1
n_samples_per_prompt: int = 1
continuous_batch_size: Optional[int] = None
repetition_penalty: Optional[float] = None
max_tool_output_chars: Optional[int] = None
tool_output_keep: ToolOutputKeep = "both"

def __post_init__(self) -> None:
if self.max_new_tokens <= 0:
raise ValueError("max_new_tokens must be positive")
if self.max_new_tokens_per_turn is not None and self.max_new_tokens_per_turn <= 0:
raise ValueError("max_new_tokens_per_turn must be positive")
if self.repetition_penalty is not None and self.repetition_penalty <= 0:
raise ValueError("repetition_penalty must be positive")
if self.max_tool_output_chars is not None and (not isinstance(self.max_tool_output_chars, int)
or self.max_tool_output_chars < 1):
raise ValueError("max_tool_output_chars must be a positive integer")
if self.tool_output_keep not in get_args(ToolOutputKeep):
raise ValueError(f"tool_output_keep must be 'start', 'end' or 'both'; got {self.tool_output_keep!r}")


@dataclass
class RolloutRequest:
"""Input to ``RolloutEngine.generate``.
class RolloutRecord:
"""One prompt and its rollout across all turns."""

class Status(Enum):
PENDING = "pending"
COMPLETED = "completed"
TRUNCATED = "truncated"

group_index: int | None = None
prompt: str | list[dict[str, str]] = ""
tokens: list[int] = field(default_factory=list)
attention_mask: list[int] = field(default_factory=list)
response: str = ""
response_length: int = 0
loss_mask: list[int] | None = None
rollout_log_probs: list[float] | None = None
status: Status = Status.PENDING
# Turns the model has generated, each followed by the output of the tools it called, if any.
num_turns: int = 0
# Tool outputs cut to SamplingConfig.max_tool_output_chars.
num_tool_outputs_truncated: int = 0

Prompts arrive *left-padded* (i.e. real tokens at the right edge) so that
causal generation appends naturally after them.
"""

prompt_ids: torch.Tensor # [B, T_p] left-padded with pad_token_id
prompt_attention_mask: torch.Tensor # [B, T_p], 1 on real prompt tokens
@dataclass
class RolloutRequest:
"""Input to ``RolloutEngine.generate``."""

samples: list[RolloutRecord]

def __post_init__(self) -> None:
if self.prompt_ids.dim() != 2:
raise ValueError(f"prompt_ids must be 2-D [B, T_p]; got {tuple(self.prompt_ids.shape)}")
if self.prompt_attention_mask.shape != self.prompt_ids.shape:
raise ValueError(f"prompt_attention_mask shape {tuple(self.prompt_attention_mask.shape)} "
f"does not match prompt_ids {tuple(self.prompt_ids.shape)}")
for i, sample in enumerate(self.samples):
if len(sample.attention_mask) != len(sample.tokens):
raise ValueError(f"samples[{i}] attention_mask length {len(sample.attention_mask)} does not "
f"match tokens length {len(sample.tokens)}")
if sample.num_turns != 0 or sample.num_tool_outputs_truncated != 0 or sample.loss_mask is not None:
raise ValueError(f"samples[{i}] already holds a rollout; pass the prompt only")


@dataclass
class RolloutBatch:
"""Output of ``RolloutEngine.generate``.

``input_ids`` holds the *concatenation* of (left-padded) prompt and
response, right-padded to the longest sequence in the batch.
"""
"""Output of ``RolloutEngine.generate``."""

input_ids: torch.Tensor # [B', T_p + T_r]; B' = B * n_samples_per_prompt
attention_mask: torch.Tensor # [B', T_p + T_r]
response_start_idx: torch.Tensor # [B'] int
samples: list[RolloutRecord]

def __post_init__(self) -> None:
if self.input_ids.dim() != 2:
raise ValueError(f"input_ids must be 2-D; got {tuple(self.input_ids.shape)}")
if self.attention_mask.shape != self.input_ids.shape:
raise ValueError(f"attention_mask shape {tuple(self.attention_mask.shape)} does not "
f"match input_ids {tuple(self.input_ids.shape)}")
B = self.input_ids.shape[0]
if self.response_start_idx.shape != (B, ):
raise ValueError(f"response_start_idx must be 1-D of length {B}; got "
f"{tuple(self.response_start_idx.shape)}")
for i, sample in enumerate(self.samples):
if len(sample.attention_mask) != len(sample.tokens):
raise ValueError(f"samples[{i}] attention_mask length {len(sample.attention_mask)} does not "
f"match tokens length {len(sample.tokens)}")

@property
def batch_size(self) -> int:
return int(self.input_ids.shape[0])
return len(self.samples)

@property
def seq_len(self) -> int:
return int(self.input_ids.shape[1])
return max(len(sample.tokens) for sample in self.samples)


class RolloutEngine(ABC):
Expand Down
47 changes: 41 additions & 6 deletions deepspeed/runtime/rollout/continuous_batching.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,18 @@

from collections import deque
from dataclasses import dataclass
from typing import Hashable
from typing import Hashable, Optional

import torch


@dataclass(frozen=True)
class ContinuousBatchRequest:
"""A request waiting for a slot in a continuous decode batch."""

request_id: Hashable
# Tokens the request may generate; None uses the scheduler's max_new_tokens.
max_new_tokens: Optional[int] = None


@dataclass(frozen=True)
Expand Down Expand Up @@ -49,8 +53,8 @@ def admitted_slots(self) -> tuple[int, ...]:
class ContinuousBatchScheduler:
"""FIFO scheduler for bounded, slot-based continuous batching.

All submitted requests share the scheduler's ``max_new_tokens`` budget;
requests may still retire earlier when the model emits EOS.
A request generates up to its own ``max_new_tokens``, or the scheduler's when
it has none; requests may still retire earlier when the model emits EOS.
``schedule`` performs admission/retirement without advancing tokens.
``advance`` represents one decode step for every active request and also
retires requests whose token budget has been consumed. A caller may pass
Expand All @@ -77,13 +81,19 @@ def active(self) -> tuple[ContinuousBatchRequest, ...]:
def pending(self) -> tuple[ContinuousBatchRequest, ...]:
return tuple(self._pending)

def submit(self, request: ContinuousBatchRequest) -> None:
def submit(self, request: ContinuousBatchRequest, front: bool = False) -> None:
"""Queue a request, optionally ahead of those already waiting; a retired request may return."""
if not isinstance(request, ContinuousBatchRequest):
raise TypeError("request must be a ContinuousBatchRequest")
if request.request_id in self._known_ids:
raise ValueError(f"duplicate request_id: {request.request_id!r}")
if request.max_new_tokens is not None and request.max_new_tokens <= 0:
raise ValueError("max_new_tokens must be positive")
self._known_ids.add(request.request_id)
self._pending.append(request)
if front:
self._pending.appendleft(request)
else:
self._pending.append(request)

def schedule(self, finished_ids=()) -> ContinuousBatchUpdate:
finished_ids = tuple(finished_ids)
Expand Down Expand Up @@ -115,6 +125,16 @@ def schedule(self, finished_ids=()) -> ContinuousBatchUpdate:
self._known_ids.discard(request_id)
return ContinuousBatchUpdate(tuple(request for request, _ in survivors), keep_slots, retired, tuple(admitted))

def will_free_slot(self, finished_ids=()) -> bool:
"""Whether ``advance(finished_ids)`` leaves a row free, so a request queued now could be admitted."""
if len(self._active) < self.max_batch_size or finished_ids:
return True
for request, generated in self._active:
limit = request.max_new_tokens if request.max_new_tokens is not None else self.max_new_tokens
if generated + 1 >= limit:
return True
return False

def advance(self, finished_ids=()) -> ContinuousBatchUpdate:
explicit_finished = set(finished_ids)
active_ids = {request.request_id for request, _ in self._active}
Expand All @@ -126,8 +146,23 @@ def advance(self, finished_ids=()) -> ContinuousBatchUpdate:
for request, generated in self._active:
generated += 1
self._generated[request.request_id] = generated
if generated >= self.max_new_tokens:
limit = request.max_new_tokens if request.max_new_tokens is not None else self.max_new_tokens
if generated >= limit:
finished.add(request.request_id)
updated.append((request, generated))
self._active = updated
return self.schedule(finished)


@dataclass
class ContinuousGraphState:
signature: tuple
cache: object
static_input: torch.Tensor
static_attention: torch.Tensor
static_causal_attention: torch.Tensor
static_position_ids: torch.Tensor
static_write_positions: torch.Tensor
static_cache_position: torch.Tensor
graph: object
static_logits: torch.Tensor
Loading
Loading