Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
11 changes: 9 additions & 2 deletions deepspeed/runtime/rollout/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- :class:`RolloutRequest`, :class:`RolloutBatch`, :class:`SamplingConfig` — dataclasses
- :class:`ResponseTokenBatch` — response-only causal training targets
- :class:`HybridEngineRollout` — concrete implementation using DeepSpeed hybrid engine
- :class:`AutoTPRollout` — rollout with an AutoTP tensor-parallel copy of the model
- :func:`build_rollout` — factory that selects the engine from config
"""

Expand All @@ -19,9 +20,11 @@
SamplingConfig,
)
from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout
from deepspeed.runtime.rollout.autotp_rollout import AutoTPRollout
from deepspeed.runtime.rollout.opsd import JSDLossOutput, ResponseTokenBatch, generalized_jsd_loss

__all__ = [
"AutoTPRollout",
"HybridEngineRollout",
"JSDLossOutput",
"RolloutBatch",
Expand All @@ -40,7 +43,7 @@ def build_rollout(rollout_cfg, student_engine=None, tokenizer=None, **kwargs):

Args:
rollout_cfg: :class:`RolloutConfig` (or any object with an ``engine``
attribute set to ``"hybrid_engine"``).
attribute set to ``"hybrid_engine"`` or ``"autotp"``).
student_engine: DeepSpeed engine wrapping the student model.
tokenizer: HuggingFace tokenizer.
"""
Expand All @@ -49,5 +52,9 @@ def build_rollout(rollout_cfg, student_engine=None, tokenizer=None, **kwargs):
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 engine_name == "autotp":
if student_engine is None or tokenizer is None:
raise ValueError("autotp rollout needs both student_engine and tokenizer")
return AutoTPRollout(engine=student_engine, tokenizer=tokenizer, cfg=rollout_cfg)

raise ValueError(f"Unknown rollout engine {engine_name!r}; choose from 'hybrid_engine'")
raise ValueError(f"Unknown rollout engine {engine_name!r}; choose from 'hybrid_engine', 'autotp'")
204 changes: 204 additions & 0 deletions deepspeed/runtime/rollout/autotp_rollout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# SPDX-License-Identifier: Apache-2.0

# DeepSpeed Team
"""Rollout engine that generates with an AutoTP tensor-parallel copy of the training model.

The training engine keeps the model in its ZeRO layout. This engine keeps a second, inference
copy of the same model sharded with AutoTP (``init_inference`` without kernel injection), and
``sync_weights`` refreshes that copy in memory from the training engine's fp32 masters:

* gather: ``safe_get_full_fp32_param`` reassembles each ZeRO-partitioned master weight.
* slice: ``_resolve_autotp_partition`` cuts it into this rank's shard, using the layout
metadata every AutoTP layer records on its weight (the same function that restores a
universal checkpoint into AutoTP, so the two cannot disagree on a layout).

One tensor-parallel group spans all ranks, so the ranks generate together: each rank's prompts
are gathered, the union is generated once, and every rank keeps its own samples.

Supported: the ``model.generate()`` path. Not supported yet: graph capture, shared prefill, and
continuous batching.
"""

import time
from copy import deepcopy
from types import SimpleNamespace

import torch

from deepspeed import comm as dist
from deepspeed.accelerator import get_accelerator
from deepspeed.checkpoint.universal_checkpoint import _resolve_autotp_partition
from deepspeed.runtime.rollout.base import RolloutBatch, RolloutRequest
from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout
from deepspeed.utils import safe_get_full_fp32_param


def _params_with_owner(module):
"""Map each parameter name to (parameter, the module that owns it)."""
owned = {}
for module_name, owner in module.named_modules():
for param_name, param in owner.named_parameters(recurse=False):
full_name = f"{module_name}.{param_name}" if module_name else param_name
owned[full_name] = (param, owner)
return owned


@torch.no_grad()
def sync_autotp_weights(train_module, tp_module):
"""Overwrite every parameter of ``tp_module`` with the current fp32 masters of ``train_module``.

Every rank must call this: the gather is a collective, and ``named_parameters`` yields the
same order on every rank, so the collectives pair up the same tensor everywhere.
Returns the number of tensors copied.
"""
tp_params = _params_with_owner(tp_module)
copied = 0
for tp_name, train_param in train_module.named_parameters():

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 Synchronize checkpoint-backed buffers with model weights

For models with checkpoint-backed buffers, the inference copy is created from config defaults and this loop copies only named_parameters(), so sync_weights can report success while leaving different model state behind. A concrete supported case is the fp32 e_score_correction_bias buffer used for MoE routing by DeepSeek-V3/GLM models (runtime/keep_in_fp32.py); the rollout copy keeps its default value (and potentially the wrong dtype), silently routing tokens differently from the training model. Copy matching buffers while preserving their source dtype, or reject models whose nonconstant buffers cannot be mapped.

Useful? React with 👍 / 👎.

full = safe_get_full_fp32_param(train_param)
assert full is not None, f"{tp_name} has no ZeRO fp32 master; is the optimizer a ZeRO optimizer?"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle frozen parameters without fp32 masters

When the training module contains any requires_grad=False parameter, safe_get_full_fp32_param returns None (ZeRO-3 explicitly does so, and ZeRO-1/2 only attach hp mappings to optimizer parameters), so the constructor's mandatory first sync aborts here. Partial fine-tuning commonly freezes embeddings or blocks, but those unchanged tensors still need to exist in the inference copy and can be gathered/copied from current model state when no optimizer master exists.

Useful? React with 👍 / 👎.

assert tp_name in tp_params, f"inference model has no parameter {tp_name}"
tp_param, owner = tp_params[tp_name]

# Only AutoTP layers carry tp_index; other modules (norms, embeddings) are replicated.
tp_rank = getattr(owner, "tp_index", 0)
tp_world_size = getattr(owner, "tp_world_size", 1)
shard = _resolve_autotp_partition(tp_param, {}, full, tp_rank, tp_world_size)
if shard is None:
assert full.shape == tp_param.shape, (
f"{tp_name}: no AutoTP layout recorded, but full shape {tuple(full.shape)} != "
f"inference shape {tuple(tp_param.shape)}")
shard = full
# copy_ rounds fp32 to the inference dtype the same way ZeRO rounds its low-precision params.
tp_param.copy_(shard.view(tp_param.shape))
copied += 1

assert copied == len(tp_params), f"synced {copied} tensors, but the inference model has {len(tp_params)}"
return copied


class AutoTPRollout(HybridEngineRollout):
"""Single-turn rollout with an AutoTP copy of the training model, refreshed by ``sync_weights``.

Args:
engine: DeepSpeed ZeRO training engine whose ``module`` is the Hugging Face causal LM.
tokenizer: HuggingFace tokenizer (must have pad_token_id or eos_token_id).
cfg: Rollout config; ``use_graph_capture`` and ``use_shared_prefill`` must be off.
"""

name = "autotp"

def __init__(self, engine, tokenizer, cfg=None):
super().__init__(engine=engine, tokenizer=tokenizer, cfg=cfg)
if self.use_graph_capture or self.use_shared_prefill:
raise NotImplementedError("AutoTP rollout supports the generate() path only; turn off "
"use_graph_capture and use_shared_prefill")
self.train_engine = engine
self.tp_size = dist.get_world_size()
# HybridEngineRollout generates through self.engine.module, so point it at the AutoTP copy.
self.engine = SimpleNamespace(module=self._build_tp_copy(engine.module))

# Every rank must sample the same tokens, so all ranks draw from one seed per generate call.
seed = torch.randint(0, 2**31 - 1, (1, ), device=get_accelerator().current_device_name())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore training RNG state after constructing the TP copy

When rollout is constructed after the training run has been seeded, _build_tp_copy consumes accelerator RNG while initializing every new parameter and init_inference broadcasts rank 0's resulting RNG state, then this draw advances it again. Unlike _generate_with_shared_seed, the constructor never restores the caller's state, so merely enabling rollout changes subsequent dropout randomness and can overwrite rank-specific streams. Snapshot CPU and accelerator RNG states before copy/seed creation and restore them afterward.

Useful? React with 👍 / 👎.

dist.broadcast(seed, src=0)
self._seed = seed.item()
self._generate_calls = 0
self.last_sync = None
# The copy starts with random weights; it must never generate before its first sync.
self.sync_weights(step=0)

def _build_tp_copy(self, train_model):
# Imported here: deepspeed/__init__.py imports the runtime, so a top-level import would be circular.
import deepspeed
from transformers import AutoModelForCausalLM

dtype = next(train_model.parameters()).dtype
# Built on the accelerator with random weights: sync_weights overwrites every tensor, so
# loading weights from disk here would only cost time and host memory.
with torch.device(get_accelerator().current_device_name()):
model = AutoModelForCausalLM.from_config(train_model.config,
Comment on lines +117 to +118

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 Shard the inference copy before placing it on the accelerator

For a model whose full replica cannot coexist with the ZeRO training model on one device—the intended reason to tensor-shard rollout—this context creates and initializes the entire unsharded CausalLM on every accelerator, while init_inference does not shard it until afterward. Peak per-rank memory is therefore the training state plus a full inference model rather than one TP shard, so realistic jobs can OOM in the constructor even when the final layout fits. Instantiate on meta/host and materialize only after AutoTP partitions the model, then record the resulting peak-memory validation.

AGENTS.md reference: AGENTS.md:L37-L37

Useful? React with 👍 / 👎.

dtype=dtype,

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 Pass torch_dtype to supported Transformers releases

When DeepSpeed is installed with the declared Transformers minimums (requirements/requirements-inf.txt allows 4.32.1 and the dev requirement is 4.51.3), PreTrainedModel._from_config consumes torch_dtype, not the newer dtype kwarg; dtype is instead forwarded to constructors such as LlamaForCausalLM.__init__, which reject it. Consequently build_rollout(..., engine="autotp") fails before AutoTP starts on those supported releases. Pass torch_dtype=dtype (which newer releases still accept) or raise the Transformers minimum.

Useful? React with 👍 / 👎.

attn_implementation=train_model.config._attn_implementation)
model.generation_config = deepcopy(train_model.generation_config)
inference_engine = deepspeed.init_inference(model.eval(),
config={
"dtype": dtype,
"tensor_parallel": {
"tp_size": self.tp_size
},
"replace_with_kernel_inject": False,
"enable_cuda_graph": False,
})
return inference_engine.module

def sync_weights(self, step: int) -> None:
"""Copy the training engine's current weights into the AutoTP copy (collective)."""
accelerator = get_accelerator()
accelerator.synchronize()
start = time.perf_counter()
copied = sync_autotp_weights(self.train_engine.module, self.engine.module)
accelerator.synchronize()
self.last_sync = {"step": step, "tensors": copied, "seconds": time.perf_counter() - start}

@torch.no_grad()
def generate(self, request, sampling):
if sampling.continuous_batch_size is not None:
raise NotImplementedError("AutoTP rollout does not support continuous batching")
rank = dist.get_rank()
gathered = [None] * self.tp_size
dist.all_gather_object(gathered, (request.prompt_ids.cpu(), request.prompt_attention_mask.cpu()))
union_request = self._left_padded_union(gathered, request.prompt_ids.device)

batch = self._generate_with_shared_seed(union_request, sampling)
self._check_same_tokens_on_all_ranks(batch)

# Generation keeps each prompt's n copies adjacent and in prompt order.
n = sampling.n_samples_per_prompt
counts = [prompt_ids.shape[0] for prompt_ids, _ in gathered]
start = sum(counts[:rank]) * n
end = start + counts[rank] * n
# Columns added only because another rank's prompts were longer are all padding here; dropping
# them returns the [B', T_p + T_r] layout that this rank's own request promises.
extra_columns = union_request.prompt_ids.shape[1] - request.prompt_ids.shape[1]
return RolloutBatch(input_ids=batch.input_ids[start:end, extra_columns:],
attention_mask=batch.attention_mask[start:end, extra_columns:],
response_start_idx=batch.response_start_idx[start:end] - extra_columns)

def _left_padded_union(self, gathered, device):
"""Stack every rank's left-padded prompts into one request; ranks' prompt widths can differ."""
pad_token_id = self.tokenizer.pad_token_id
if pad_token_id is None:
pad_token_id = self.tokenizer.eos_token_id
if pad_token_id is None:
raise ValueError("The tokenizer must define pad_token_id or eos_token_id")

width = max(prompt_ids.shape[1] for prompt_ids, _ in gathered)
all_ids = []
all_masks = []
for prompt_ids, attention_mask in gathered:
padding = (width - prompt_ids.shape[1], 0)
all_ids.append(torch.nn.functional.pad(prompt_ids, padding, value=pad_token_id))
all_masks.append(torch.nn.functional.pad(attention_mask, padding, value=0))
return RolloutRequest(prompt_ids=torch.cat(all_ids).to(device),
prompt_attention_mask=torch.cat(all_masks).to(device))

def _generate_with_shared_seed(self, request, sampling):
accelerator = get_accelerator()
# Restored below so that generating does not change the caller's training randomness.
cpu_rng_state = torch.get_rng_state()
device_rng_state = accelerator.get_rng_state()
seed = self._seed + self._generate_calls
self._generate_calls += 1
try:
torch.manual_seed(seed)
accelerator.manual_seed(seed)
return super().generate(request, sampling)
finally:
torch.set_rng_state(cpu_rng_state)
accelerator.set_rng_state(device_rng_state)

def _check_same_tokens_on_all_ranks(self, batch):
gathered = [None] * self.tp_size
input_ids = batch.input_ids.cpu()
dist.all_gather_object(gathered, input_ids)
if any(not torch.equal(other, input_ids) for other in gathered):
raise RuntimeError("AutoTP ranks generated different tokens; the tensor-parallel copy is out of sync")
26 changes: 26 additions & 0 deletions docs/code-docs/source/inference-engine.rst
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,32 @@ does not advance the cache or synchronize a device tensor to the host.
This is a targeted query-offset compatibility fix, not a guarantee of support
for every Transformers 5.20 cache API.

AutoTP Rollout (experimental)
-----------------------------

``AutoTPRollout`` generates with a separate tensor-parallel copy of the training
model, sharded across all ranks with AutoTP (``init_inference`` without kernel
injection). Select it with ``build_rollout`` and ``engine="autotp"``.

The training engine keeps its ZeRO layout. Call ``rollout.sync_weights(step)``
after each optimizer step and before generating: it gathers each parameter's
full fp32 master weight from ZeRO and copies this rank's AutoTP shard into the
inference copy, in memory. Shards are cut with the layout metadata each AutoTP
layer records, the same metadata used to restore a universal checkpoint into
AutoTP. The constructor runs one sync, so the copy never generates with its
initial weights.

All ranks form one tensor-parallel group, so they generate together: each
rank's prompts are gathered, the union is generated once, and each rank gets
back only its own rows, in its own ``[B', T_p + T_r]`` layout. Every rank samples
from the same seed, and generation raises an error if the ranks' tokens differ.

The inference copy costs roughly one more model's worth of memory on top of
training, divided by the number of ranks. Only the ``generate()`` path is
supported; ``use_graph_capture``, ``use_shared_prefill`` and continuous batching
are rejected. Models with tied input and output embeddings fail the first sync,
because AutoTP shards the output head separately. Contact: OkoroAchraf on GitHub.

OPSD response-token utilities
-----------------------------

Expand Down
Loading
Loading