diff --git a/deepspeed/runtime/rollout/__init__.py b/deepspeed/runtime/rollout/__init__.py index a7af574ff419..f44232bfea83 100644 --- a/deepspeed/runtime/rollout/__init__.py +++ b/deepspeed/runtime/rollout/__init__.py @@ -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 """ @@ -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", @@ -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. """ @@ -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'") diff --git a/deepspeed/runtime/rollout/autotp_rollout.py b/deepspeed/runtime/rollout/autotp_rollout.py new file mode 100644 index 000000000000..076e35316aca --- /dev/null +++ b/deepspeed/runtime/rollout/autotp_rollout.py @@ -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(): + 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?" + 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()) + 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, + dtype=dtype, + 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") diff --git a/docs/code-docs/source/inference-engine.rst b/docs/code-docs/source/inference-engine.rst index 67f6620be630..f720e38a1997 100644 --- a/docs/code-docs/source/inference-engine.rst +++ b/docs/code-docs/source/inference-engine.rst @@ -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 ----------------------------- diff --git a/tests/unit/runtime/rollout/test_autotp_rollout.py b/tests/unit/runtime/rollout/test_autotp_rollout.py new file mode 100644 index 000000000000..c2c88d70d8a9 --- /dev/null +++ b/tests/unit/runtime/rollout/test_autotp_rollout.py @@ -0,0 +1,251 @@ +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +"""CPU unit tests for AutoTPRollout. + +Two simulated TP ranks are built in one process: AutoTP layers read their rank from +``deepspeed.comm``, which is patched, so the layers partition and record their layout metadata +exactly as they do under ``init_inference``. The ZeRO gather is patched to return the full weight. +""" + +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest +import torch + +from deepspeed.module_inject import layers as autotp_layers +from deepspeed.module_inject.layers import LinearAllreduce, LinearLayer +from deepspeed.runtime.rollout import build_rollout +from deepspeed.runtime.rollout import autotp_rollout +from deepspeed.runtime.rollout.autotp_rollout import AutoTPRollout, sync_autotp_weights +from deepspeed.runtime.rollout.base import RolloutBatch, RolloutConfig, RolloutRequest, SamplingConfig +from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout, HybridEngineRolloutConfig + +TP_SIZE = 2 +PAD = 0 +RESPONSE_TOKENS = 1 + + +class _Block(torch.nn.Module): + """Embedding, a column-parallel and a row-parallel projection, and a norm: one of each layout.""" + + def __init__(self): + super().__init__() + self.embed = torch.nn.Embedding(10, 8) + self.up = torch.nn.Linear(8, 12, bias=True) + self.down = torch.nn.Linear(12, 8, bias=True) + self.norm = torch.nn.LayerNorm(8) + + +def _train_module(): + """The training engine's module, with weights unrelated to the AutoTP copy's initial ones.""" + torch.manual_seed(0) + return _Block() + + +def _tp_copy(tp_rank, dtype): + """Rank ``tp_rank``'s AutoTP copy, initialized with weights unrelated to the training module.""" + torch.manual_seed(1) + block = _Block().to(dtype) + with patch.object(autotp_layers.dist, "get_world_size", return_value=TP_SIZE), \ + patch.object(autotp_layers.dist, "get_rank", return_value=tp_rank): + block.up = LinearLayer(block.up, mp_group=object(), name="up") + block.down = LinearAllreduce(block.down, mp_group=object(), name="down") + return block + + +def _sync(train_module, tp_module): + # ZeRO-2 keeps a full low-precision copy on every rank, so the gather's result is its fp32 value. + with patch.object(autotp_rollout, "safe_get_full_fp32_param", side_effect=lambda p: p.detach().float()): + return sync_autotp_weights(train_module, tp_module) + + +@pytest.mark.parametrize("tp_rank", range(TP_SIZE)) +def test_sync_copies_each_layout_into_its_shard(tp_rank): + train = _train_module() + tp_module = _tp_copy(tp_rank, torch.float32) + full = dict(train.named_parameters()) + assert tp_module.up.weight.shape == (12 // TP_SIZE, 8) + assert not torch.equal(tp_module.up.weight, full["up.weight"].chunk(TP_SIZE, dim=0)[tp_rank]) + + assert _sync(train, tp_module) == len(full) + + tp = dict(tp_module.named_parameters()) + # Column-parallel: weight and bias split on the output dimension. + assert torch.equal(tp["up.weight"], full["up.weight"].chunk(TP_SIZE, dim=0)[tp_rank]) + assert torch.equal(tp["up.bias"], full["up.bias"].chunk(TP_SIZE, dim=0)[tp_rank]) + # Row-parallel: weight split on the input dimension, bias replicated. + assert torch.equal(tp["down.weight"], full["down.weight"].chunk(TP_SIZE, dim=1)[tp_rank]) + assert torch.equal(tp["down.bias"], full["down.bias"]) + # Modules AutoTP did not replace are copied whole. + for name in ("embed.weight", "norm.weight", "norm.bias"): + assert torch.equal(tp[name], full[name]) + + +def test_sync_rounds_fp32_masters_to_the_inference_dtype(): + train = _train_module() + tp_module = _tp_copy(0, torch.bfloat16) + _sync(train, tp_module) + full = dict(train.named_parameters()) + assert tp_module.down.weight.dtype == torch.bfloat16 + assert torch.equal(tp_module.down.weight, full["down.weight"].chunk(TP_SIZE, dim=1)[0].to(torch.bfloat16)) + + +def test_sync_rejects_an_inference_copy_missing_a_parameter(): + train = _train_module() + tp_module = _tp_copy(0, torch.float32) + del tp_module.norm + with pytest.raises(AssertionError, match="no parameter norm.weight"): + _sync(train, tp_module) + + +def test_sync_rejects_a_training_model_missing_a_parameter(): + train = _train_module() + del train.norm + with pytest.raises(AssertionError, match="synced"): + _sync(train, _tp_copy(0, torch.float32)) + + +@pytest.mark.parametrize("option", ["use_graph_capture", "use_shared_prefill"]) +def test_constructor_rejects_unsupported_generation_paths(option): + # Both paths drive engine and cache internals that the AutoTP copy does not provide. + with pytest.raises(NotImplementedError, match=option): + AutoTPRollout(MagicMock(), MagicMock(), cfg=HybridEngineRolloutConfig(**{option: True})) + + +def test_engine_factory_autotp_requires_student_engine(): + with pytest.raises(ValueError, match="needs both"): + build_rollout(RolloutConfig(engine="autotp")) + + +# -- generate: one TP group spans all ranks, so each rank generates the union of all prompts ------ + + +def _rollout(): + rollout = AutoTPRollout.__new__(AutoTPRollout) + rollout.tp_size = TP_SIZE + rollout.tokenizer = SimpleNamespace(pad_token_id=PAD, eos_token_id=2) + rollout._seed = 1234 + rollout._generate_calls = 0 + return rollout + + +def _prompts(*rows): + """A left-padded request; a row's zeros are padding.""" + prompt_ids = torch.tensor(rows, dtype=torch.long) + return RolloutRequest(prompt_ids=prompt_ids, prompt_attention_mask=(prompt_ids != PAD).long()) + + +def _fake_union_generate(seen): + """Stand-in for HybridEngineRollout.generate under the RolloutBatch contract: n adjacent copies per + prompt in prompt order, with the row's position in the union as its response token.""" + + def generate(self, request, sampling): + seen.append((torch.initial_seed(), request)) + n = sampling.n_samples_per_prompt + prompt_ids = request.prompt_ids.repeat_interleave(n, dim=0) + prompt_mask = request.prompt_attention_mask.repeat_interleave(n, dim=0) + total = prompt_ids.shape[0] + responses = 100 + torch.arange(total).unsqueeze(1) + return RolloutBatch(input_ids=torch.cat([prompt_ids, responses], dim=1), + attention_mask=torch.cat([prompt_mask, torch.ones_like(responses)], dim=1), + response_start_idx=torch.full((total, ), prompt_ids.shape[1], dtype=torch.long)) + + return generate + + +def _generate(rank, per_rank_requests, n_samples_per_prompt=1, gathered_tokens=None, rollout=None): + rollout = rollout or _rollout() + seen = [] + + def all_gather_object(output, obj): + if isinstance(obj, tuple): + output[:] = [(request.prompt_ids, request.prompt_attention_mask) for request in per_rank_requests] + else: # the token check: every rank reports what this rank generated, unless overridden + output[:] = gathered_tokens(obj) if gathered_tokens else [obj] * TP_SIZE + + with patch.object(autotp_rollout.dist, "get_rank", return_value=rank), \ + patch.object(autotp_rollout.dist, "all_gather_object", side_effect=all_gather_object), \ + patch.object(HybridEngineRollout, "generate", _fake_union_generate(seen)): + sampling = SamplingConfig(max_new_tokens=RESPONSE_TOKENS, n_samples_per_prompt=n_samples_per_prompt) + batch = rollout.generate(per_rank_requests[rank], sampling) + return rollout, batch, seen + + +@pytest.mark.parametrize("rank, expected_prompts, expected_responses", [(0, [[7], [8]], [100, 101, 102, 103]), + (1, [[9]], [104, 105])]) +def test_generate_returns_only_this_ranks_rows(rank, expected_prompts, expected_responses): + per_rank = [_prompts([7], [8]), _prompts([9])] + _, batch, _ = _generate(rank, per_rank, n_samples_per_prompt=2) + expected_rows = [ + prompt + [response] + for prompt, response in zip([p for p in expected_prompts for _ in range(2)], expected_responses) + ] + assert batch.input_ids.tolist() == expected_rows + + +@pytest.mark.parametrize("rank, expected_ids, expected_mask, expected_start", [ + (0, [[0, 7, 100]], [[0, 1, 1]], [2]), + (1, [[8, 9, 10, 101]], [[1, 1, 1, 1]], [3]), +]) +def test_generate_keeps_each_ranks_own_layout_when_prompt_widths_differ(rank, expected_ids, expected_mask, + expected_start): + # A rank with short prompts must get back [B', T_p + T_r] for its own T_p, or its response + # boundary would not match the request it made. + per_rank = [_prompts([0, 7]), _prompts([8, 9, 10])] + _, batch, _ = _generate(rank, per_rank) + assert batch.input_ids.tolist() == expected_ids + assert batch.attention_mask.tolist() == expected_mask + assert batch.response_start_idx.tolist() == expected_start + + +def test_generate_left_pads_the_union_without_attending_to_the_padding(): + per_rank = [_prompts([7]), _prompts([8, 9])] + _, _, seen = _generate(0, per_rank) + _, union = seen[0] + assert union.prompt_ids.tolist() == [[PAD, 7], [8, 9]] + assert union.prompt_attention_mask.tolist() == [[0, 1], [1, 1]] + + +def test_generate_seeds_every_rank_alike_and_each_call_differently(): + per_rank = [_prompts([7]), _prompts([9])] + seeds_per_rank = [] + for rank in range(TP_SIZE): + rollout = _rollout() + seeds = [] + for _ in range(2): + _, _, seen = _generate(rank, per_rank, rollout=rollout) + seeds += [seed for seed, _ in seen] + seeds_per_rank.append(seeds) + # Ranks that sample from different seeds pick different tokens and deadlock in AutoTP's all-reduce. + assert seeds_per_rank[0] == seeds_per_rank[1] + # Reusing one seed would make every rollout step draw the same samples for the same prompts. + assert seeds_per_rank[0][0] != seeds_per_rank[0][1] + + +def test_generate_leaves_the_callers_random_stream_unchanged(): + # Otherwise, turning rollout on would change the training run's dropout and data shuffling. + per_rank = [_prompts([7]), _prompts([9])] + torch.manual_seed(42) + expected = torch.rand(1) + torch.manual_seed(42) + _generate(0, per_rank) + assert torch.equal(torch.rand(1), expected) + + +def test_generate_fails_loudly_when_ranks_disagree(): + per_rank = [_prompts([7]), _prompts([9])] + + def diverged(input_ids): + other = input_ids.clone() + other[0, -1] = 99 + return [input_ids, other] + + with pytest.raises(RuntimeError, match="different tokens"): + _generate(0, per_rank, gathered_tokens=diverged) + + +def test_generate_rejects_continuous_batching(): + with pytest.raises(NotImplementedError, match="continuous batching"): + _rollout().generate(_prompts([7]), SamplingConfig(max_new_tokens=1, continuous_batch_size=4)) diff --git a/tests/unit/v1/test_autotp_rollout_v1.py b/tests/unit/v1/test_autotp_rollout_v1.py new file mode 100644 index 000000000000..478f9a3f4200 --- /dev/null +++ b/tests/unit/v1/test_autotp_rollout_v1.py @@ -0,0 +1,101 @@ +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +"""End-to-end AutoTPRollout test: a real ZeRO engine, real AutoTP sharding and Hugging Face generate().""" + +from types import SimpleNamespace + +import pytest +import torch +import transformers + +import deepspeed +from deepspeed import comm as dist +from deepspeed.accelerator import get_accelerator +from deepspeed.runtime.rollout import RolloutConfig, RolloutRequest, SamplingConfig, build_rollout +from deepspeed.utils import safe_get_full_fp32_param +from unit.common import DistributedTest + +PAD = 0 +NEW_TOKENS = 6 + + +def _tiny_config(): + # Every dimension AutoTP splits is several times tp_grain_size (64), so no rank gets an empty shard. + return transformers.LlamaConfig(vocab_size=512, + hidden_size=256, + intermediate_size=512, + num_hidden_layers=2, + num_attention_heads=4, + num_key_value_heads=4, + max_position_embeddings=64, + tie_word_embeddings=False, + attn_implementation="eager") + + +def _greedy_by_unsharded_model(config, train_module, prompt_ids): + """The independent oracle: the same masters in an ordinary model, one prompt at a time.""" + # The gather is a collective, so every rank builds this once however many prompts it has. + masters = {name: safe_get_full_fp32_param(param) for name, param in train_module.named_parameters()} + model = transformers.AutoModelForCausalLM.from_config(config, dtype=torch.float32).to(prompt_ids.device).eval() + model.load_state_dict(masters) + rows = [] + for row in prompt_ids.split(1): + rows.append( + model.generate(row, + attention_mask=(row != PAD).long(), + max_new_tokens=NEW_TOKENS, + do_sample=False, + eos_token_id=None, + pad_token_id=PAD)) + return torch.cat(rows) + + +@pytest.mark.parametrize("zero_stage", [1, 2, 3]) +class TestAutoTPRollout(DistributedTest): + world_size = 2 + + def test_generation_follows_the_training_engine(self, zero_stage): + device = get_accelerator().current_device_name() + torch.manual_seed(0) + config = _tiny_config() + model = transformers.AutoModelForCausalLM.from_config(config, dtype=torch.float32) + engine, _, _, _ = deepspeed.initialize(model=model, + optimizer=torch.optim.SGD(model.parameters(), lr=0.5), + config={ + "train_micro_batch_size_per_gpu": 1, + "zero_allow_untested_optimizer": True, + "zero_optimization": { + "stage": zero_stage + }, + }) + tokenizer = SimpleNamespace(pad_token_id=PAD, eos_token_id=None) + rollout = build_rollout(RolloutConfig(engine="autotp"), student_engine=engine, tokenizer=tokenizer) + + # The ranks ask for different numbers of prompts, of different widths. + if dist.get_rank() == 0: + prompt_ids = torch.tensor([[PAD, 5, 6], [7, 8, 9]], device=device) + else: + prompt_ids = torch.tensor([[3, 4, 5, 6, 7]], device=device) + request = RolloutRequest(prompt_ids=prompt_ids, prompt_attention_mask=(prompt_ids != PAD).long()) + greedy = SamplingConfig(max_new_tokens=NEW_TOKENS, temperature=0.0) + + batch = rollout.generate(request, greedy) + assert batch.response_start_idx.tolist() == [prompt_ids.shape[1]] * prompt_ids.shape[0] + assert torch.equal(batch.input_ids, _greedy_by_unsharded_model(config, engine.module, prompt_ids)) + + # A stale inference copy would keep generating from the weights it had before this step. + labels = torch.randint(1, config.vocab_size, (2, 8), device=device) + engine.train() + engine.backward(engine(input_ids=labels, labels=labels).loss) + engine.step() + rollout.sync_weights(step=1) + batch = rollout.generate(request, greedy) + assert torch.equal(batch.input_ids, _greedy_by_unsharded_model(config, engine.module, prompt_ids)) + + # Sampling needs a shared seed: generate() itself raises if the ranks' tokens differ. + sampling = SamplingConfig(max_new_tokens=NEW_TOKENS, temperature=1.0, n_samples_per_prompt=2) + first = rollout.generate(request, sampling) + second = rollout.generate(request, sampling) + assert first.input_ids.shape == (prompt_ids.shape[0] * 2, prompt_ids.shape[1] + NEW_TOKENS) + assert not torch.equal(first.input_ids, second.input_ids)