From be21c01319d8aeaaa3d29f695a6b0eb292644c23 Mon Sep 17 00:00:00 2001 From: Puyuan Yao Date: Wed, 28 Oct 2026 01:25:15 -0500 Subject: [PATCH 1/4] feat(rollout): sample on the CUDA graph and continuous batching decode paths Graph capture applied only to greedy decoding, and continuous batching rejected temperature > 0. Only the decode forward is captured, so tokens can be picked from its output logits after each replay. - One token selector picks the first and every decoded token on graph decode and on continuous batching with and without graphs: argmax at temperature <= 0, otherwise Hugging Face's temperature, top-k and top-p warpers in generate()'s order, then multinomial sampling. - generate() routes sampled requests to the graph path. - Continuous batching accepts temperature > 0 and applies the model's repetition penalty before the warpers. - One helper builds the generate() sampling arguments for the main path and for continuous batching's legacy prefill. Signed-off-by: Puyuan Yao --- .../runtime/rollout/hybrid_engine_rollout.py | 136 ++++++++++++------ docs/code-docs/source/inference-engine.rst | 21 ++- .../rollout/test_hybrid_engine_rollout.py | 116 ++++++++++++++- .../unit/v1/test_hybrid_engine_rollout_v1.py | 93 ++++++++++++ 4 files changed, 313 insertions(+), 53 deletions(-) diff --git a/deepspeed/runtime/rollout/hybrid_engine_rollout.py b/deepspeed/runtime/rollout/hybrid_engine_rollout.py index 725ffbef0c5d..8db36f30c8e1 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 @@ -169,11 +170,9 @@ def generate(self, request: RolloutRequest, sampling: SamplingConfig) -> Rollout accelerator.synchronize() expansion_end = time.perf_counter() - is_greedy = sampling.temperature <= 0.0 - forward_profiler = None forward_profile_handles = [] - if self.enable_profiling and not (self.use_graph_capture and is_greedy): + if self.enable_profiling and not self.use_graph_capture: forward_profiler = _ForwardProfiler(accelerator) forward_profile_handles = forward_profiler.register(module) @@ -184,25 +183,19 @@ def generate(self, request: RolloutRequest, sampling: SamplingConfig) -> Rollout raise RuntimeError("Shared prefill does not support graph capture") self.engine.prepare_shared_prefill(B, n, prompt_len) shared_prefill_handles = self._register_shared_prefill_hooks(module, B, n) - if self.use_graph_capture and is_greedy: + if self.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: @@ -282,11 +275,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( @@ -297,6 +290,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 @@ -463,6 +457,7 @@ def _generate_continuous(self, request, sampling, max_batch_size): prompt_lengths, model_dtype, device, + sampling, self.align_decode_fronts, profile, ) @@ -501,6 +496,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))) @@ -545,7 +541,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 @@ -553,6 +549,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: @@ -659,6 +656,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), ) @@ -694,6 +692,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 @@ -901,8 +900,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: @@ -936,6 +933,7 @@ def _continuous_prefill(self, prompt_lengths, model_dtype, device, + sampling, align_decode_fronts=False, profile=None, target_slots=None): @@ -960,6 +958,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) @@ -994,6 +993,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) @@ -1075,7 +1075,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 @@ -1086,10 +1087,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 @@ -1106,25 +1107,67 @@ 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 + return self._token_selector(sampling)(prefill_output.logits[:, -1, :]), prefill_cache @staticmethod - def _continuous_next_tokens(logits, request_ids, request_by_id, responses, module): + def _continuous_next_tokens(logits, request_ids, request_by_id, responses, module, select_next_tokens): repetition_penalty = getattr(getattr(module, "generation_config", None), "repetition_penalty", 1.0) if repetition_penalty is None: repetition_penalty = 1.0 - 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) + if repetition_penalty != 1.0: + # generate() applies the penalty before the sampling warpers, so it shapes the sampled distribution. + logits = logits.clone() + for row, request_id in enumerate(request_ids): + input_ids = torch.cat((request_by_id[request_id].prompt_ids, *responses[request_id]), dim=1) + scores = logits[row:row + 1].gather(1, input_ids) + scores = torch.where(scores < 0, scores * repetition_penalty, scores / repetition_penalty) + logits[row:row + 1].scatter_(1, input_ids, scores) + 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): @@ -1300,11 +1343,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 @@ -1313,6 +1356,7 @@ 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) # --- Prefill with HF StaticCache (correct attention semantics) --- prefill_cache = self._create_static_cache(StaticCache, module.config, batch_size, max_len, device, model_dtype) @@ -1326,7 +1370,7 @@ 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 = select_next_tokens(prefill_out.logits[:, -1, :]) # --- Copy prefill KV into DeepSpeedStaticCache --- write_pos = torch.tensor(prompt_len - 1, dtype=torch.long, device=device) @@ -1416,7 +1460,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 = select_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 0846596680d7..a100f5bec359 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. +Other settings from the model's ``generation_config``, such as a repetition +penalty, are not applied on the graph path. Continuous batching, with or +without graph capture, picks tokens the same way and also applies the model's +repetition penalty before the warpers, as ``generate()`` does. + 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 4bde88b77097..14e4be549bf8 100644 --- a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py +++ b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py @@ -110,8 +110,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( @@ -806,6 +804,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]])]} @@ -819,6 +821,7 @@ def test_continuous_generation_applies_repetition_penalty(): {0: request}, responses, module, + _argmax, ) assert next_tokens.tolist() == [[1]] @@ -835,11 +838,113 @@ 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 _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): @@ -1133,9 +1238,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): engine = _make_engine() tok = _make_tokenizer() cfg = HybridEngineRolloutConfig(use_graph_capture=True, enable_profiling=True) @@ -1147,13 +1253,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 c4af5a8a6c95..dad2341a8a92 100644 --- a/tests/unit/v1/test_hybrid_engine_rollout_v1.py +++ b/tests/unit/v1/test_hybrid_engine_rollout_v1.py @@ -188,3 +188,96 @@ 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 sampling from the + # wrong distribution is hard to detect. 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)) + + +def _reference_log_probs(logits, temperature, top_k, top_p): + """Log-probs of the distribution ``SamplingConfig`` describes, derived from the raw logits.""" + scores = logits.float() / temperature + if top_k > 0: + kth_score = scores.topk(top_k, dim=-1).values[..., -1:] + scores = scores.masked_fill(scores < kth_score, float("-inf")) + if top_p < 1.0: + sorted_probs, order = scores.softmax(dim=-1).sort(dim=-1, descending=True) + mass_before = sorted_probs.cumsum(dim=-1) - sorted_probs + # A token is kept while the more likely tokens hold less than top_p of the mass. The small margin keeps + # tokens on the boundary, where the graph's incremental decode and this full forward can round apart. + drop_sorted = mass_before >= top_p + 1e-4 + drop = drop_sorted.scatter(-1, order, drop_sorted) + scores = scores.masked_fill(drop, float("-inf")) + return scores.log_softmax(dim=-1) + + +# Plain graph decode, continuous batching with graph capture, and continuous batching without it. +@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, -1, 1.0), (0.7, 5, 1.0), (1.0, -1, 0.8)]) +def test_decode_samples_from_the_configured_distribution(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) + rollout = _rollout(model, use_graph_capture) + prompt_len, new_tokens = 8, 32 + request = _random_request(batch_size=32, prompt_len=prompt_len, 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.generate(request, sampling) + + with torch.no_grad(): + logits = model(output.input_ids).logits + # Positions prompt_len - 1 .. end - 2 predict the generated tokens. + log_probs = _reference_log_probs(logits[:, prompt_len - 1:-1], temperature, top_k, top_p) + tokens = output.input_ids[:, prompt_len:] + token_log_probs = log_probs.gather(-1, tokens.unsqueeze(-1)).squeeze(-1) + assert torch.isfinite(token_log_probs).all(), "sampled a token outside the top-k / top-p support" + + # Tokens drawn from q satisfy E[log q(x)] = -H(q) and P[x = argmax q] = mean max q. + probs = log_probs.exp() + entropy = -(probs * log_probs.clamp(min=-1e30)).sum(dim=-1) + gap = (token_log_probs + entropy).flatten() + gap_z = gap.mean() / (gap.std() / gap.numel()**0.5) + max_probs, argmax = probs.max(dim=-1) + hits = (tokens == argmax).float() + hit_z = (hits.mean() - max_probs.mean()) / ((max_probs * (1 - max_probs)).sum().sqrt() / hits.numel()) + assert abs(gap_z.item()) < 4, f"log-prob gap z-score {gap_z.item():.2f}" + assert abs(hit_z.item()) < 4, f"argmax hit-rate z-score {hit_z.item():.2f}" From 0ed9232139f5014a7defbcf76d2fb5ddb6032f5c Mon Sep 17 00:00:00 2001 From: Puyuan Yao Date: Wed, 28 Oct 2026 16:43:39 -0500 Subject: [PATCH 2/4] test(rollout): compare CUDA decode sampling with HF generate() Under the same seed, the graph decode and continuous batching paths must generate exactly the tokens Hugging Face generate() samples. Each prompt gets its own slot, so every path draws all rows in one call per step, as generate() does. This replaces the log-prob and argmax z-score checks. Signed-off-by: Puyuan Yao --- .../unit/v1/test_hybrid_engine_rollout_v1.py | 65 ++++++------------- 1 file changed, 21 insertions(+), 44 deletions(-) diff --git a/tests/unit/v1/test_hybrid_engine_rollout_v1.py b/tests/unit/v1/test_hybrid_engine_rollout_v1.py index dad2341a8a92..d09db2d3cc8c 100644 --- a/tests/unit/v1/test_hybrid_engine_rollout_v1.py +++ b/tests/unit/v1/test_hybrid_engine_rollout_v1.py @@ -202,8 +202,8 @@ def _tiny_llama(device): num_key_value_heads=2, max_position_embeddings=128) model = LlamaForCausalLM(config) - # A random initialization gives almost uniform next-token distributions, under which sampling from the - # wrong distribution is hard to detect. Scaling the output head makes them peaked. + # 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() @@ -223,37 +223,19 @@ def _random_request(batch_size, prompt_len, device): return RolloutRequest(prompt_ids.to(device), torch.ones_like(prompt_ids).to(device)) -def _reference_log_probs(logits, temperature, top_k, top_p): - """Log-probs of the distribution ``SamplingConfig`` describes, derived from the raw logits.""" - scores = logits.float() / temperature - if top_k > 0: - kth_score = scores.topk(top_k, dim=-1).values[..., -1:] - scores = scores.masked_fill(scores < kth_score, float("-inf")) - if top_p < 1.0: - sorted_probs, order = scores.softmax(dim=-1).sort(dim=-1, descending=True) - mass_before = sorted_probs.cumsum(dim=-1) - sorted_probs - # A token is kept while the more likely tokens hold less than top_p of the mass. The small margin keeps - # tokens on the boundary, where the graph's incremental decode and this full forward can round apart. - drop_sorted = mass_before >= top_p + 1e-4 - drop = drop_sorted.scatter(-1, order, drop_sorted) - scores = scores.masked_fill(drop, float("-inf")) - return scores.log_softmax(dim=-1) - - -# Plain graph decode, continuous batching with graph capture, and continuous batching without it. @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, -1, 1.0), (0.7, 5, 1.0), (1.0, -1, 0.8)]) -def test_decode_samples_from_the_configured_distribution(temperature, top_k, top_p, use_graph_capture, - continuous_batch_size): +@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) - rollout = _rollout(model, use_graph_capture) - prompt_len, new_tokens = 8, 32 - request = _random_request(batch_size=32, prompt_len=prompt_len, device=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, @@ -261,23 +243,18 @@ def test_decode_samples_from_the_configured_distribution(temperature, top_k, top continuous_batch_size=continuous_batch_size) torch.manual_seed(2) - output = rollout.generate(request, sampling) + output = _rollout(model, use_graph_capture).generate(request, sampling) + torch.manual_seed(2) with torch.no_grad(): - logits = model(output.input_ids).logits - # Positions prompt_len - 1 .. end - 2 predict the generated tokens. - log_probs = _reference_log_probs(logits[:, prompt_len - 1:-1], temperature, top_k, top_p) - tokens = output.input_ids[:, prompt_len:] - token_log_probs = log_probs.gather(-1, tokens.unsqueeze(-1)).squeeze(-1) - assert torch.isfinite(token_log_probs).all(), "sampled a token outside the top-k / top-p support" - - # Tokens drawn from q satisfy E[log q(x)] = -H(q) and P[x = argmax q] = mean max q. - probs = log_probs.exp() - entropy = -(probs * log_probs.clamp(min=-1e30)).sum(dim=-1) - gap = (token_log_probs + entropy).flatten() - gap_z = gap.mean() / (gap.std() / gap.numel()**0.5) - max_probs, argmax = probs.max(dim=-1) - hits = (tokens == argmax).float() - hit_z = (hits.mean() - max_probs.mean()) / ((max_probs * (1 - max_probs)).sum().sqrt() / hits.numel()) - assert abs(gap_z.item()) < 4, f"log-prob gap z-score {gap_z.item():.2f}" - assert abs(hit_z.item()) < 4, f"argmax hit-rate z-score {hit_z.item():.2f}" + 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() From 2a5a4f12adb9e8244988662f612aa752fefa3b2f Mon Sep 17 00:00:00 2001 From: Puyuan Yao Date: Sun, 1 Nov 2026 22:38:19 -0600 Subject: [PATCH 3/4] fix(rollout): apply repetition penalty on all decode paths Signed-off-by: Puyuan Yao --- .../runtime/rollout/hybrid_engine_rollout.py | 55 ++++++++++++++----- docs/code-docs/source/inference-engine.rst | 8 +-- .../rollout/test_hybrid_engine_rollout.py | 48 ++++++++++++++++ .../unit/v1/test_hybrid_engine_rollout_v1.py | 42 ++++++++++++++ 4 files changed, 134 insertions(+), 19 deletions(-) diff --git a/deepspeed/runtime/rollout/hybrid_engine_rollout.py b/deepspeed/runtime/rollout/hybrid_engine_rollout.py index 8db36f30c8e1..9e31b4c2798a 100644 --- a/deepspeed/runtime/rollout/hybrid_engine_rollout.py +++ b/deepspeed/runtime/rollout/hybrid_engine_rollout.py @@ -1107,21 +1107,40 @@ def _continuous_prefill_cache(self, module, static_cache_type, prompt_ids, promp position_ids=position_ids, **self._last_logits_kwargs(module), ) - return self._token_selector(sampling)(prefill_output.logits[:, -1, :]), 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, select_next_tokens): + 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 + 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: - # generate() applies the penalty before the sampling warpers, so it shapes the sampled distribution. - logits = logits.clone() - for row, request_id in enumerate(request_ids): - input_ids = torch.cat((request_by_id[request_id].prompt_ids, *responses[request_id]), dim=1) - scores = logits[row:row + 1].gather(1, input_ids) - scores = torch.where(scores < 0, scores * repetition_penalty, scores / repetition_penalty) - logits[row:row + 1].scatter_(1, input_ids, scores) + 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 @@ -1357,6 +1376,13 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, 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) @@ -1370,7 +1396,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 = select_next_tokens(prefill_out.logits[:, -1, :]) + 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) @@ -1391,8 +1418,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) @@ -1460,7 +1485,7 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, # Replay get_accelerator().replay_graph(graph) - next_token = select_next_tokens(static_logits[:, -1, :]) + 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 a100f5bec359..53e2d10f5f41 100644 --- a/docs/code-docs/source/inference-engine.rst +++ b/docs/code-docs/source/inference-engine.rst @@ -70,10 +70,10 @@ 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. -Other settings from the model's ``generation_config``, such as a repetition -penalty, are not applied on the graph path. Continuous batching, with or -without graph capture, picks tokens the same way and also applies the model's -repetition penalty before the warpers, as ``generate()`` does. +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 --------------------- diff --git a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py index 14e4be549bf8..ede7cea5178d 100644 --- a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py +++ b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py @@ -864,6 +864,54 @@ def test_continuous_sampling_applies_repetition_penalty_before_warpers(): 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 diff --git a/tests/unit/v1/test_hybrid_engine_rollout_v1.py b/tests/unit/v1/test_hybrid_engine_rollout_v1.py index d09db2d3cc8c..ae5bbbca858a 100644 --- a/tests/unit/v1/test_hybrid_engine_rollout_v1.py +++ b/tests/unit/v1/test_hybrid_engine_rollout_v1.py @@ -258,3 +258,45 @@ def test_decode_sampling_matches_hf_generate(temperature, top_k, top_p, use_grap 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 From b1adfce43e2a03a99af1cd11952ce66e62271a13 Mon Sep 17 00:00:00 2001 From: Puyuan Yao Date: Sat, 7 Nov 2026 13:57:44 -0600 Subject: [PATCH 4/4] style: apply yapf formatting Signed-off-by: Puyuan Yao --- tests/unit/runtime/rollout/test_hybrid_engine_rollout.py | 9 +++------ tests/unit/v1/test_hybrid_engine_rollout_v1.py | 7 ++++++- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py index aa75595f22bf..b2301d2e2252 100644 --- a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py +++ b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py @@ -937,6 +937,7 @@ def test_continuous_generation_applies_repetition_penalty_in_float32(): 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) @@ -952,12 +953,8 @@ def forward(self, input_ids, **kwargs): 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"), + 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]] diff --git a/tests/unit/v1/test_hybrid_engine_rollout_v1.py b/tests/unit/v1/test_hybrid_engine_rollout_v1.py index 776a0943ef30..d62aadc37ce9 100644 --- a/tests/unit/v1/test_hybrid_engine_rollout_v1.py +++ b/tests/unit/v1/test_hybrid_engine_rollout_v1.py @@ -380,7 +380,12 @@ def test_decode_repetition_penalty_matches_hf_generate(temperature, use_graph_ca 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 { + hf_sampling = { + "do_sample": True, + "temperature": temperature, + "top_k": 0, + "top_p": 1.0 + } if temperature > 0 else { "do_sample": False }