diff --git a/deepspeed/runtime/rollout/hybrid_engine_rollout.py b/deepspeed/runtime/rollout/hybrid_engine_rollout.py index 607b4f63f72e..3291a7a35bde 100644 --- a/deepspeed/runtime/rollout/hybrid_engine_rollout.py +++ b/deepspeed/runtime/rollout/hybrid_engine_rollout.py @@ -6,12 +6,13 @@ Two generation paths: 1. **model.generate()** (default): delegates to HuggingFace generate. Supports sampling (temperature, top_p) and greedy. - 2. **graph capture + DeepSpeedStaticCache**: only for greedy (temperature=0). - Pre-allocates a StaticCache, captures the decode forward pass into a - graph, and replays it for each decode step. Eliminates kernel launch - overhead. - 3. **continuous batching (experimental)**: an opt-in bounded greedy path - selected through ``SamplingConfig.continuous_batch_size``. + 2. **graph capture + DeepSpeedStaticCache**: greedy and sampling + (temperature, top_k, top_p). Pre-allocates a StaticCache, captures the + decode forward pass into a graph, and replays it for each decode + step. Eliminates kernel launch overhead. + 3. **continuous batching (experimental)**: an opt-in bounded path + selected through ``SamplingConfig.continuous_batch_size``; greedy or + sampled like the graph path, with or without graph capture. """ import time @@ -170,8 +171,7 @@ def generate(self, request: RolloutRequest, sampling: SamplingConfig) -> Rollout accelerator.synchronize() expansion_end = time.perf_counter() - is_greedy = sampling.temperature <= 0.0 - use_graph_capture = self.use_graph_capture and is_greedy + use_graph_capture = self.use_graph_capture if use_graph_capture and not get_accelerator().is_graph_capture_supported(): # Same opt-in as the HybridEngine graph cache and the continuous # rollout path: falling back keeps backends that only expose a @@ -195,23 +195,17 @@ def generate(self, request: RolloutRequest, sampling: SamplingConfig) -> Rollout shared_prefill_handles = self._register_shared_prefill_hooks(module, B, n) if use_graph_capture: output_ids = self._generate_graph(prompt_ids, prompt_attn, max_new_tokens, pad_token_id, module, - device) + device, sampling) else: - temperature = max(sampling.temperature, 1e-8) - do_sample = not is_greedy generate_kwargs = { "attention_mask": prompt_attn, "max_new_tokens": max_new_tokens, # ZeRO-3 gathers parameters during each decode forward, so every # data-parallel rank must execute the same number of iterations. "eos_token_id": None, - "do_sample": do_sample, - "temperature": temperature if do_sample else 1.0, - "top_p": sampling.top_p if do_sample else 1.0, "pad_token_id": pad_token_id, + **self._hf_sampling_kwargs(sampling), } - if do_sample: - generate_kwargs["top_k"] = max(sampling.top_k, 0) output_ids = module.generate(prompt_ids, **generate_kwargs) finally: for handle in shared_prefill_handles: @@ -291,11 +285,11 @@ def generate(self, request: RolloutRequest, sampling: SamplingConfig) -> Rollout @torch.no_grad() def _generate_continuous(self, request, sampling, max_batch_size): - """Generate independent greedy requests in an experimental continuous batch. + """Generate independent requests in an experimental continuous batch. - Continuous batching currently requires one prompt row per request and - greedy decoding. Completed rows retire immediately and pending prompts - prefill into the released rows before the next decode step. + Continuous batching currently requires one prompt row per request. + Completed rows retire immediately and pending prompts prefill into the + released rows before the next decode step. """ original_request = request requests = tuple( @@ -313,6 +307,7 @@ def _generate_continuous(self, request, sampling, max_batch_size): return self._generate_continuous_graph(original_request, requests, sampling, max_batch_size) module = self.engine.module + select_next_tokens = self._token_selector(sampling) profile = self._start_continuous_profile() if self.enable_profiling else None profile_accelerator = profile["accelerator"] if profile is not None else None profile_start = profile["start"] if profile is not None else None @@ -479,6 +474,7 @@ def _generate_continuous(self, request, sampling, max_batch_size): prompt_lengths, model_dtype, device, + sampling, self.align_decode_fronts, profile, ) @@ -517,6 +513,7 @@ def _generate_continuous(self, request, sampling, max_batch_size): request_by_id, responses, module, + select_next_tokens, ) stats["decode_steps"] += 1 decoded_tokens = dict(zip(survivor_ids, decoded.split(1, dim=0))) @@ -561,7 +558,7 @@ def _generate_continuous(self, request, sampling, max_batch_size): @torch.no_grad() def _generate_continuous_graph(self, original_request, requests, sampling, max_batch_size): - """Run continuous greedy decoding with a fixed-capacity graph. + """Run continuous decoding with a fixed-capacity graph. Scheduler slots stay attached to physical cache rows for their whole lifetime. Retired rows are masked until a new prompt is prefetched into @@ -569,6 +566,7 @@ def _generate_continuous_graph(self, original_request, requests, sampling, max_b static tensor addresses. """ module = self.engine.module + select_next_tokens = self._token_selector(sampling) prompt_len = requests[0].prompt_ids.shape[1] self._validate_continuous_graph_options(prompt_len, sampling) if getattr(module, "_supports_cache_class", None) is False: @@ -673,6 +671,7 @@ def _generate_continuous_graph(self, original_request, requests, sampling, max_b prompt_lengths, model_dtype, device, + sampling, profile=profile, target_slots=tuple(admitted_slots), ) @@ -708,6 +707,7 @@ def _generate_continuous_graph(self, original_request, requests, sampling, max_b request_by_id, responses, module, + select_next_tokens, ) for request_id, token in zip(decode_ids, decoded.split(1, dim=0)): decoded_tokens[request_id] = token @@ -915,8 +915,6 @@ def _validate_continuous_inputs(self, requests, sampling, max_batch_size): device = requests[0].prompt_ids.device if sampling.max_new_tokens <= 0: raise ValueError("max_new_tokens must be positive") - if sampling.temperature > 0: - raise ValueError("continuous batching currently supports greedy decoding only") if sampling.n_samples_per_prompt != 1: raise ValueError("continuous batching currently supports one sample per prompt") for request in requests: @@ -950,6 +948,7 @@ def _continuous_prefill(self, prompt_lengths, model_dtype, device, + sampling, align_decode_fronts=False, profile=None, target_slots=None): @@ -974,6 +973,7 @@ def _continuous_prefill(self, prompt_attention, model_dtype, device, + sampling, ) self._profile_end(profile, "prefill_forward_ms", prefill_start, count="num_prefill_forwards") cache_copy_start = self._profile_start(profile) @@ -1008,6 +1008,7 @@ def _continuous_prefill(self, prompt_attention, model_dtype, device, + sampling, ) self._profile_end(profile, "prefill_forward_ms", prefill_start, count="num_prefill_forwards") cache_copy_start = self._profile_start(profile) @@ -1089,7 +1090,8 @@ def _finish_continuous_profile(self, profile, request, responses, max_batch_size "continuous_batch_size": max_batch_size, } - def _continuous_prefill_cache(self, module, static_cache_type, prompt_ids, prompt_attention, model_dtype, device): + def _continuous_prefill_cache(self, module, static_cache_type, prompt_ids, prompt_attention, model_dtype, device, + sampling): position_ids = self._prefill_position_ids(prompt_attention) if getattr(module, "_supports_cache_class", None) is None: pad_token_id = self.tokenizer.pad_token_id @@ -1100,10 +1102,10 @@ def _continuous_prefill_cache(self, module, static_cache_type, prompt_ids, promp attention_mask=prompt_attention, position_ids=position_ids, max_new_tokens=1, - do_sample=False, eos_token_id=None, pad_token_id=pad_token_id, return_dict_in_generate=True, + **self._hf_sampling_kwargs(sampling), ) return prefill_output.sequences[:, -1:], prefill_output.past_key_values @@ -1120,25 +1122,86 @@ def _continuous_prefill_cache(self, module, static_cache_type, prompt_ids, promp position_ids=position_ids, **self._last_logits_kwargs(module), ) - return prefill_output.logits[:, -1, :].argmax(dim=-1, keepdim=True), prefill_cache + logits = self._apply_repetition_penalty(prefill_output.logits[:, -1, :], prompt_ids, + self._repetition_penalty(module)) + return self._token_selector(sampling)(logits), prefill_cache @staticmethod - def _continuous_next_tokens(logits, request_ids, request_by_id, responses, module): + def _repetition_penalty(module): repetition_penalty = getattr(getattr(module, "generation_config", None), "repetition_penalty", 1.0) - if repetition_penalty is None: - repetition_penalty = 1.0 + return 1.0 if repetition_penalty is None else repetition_penalty + + @staticmethod + def _apply_repetition_penalty(logits, input_ids, repetition_penalty): + """Penalize the tokens of ``input_ids`` in last-position ``logits``, without changing ``logits``. + + generate() applies the penalty in float32, before the sampling warpers, so it shapes the sampled distribution. + """ if repetition_penalty == 1.0: - return logits.argmax(dim=-1, keepdim=True) - - next_tokens = [] - for row, request_id in enumerate(request_ids): - input_ids = torch.cat((request_by_id[request_id].prompt_ids, *responses[request_id]), dim=1) - row_logits = logits[row:row + 1].clone() - scores = row_logits.gather(1, input_ids) - scores = torch.where(scores < 0, scores * repetition_penalty, scores / repetition_penalty) - row_logits.scatter_(1, input_ids, scores) - next_tokens.append(row_logits.argmax(dim=-1, keepdim=True)) - return torch.cat(next_tokens, dim=0) + return logits + logits = logits.float() + scores = logits.gather(1, input_ids) + scores = torch.where(scores < 0, scores * repetition_penalty, scores / repetition_penalty) + return logits.scatter(1, input_ids, scores) + + @classmethod + def _continuous_next_tokens(cls, logits, request_ids, request_by_id, responses, module, select_next_tokens): + repetition_penalty = cls._repetition_penalty(module) + if repetition_penalty != 1.0: + logits = torch.cat([ + cls._apply_repetition_penalty( + logits[row:row + 1], + torch.cat((request_by_id[request_id].prompt_ids, *responses[request_id]), dim=1), + repetition_penalty, + ) for row, request_id in enumerate(request_ids) + ], + dim=0) + return select_next_tokens(logits) + + @staticmethod + def _hf_sampling_kwargs(sampling): + """Hugging Face ``generate()`` arguments for ``sampling``; ``temperature <= 0`` is greedy.""" + if sampling.temperature <= 0.0: + return {"do_sample": False, "temperature": 1.0, "top_p": 1.0} + return { + "do_sample": True, + "temperature": sampling.temperature, + "top_p": sampling.top_p, + "top_k": max(sampling.top_k, 0), + } + + @staticmethod + def _token_selector(sampling): + """Return a function that picks the next tokens ``[B, 1]`` from last-position logits ``[B, V]``. + + Tokens are picked after each forward or graph replay, outside any + captured graph. Sampling applies Hugging Face's temperature, top-k and + top-p warpers in the order ``generate()`` applies them, so every path + draws from the same distribution as ``generate()``. + """ + if sampling.temperature <= 0.0: + return lambda logits: logits.argmax(dim=-1, keepdim=True) + + from transformers.generation.logits_process import (TemperatureLogitsWarper, TopKLogitsWarper, + TopPLogitsWarper) + + warpers = [] + if sampling.temperature != 1.0: + warpers.append(TemperatureLogitsWarper(sampling.temperature)) + if sampling.top_k > 0: + warpers.append(TopKLogitsWarper(top_k=sampling.top_k)) + if sampling.top_p < 1.0: + warpers.append(TopPLogitsWarper(top_p=sampling.top_p)) + + def sample(logits): + # generate() also warps and samples in float32. + scores = logits.float() + for warper in warpers: + # The warpers read only the scores, not the generated ids. + scores = warper(None, scores) + return torch.multinomial(torch.softmax(scores, dim=-1), num_samples=1) + + return sample @staticmethod def _prefill_position_ids(attention_mask): @@ -1314,11 +1377,11 @@ def _pad_after_eos(output_ids, response_start, eos_token_id, pad_token_id): return output_ids, response_attn.long() # ------------------------------------------------------------------ - # Graph capture decode loop (greedy only) + # Graph capture decode loop # ------------------------------------------------------------------ - def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, module, device): - """Greedy decode with DeepSpeedStaticCache + graph capture.""" + def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, module, device, sampling): + """Decode with DeepSpeedStaticCache + graph capture, greedy or sampled per ``sampling``.""" from transformers import StaticCache from deepspeed.utils.static_cache import DeepSpeedStaticCache @@ -1330,6 +1393,14 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, max_len = prompt_len + max_new_tokens eos_token_id = self.tokenizer.eos_token_id model_dtype = next(module.parameters()).dtype + select_next_tokens = self._token_selector(sampling) + repetition_penalty = self._repetition_penalty(module) + output_ids = [prompt_ids] + + def next_tokens(logits): + if repetition_penalty != 1.0: + logits = self._apply_repetition_penalty(logits, torch.cat(output_ids, dim=1), repetition_penalty) + return select_next_tokens(logits) # --- Prefill with HF StaticCache (correct attention semantics) --- prefill_cache = self._create_static_cache(StaticCache, module.config, batch_size, max_len, device, model_dtype) @@ -1343,7 +1414,8 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, cache_position=torch.arange(prompt_len, device=device), **self._last_logits_kwargs(module), ) - next_token = prefill_out.logits[:, -1, :].argmax(dim=-1, keepdim=True) + next_token = next_tokens(prefill_out.logits[:, -1, :]) + output_ids.append(next_token) # --- Copy prefill KV into DeepSpeedStaticCache --- write_pos = torch.tensor(prompt_len - 1, dtype=torch.long, device=device) @@ -1364,8 +1436,6 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, ds_layer.keys[:, :, :prompt_len, :].copy_(hf_keys[:, :, :prompt_len, :]) ds_layer.values[:, :, :prompt_len, :].copy_(hf_values[:, :, :prompt_len, :]) - output_ids = [prompt_ids, next_token] - # --- Static buffers for graph capture --- static_token = torch.zeros(batch_size, 1, dtype=torch.long, device=device) static_attn = torch.zeros(batch_size, max_len, dtype=torch.long, device=device) @@ -1440,7 +1510,7 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, # Replay get_accelerator().replay_graph(graph) - next_token = static_logits[:, -1, :].argmax(dim=-1, keepdim=True) + next_token = next_tokens(static_logits[:, -1, :]) output_ids.append(next_token) eos_mask |= (next_token.squeeze(1) == eos_token_id) diff --git a/docs/code-docs/source/inference-engine.rst b/docs/code-docs/source/inference-engine.rst index 67f6620be630..461f5d101eee 100644 --- a/docs/code-docs/source/inference-engine.rst +++ b/docs/code-docs/source/inference-engine.rst @@ -60,6 +60,21 @@ For benchmark matrices, cases execute from the largest effective batch to the smallest because HybridEngine sizes its inference workspace on the first forward. Results remain in the user-requested matrix order. +HybridEngine Rollout CUDA Graph Decode +-------------------------------------- + +``HybridEngineRolloutConfig(use_graph_capture=True)`` captures the decode +forward pass in a CUDA graph and replays it for every generated token. Only the +model forward is captured; the next token is chosen from the graph's output +logits after each replay. Greedy decoding (``temperature <= 0``) takes the +argmax. Sampling applies the ``temperature``, ``top_k`` and ``top_p`` settings +of ``SamplingConfig`` with Hugging Face's logits warpers, in the order +``generate()`` applies them, so both paths sample from the same distribution. +Both greedy decoding and sampling first apply the repetition penalty from the +model's ``generation_config``, as ``generate()`` does. Other +``generation_config`` settings are not applied on the graph path. Continuous +batching, with or without graph capture, picks tokens the same way. + Shared Prompt Prefill --------------------- @@ -102,9 +117,9 @@ configured capacity. The experimental path intentionally does not implement paged attention or change the default generation semantics. It currently requires one padded prompt width for -all rows, a model with cache-class support, greedy decoding, and one sample per -prompt. Shared prompt prefill is rejected until the scheduling semantics are -validated on real workloads. Models that explicitly declare no cache-class +all rows, a model with cache-class support, and one sample per prompt. Shared +prompt prefill is rejected until the scheduling semantics are validated on real +workloads. Models that explicitly declare no cache-class support are rejected; models with unknown support should be validated against the default ``generate()`` path before use. ``align_decode_fronts=False`` is the default equal-width padded-prompt baseline: diff --git a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py index 054ab4c0d4f4..b2301d2e2252 100644 --- a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py +++ b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py @@ -119,8 +119,6 @@ def test_continuous_generation_rejects_unsupported_inputs(): rollout.generate(empty_request, SamplingConfig(max_new_tokens=2, continuous_batch_size=1)) with pytest.raises(ValueError, match="positive"): rollout.generate(request, SamplingConfig(max_new_tokens=2, continuous_batch_size=0)) - with pytest.raises(ValueError, match="greedy"): - rollout.generate(request, SamplingConfig(max_new_tokens=2, temperature=0.5, continuous_batch_size=1)) @pytest.mark.parametrize( @@ -857,6 +855,10 @@ def forward(self, input_ids, attention_mask, past_key_values=None, use_cache=Tru assert rollout.get_last_continuous_stats()["trim_count"] > 0 +def _argmax(logits): + return logits.argmax(dim=-1, keepdim=True) + + def test_continuous_generation_applies_repetition_penalty(): request = RolloutRequest(torch.tensor([[0]]), torch.ones((1, 1), dtype=torch.long)) responses = {0: [torch.tensor([[0]])]} @@ -870,6 +872,7 @@ def test_continuous_generation_applies_repetition_penalty(): {0: request}, responses, module, + _argmax, ) assert next_tokens.tolist() == [[1]] @@ -886,11 +889,158 @@ def test_continuous_generation_treats_none_repetition_penalty_as_one(): {0: request}, responses, module, + _argmax, ) assert next_tokens.tolist() == [[0]] +def test_continuous_sampling_applies_repetition_penalty_before_warpers(): + request = RolloutRequest(torch.tensor([[0]]), torch.ones((1, 1), dtype=torch.long)) + responses = {0: [torch.tensor([[0]])]} + module = SimpleNamespace(generation_config=SimpleNamespace(repetition_penalty=1.5)) + select = HybridEngineRollout._token_selector(SamplingConfig(max_new_tokens=1, temperature=1.0, top_k=1)) + + # generate() penalizes first: token 0 drops from 6 to 4, so top-k 1 keeps only token 1. Warping first would + # keep only token 0. + next_tokens = HybridEngineRollout._continuous_next_tokens( + torch.tensor([[6.0, 5.0]]), + (0, ), + {0: request}, + responses, + module, + select, + ) + + assert next_tokens.tolist() == [[1]] + + +def test_continuous_generation_applies_repetition_penalty_in_float32(): + request = RolloutRequest(torch.tensor([[0]]), torch.ones((1, 1), dtype=torch.long)) + responses = {0: [torch.tensor([[0]])]} + module = SimpleNamespace(generation_config=SimpleNamespace(repetition_penalty=1.5)) + logits = torch.tensor([[6.03125, 4.03125]], dtype=torch.bfloat16) + + # generate() penalizes in float32: token 0 drops to 4.0208, below token 1. In bf16 it would round up to 4.03125, + # tying with token 1, and argmax would keep token 0. + next_tokens = HybridEngineRollout._continuous_next_tokens( + logits, + (0, ), + {0: request}, + responses, + module, + _argmax, + ) + + assert next_tokens.tolist() == [[1]] + assert logits.tolist() == [[6.03125, 4.03125]] + + +def test_continuous_prefill_applies_repetition_penalty(): + + class Model(torch.nn.Module): + _supports_cache_class = True + config = PretrainedConfig(num_hidden_layers=1, num_attention_heads=1, hidden_size=1, head_dim=1) + generation_config = SimpleNamespace(repetition_penalty=1.5) + + def forward(self, input_ids, **kwargs): + # Token 0 is in the prompt and wins before the penalty; token 1 is not in the prompt. + logits = torch.tensor([6.0, 5.0]).expand(input_ids.shape[0], 1, 2) + return SimpleNamespace(logits=logits) + + rollout = HybridEngineRollout(SimpleNamespace(module=Model()), + SimpleNamespace(pad_token_id=0, eos_token_id=-1), + cfg=HybridEngineRolloutConfig()) + prompt_ids = torch.tensor([[0, 0]]) + + tokens, _ = rollout._continuous_prefill_cache(rollout.engine.module, lambda *args, **kwargs: None, prompt_ids, + torch.ones_like(prompt_ids), torch.float32, torch.device("cpu"), + SamplingConfig(max_new_tokens=1, temperature=0)) + + assert tokens.tolist() == [[1]] + + +def _reference_probs(logits, temperature, top_k, top_p): + """The distribution ``SamplingConfig`` describes, derived from ``logits`` independently of the rollout.""" + scores = logits / temperature + if top_k > 0: + kth_score = scores.topk(top_k).values[-1] + scores = scores.masked_fill(scores < kth_score, float("-inf")) + probs = scores.softmax(dim=-1) + if top_p < 1.0: + sorted_probs, order = probs.sort(descending=True) + # A token is kept while the more likely tokens hold less than top_p of the mass. + keep_sorted = (sorted_probs.cumsum(dim=-1) - sorted_probs) < top_p + keep = torch.zeros_like(keep_sorted).scatter(0, order, keep_sorted) + probs = torch.where(keep, probs, torch.zeros_like(probs)) + probs = probs / probs.sum() + return probs + + +@pytest.mark.parametrize("temperature, top_k, top_p", [(1.0, -1, 1.0), (0.5, -1, 1.0), (1.0, 3, 1.0), (1.0, -1, 0.7), + (0.7, 4, 0.9)]) +def test_token_selector_samples_the_configured_distribution(temperature, top_k, top_p): + logits = torch.tensor([2.0, 1.5, 1.0, 0.5, 0.0, -0.5, -1.0, -2.0]) + expected = _reference_probs(logits, temperature, top_k, top_p) + select = HybridEngineRollout._token_selector( + SamplingConfig(max_new_tokens=1, temperature=temperature, top_k=top_k, top_p=top_p)) + draws = 20000 + + torch.manual_seed(0) + tokens = select(logits.expand(draws, -1)).squeeze(1) + + observed = torch.bincount(tokens, minlength=logits.numel()).float() / draws + assert (observed[expected == 0] == 0).all(), "sampled a token outside the top-k / top-p support" + tolerance = 4 * (expected * (1 - expected) / draws).sqrt() + 1e-6 + assert ((observed - expected).abs() <= tolerance).all(), f"observed {observed}, expected {expected}" + + +def test_token_selector_is_argmax_without_temperature(): + logits = torch.tensor([[0.1, 3.0, 2.0], [5.0, -1.0, 4.9]]) + select = HybridEngineRollout._token_selector(SamplingConfig(max_new_tokens=1, temperature=0)) + + assert select(logits).tolist() == [[1], [0]] + + +def test_continuous_generation_samples_when_temperature_is_set(): + + class TiedLogitsModel(torch.nn.Module): + """Tokens 7 and 8 share the top logit at every position, so greedy decoding always picks 7.""" + _supports_cache_class = True + + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.zeros(1)) + self.config = PretrainedConfig( + max_position_embeddings=32, + num_hidden_layers=1, + num_attention_heads=1, + num_key_value_heads=1, + hidden_size=1, + head_dim=1, + ) + + def forward(self, input_ids, attention_mask, past_key_values=None, use_cache=True, **kwargs): + states = input_ids[:, None, :, None].to(dtype=torch.float32) + past_key_values.update(states, states, layer_idx=0, cache_kwargs=kwargs) + logits = torch.zeros((input_ids.shape[0], input_ids.shape[1], 16)) + logits[..., 7] = 5.0 + logits[..., 8] = 5.0 + return SimpleNamespace(logits=logits, past_key_values=past_key_values) + + rollout = HybridEngineRollout(SimpleNamespace(module=TiedLogitsModel()), + SimpleNamespace(pad_token_id=0, eos_token_id=2)) + request = RolloutRequest(torch.tensor([[1, 2, 3]] * 8), torch.ones((8, 3), dtype=torch.long)) + sampling = SamplingConfig(max_new_tokens=4, temperature=1.0, top_k=2, continuous_batch_size=2) + + torch.manual_seed(0) + output = rollout.generate(request, sampling) + + generated = output.input_ids[:, 3:] + # Top-k 2 keeps only tokens 7 and 8, each with probability 1/2. + assert set(generated.flatten().tolist()) == {7, 8} + + @patch("deepspeed.runtime.rollout.hybrid_engine_rollout.time.perf_counter") @patch("deepspeed.runtime.rollout.hybrid_engine_rollout.get_accelerator") def test_generate_records_profile_when_enabled(mock_get_accelerator, mock_perf_counter): @@ -1184,9 +1334,10 @@ def test_sync_weights_is_noop(): # -- generate dispatches correctly ------------------------------------- +@pytest.mark.parametrize("temperature", [0, 0.7]) @patch("deepspeed.runtime.rollout.hybrid_engine_rollout.time.perf_counter") @patch("deepspeed.runtime.rollout.hybrid_engine_rollout.get_accelerator") -def test_generate_calls_graph_capture_when_enabled(mock_get_accelerator, mock_perf_counter): +def test_generate_calls_graph_capture_when_enabled(mock_get_accelerator, mock_perf_counter, temperature): mock_get_accelerator.return_value.is_graph_capture_supported.return_value = True engine = _make_engine() tok = _make_tokenizer() @@ -1199,13 +1350,15 @@ def test_generate_calls_graph_capture_when_enabled(mock_get_accelerator, mock_pe req.prompt_ids = torch.tensor([[1, 2]]) req.prompt_attention_mask = torch.ones(1, 2, dtype=torch.long) sampling = MagicMock() - sampling.temperature = 0 + sampling.temperature = temperature sampling.n_samples_per_prompt = 1 sampling.max_new_tokens = 3 sampling.continuous_batch_size = None rollout.generate(req, sampling) rollout._generate_graph.assert_called_once() + # Sampling must not fall back to Hugging Face generate(). + engine.module.generate.assert_not_called() profile = rollout.get_last_profile() assert profile["prefill_forward_ms"] is None assert profile["decode_forward_ms"] is None diff --git a/tests/unit/v1/test_hybrid_engine_rollout_v1.py b/tests/unit/v1/test_hybrid_engine_rollout_v1.py index 5d8fa7e63246..d62aadc37ce9 100644 --- a/tests/unit/v1/test_hybrid_engine_rollout_v1.py +++ b/tests/unit/v1/test_hybrid_engine_rollout_v1.py @@ -292,3 +292,120 @@ def counted_create_graph(): accelerator.create_graph = original_create_graph assert capture_count[0] == 1 + + +def _tiny_llama(device): + from transformers import LlamaConfig, LlamaForCausalLM + + torch.manual_seed(0) + config = LlamaConfig(vocab_size=64, + hidden_size=64, + intermediate_size=128, + num_hidden_layers=2, + num_attention_heads=4, + num_key_value_heads=2, + max_position_embeddings=128) + model = LlamaForCausalLM(config) + # A random initialization gives almost uniform next-token distributions, under which a wrong temperature or + # cutoff rarely changes the drawn token. Scaling the output head makes them peaked. + with torch.no_grad(): + model.lm_head.weight.mul_(30) + return model.to(device).eval() + + +def _rollout(model, use_graph_capture): + # eos -1 never matches, so every row generates the full length. + tokenizer = SimpleNamespace(pad_token_id=0, eos_token_id=-1) + return HybridEngineRollout(SimpleNamespace(module=model), + tokenizer, + cfg=HybridEngineRolloutConfig(use_graph_capture=use_graph_capture)) + + +def _random_request(batch_size, prompt_len, device): + generator = torch.Generator().manual_seed(1) + prompt_ids = torch.randint(1, 64, (batch_size, prompt_len), generator=generator) + return RolloutRequest(prompt_ids.to(device), torch.ones_like(prompt_ids).to(device)) + + +@pytest.mark.parametrize("use_graph_capture, continuous_batch_size", [(True, None), (True, 8), (False, 8)]) +@pytest.mark.parametrize("temperature, top_k, top_p", [(1.0, 0, 1.0), (0.7, 5, 1.0), (1.0, 0, 0.8)]) +def test_decode_sampling_matches_hf_generate(temperature, top_k, top_p, use_graph_capture, continuous_batch_size): + accelerator = get_accelerator() + if not accelerator.is_available() or accelerator.device_name() != "cuda": + pytest.skip("CUDA is required for CUDA graph decode coverage") + + device = torch.device(accelerator.device_name()) + model = _tiny_llama(device) + new_tokens = 32 + # Every prompt gets its own continuous batching slot, so each step draws the tokens of all rows in one call, as + # generate() does, and the same seed gives both the same random numbers. + request = _random_request(batch_size=8, prompt_len=8, device=device) + sampling = SamplingConfig(max_new_tokens=new_tokens, + temperature=temperature, + top_k=top_k, + top_p=top_p, + continuous_batch_size=continuous_batch_size) + + torch.manual_seed(2) + output = _rollout(model, use_graph_capture).generate(request, sampling) + + torch.manual_seed(2) + with torch.no_grad(): + expected = model.generate(request.prompt_ids, + attention_mask=request.prompt_attention_mask, + max_new_tokens=new_tokens, + do_sample=True, + temperature=temperature, + top_k=top_k, + top_p=top_p, + eos_token_id=None, + pad_token_id=0) + + assert output.input_ids.tolist() == expected.tolist() + + +@pytest.mark.parametrize("use_graph_capture, continuous_batch_size", [(True, None), (True, 8), (False, 8)]) +@pytest.mark.parametrize("temperature", [0.0, 0.7]) +def test_decode_repetition_penalty_matches_hf_generate(temperature, use_graph_capture, continuous_batch_size): + accelerator = get_accelerator() + if not accelerator.is_available() or accelerator.device_name() != "cuda": + pytest.skip("CUDA is required for CUDA graph decode coverage") + + device = torch.device(accelerator.device_name()) + model = _tiny_llama(device) + new_tokens = 32 + request = _random_request(batch_size=8, prompt_len=8, device=device) + sampling = SamplingConfig(max_new_tokens=new_tokens, + temperature=temperature, + top_k=0, + top_p=1.0, + continuous_batch_size=continuous_batch_size) + hf_sampling = { + "do_sample": True, + "temperature": temperature, + "top_k": 0, + "top_p": 1.0 + } if temperature > 0 else { + "do_sample": False + } + + def hf_generate(): + torch.manual_seed(2) + with torch.no_grad(): + return model.generate(request.prompt_ids, + attention_mask=request.prompt_attention_mask, + max_new_tokens=new_tokens, + eos_token_id=None, + pad_token_id=0, + **hf_sampling).tolist() + + model.generation_config.repetition_penalty = 1.0 + unpenalized = hf_generate() + model.generation_config.repetition_penalty = 1.3 + expected = hf_generate() + assert expected != unpenalized + + torch.manual_seed(2) + output = _rollout(model, use_graph_capture).generate(request, sampling) + + assert output.input_ids.tolist() == expected