Skip to content

Commit 526141c

Browse files
authored
[Performance]Reduce sampling (vllm-project#8308)
What this PR does / why we need it? This PR introduces a significant optimization to the sampling process in a distributed (Tensor Parallel) environment, named "reduce sampling". The core goal is to minimize communication overhead during token selection, thereby improving the performance of vLLM Ascend in distributed deployment scenarios. In traditional distributed sampling, full vocabulary gathering across tensor parallel ranks leads to high communication costs, especially in large-scale parallel settings. This optimization addresses the issue by designing specialized sampling logic that intelligently aggregates and processes vocabulary information, reducing unnecessary data transmission while ensuring sampling accuracy. Does this PR introduce any user-facing change? No breaking user-facing changes. A new configuration option enable_reduce_sample is added to AscendConfig, which users can optionally enable to activate the optimized distributed sampling scheme. Existing sampling behaviors remain unchanged by default. How was this patch tested? Tested with vLLM version based on v0.20.1. - Validation of distributed greedy sampling logic, ensuring correct global argmax selection across tensor parallel ranks. - Verification of distributed top-k/top-p sampling, confirming accurate candidate aggregation and filtering. - Functional testing of speculative decoding rejection sampling with the new compressed vocabulary mode. - End-to-end testing of the integrated sampling pipeline in ModelRunnerV1, covering both regular and speculative decoding workflows. Summary of Changes - Optimized Distributed Sampling Scheme: Added enable_reduce_sample in AscendConfig to toggle the optimized sampling mode for Tensor Parallelism, reducing communication overhead. - Distributed Greedy Sampling: Implemented a new greedy_sample function that gathers local maximum logits and their global indices across ranks to determine the global argmax, avoiding full vocabulary gathering. - Distributed Top-K/Top-P Sampling: Enhanced top-k/top-p logic to perform local top-k selection first, then gather candidates across ranks and apply top-p filtering on the combined global candidates. - Updated Rejection Sampling: Modified core rejection sampling functions (rejection_sample, rejection_random_sample_kernel, etc.) to support compressed vocabulary mode, working with reduced candidate tokens and global indices for efficiency. - Model-Specific Logits Handling: Patched Eagle3LlamaForCausalLM.compute_logits to return only selected draft token IDs (and bias) when reduce sampling is enabled, optimizing draft generation. - Pipeline Integration: IntegratedAscendRejectionSampler and AscendTopKTopPSampler into ModelRunnerV1’s sampling pipeline, adding prepare_sampling calls to pass max_topk dynamically. - vLLM version: v0.20.1 --------- Signed-off-by: hzx55906 <513464215@qq.com>
1 parent f11845b commit 526141c

14 files changed

Lines changed: 1461 additions & 447 deletions

File tree

‎tests/ut/sample/test_rejection_sampler.py‎

Lines changed: 260 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,3 @@
1-
#
2-
# Licensed under the Apache License, Version 2.0 (the "License");
3-
# you may not use this file except in compliance with the License.
4-
# You may obtain a copy of the License at
5-
#
6-
# http://www.apache.org/licenses/LICENSE-2.0
7-
#
8-
# Unless required by applicable law or agreed to in writing, software
9-
# distributed under the License is distributed on an "AS IS" BASIS,
10-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11-
# See the License for the specific language governing permissions and
12-
# limitations under the License.
13-
# This file is a part of the vllm-ascend project.
14-
#
151
from unittest.mock import patch
162

173
import torch
@@ -225,6 +211,208 @@ def test_sample_recovered_tokens_pytorch_ngram(self):
225211
assert output_token_ids[0].item() == 0
226212
assert output_token_ids[1].item() == 1
227213

214+
@patch("torch.arange", new=mock_pin_memory(torch.arange))
215+
@patch("torch.ones", new=mock_pin_memory(torch.ones))
216+
@patch("torch.full", new=mock_pin_memory(torch.full))
217+
@patch("torch.tensor", new=mock_pin_memory(torch.tensor))
218+
def test_reduce_sample_recovered_tokens_pytorch_ngram(self):
219+
"""Test recovered token sampling under n-gram mode"""
220+
output_token_ids = torch.empty(2, dtype=torch.int32)
221+
cu_num_draft_tokens = torch.tensor([1, 2])
222+
draft_token_ids = torch.tensor([1, 2])
223+
draft_probs = None
224+
target_probs = torch.tensor(
225+
[
226+
[0.1, 0.2, 0.7],
227+
[0.3, 0.3, 0.4],
228+
]
229+
)
230+
q = torch.tensor(
231+
[
232+
[0.1, 0.2, 0.7],
233+
[0.5, 0.4, 0.1],
234+
]
235+
)
236+
vocab_size = 3
237+
target_indices = torch.tensor(
238+
[
239+
[0, 1, 2],
240+
[0, 1, 2],
241+
]
242+
)
243+
enable_reduce_sampling = True
244+
sample_recovered_tokens_pytorch(
245+
output_token_ids,
246+
cu_num_draft_tokens,
247+
draft_token_ids,
248+
draft_probs,
249+
target_probs,
250+
q,
251+
vocab_size,
252+
IS_NGRAM=True,
253+
target_indices=target_indices,
254+
enable_reduce_sampling=enable_reduce_sampling,
255+
)
256+
257+
assert output_token_ids[0].item() == 0
258+
assert output_token_ids[1].item() == 1
259+
260+
@patch("torch.arange", new=mock_pin_memory(torch.arange))
261+
@patch("torch.ones", new=mock_pin_memory(torch.ones))
262+
@patch("torch.full", new=mock_pin_memory(torch.full))
263+
@patch("torch.tensor", new=mock_pin_memory(torch.tensor))
264+
def test_rejection_random_reduce_sample_block_verify_pytorch(self):
265+
"""Test random rejection sampling for block verify: accept based on uniform probability"""
266+
batch_size = 2
267+
max_spec_len = 3
268+
output_token_ids = torch.full((batch_size, max_spec_len + 1), PLACEHOLDER_TOKEN_ID)
269+
270+
cu_num_draft_tokens = torch.tensor([2, 1])
271+
draft_token_ids = torch.tensor([1, 0, 2])
272+
draft_probs = torch.tensor(
273+
[
274+
[0.0, 0.6, 0.0, 0.4, 0.0],
275+
[0.1, 0.2, 0.3, 0.4, 0.0],
276+
[0.5, 0.5, 0.0, 0.0, 0.0],
277+
]
278+
)
279+
target_probs = torch.tensor(
280+
[
281+
[0.0, 0.8, 0.0, 0.2],
282+
[0.2, 0.1, 0.3, 0.4],
283+
[0.9, 0.1, 0.0, 0.0],
284+
]
285+
)
286+
bonus_token_ids = torch.tensor([[100], [200]])
287+
recovered_token_ids = torch.tensor([1, 2, 3])
288+
uniform_probs = torch.tensor([0.7, 0.6, 0.5])
289+
is_greedy = torch.tensor([False, False])
290+
vocab_size = 5
291+
target_indices = torch.tensor(
292+
[
293+
[0, 1, 2, 3],
294+
[0, 1, 2, 3],
295+
[0, 1, 2, 3],
296+
]
297+
)
298+
enable_reduce_sampling = True
299+
rejection_random_sample_block_verify_pytorch(
300+
output_token_ids,
301+
cu_num_draft_tokens,
302+
draft_token_ids,
303+
draft_probs,
304+
target_probs,
305+
bonus_token_ids,
306+
recovered_token_ids,
307+
uniform_probs,
308+
is_greedy,
309+
max_spec_len,
310+
vocab_size,
311+
IS_NGRAM=False,
312+
target_indices=target_indices,
313+
enable_reduce_sampling=enable_reduce_sampling,
314+
)
315+
316+
assert output_token_ids[0, 0].item() == 1
317+
assert output_token_ids[0, 1].item() == 0
318+
assert output_token_ids[0, 2].item() == 100
319+
320+
@patch("torch.arange", new=mock_pin_memory(torch.arange))
321+
@patch("torch.ones", new=mock_pin_memory(torch.ones))
322+
@patch("torch.full", new=mock_pin_memory(torch.full))
323+
@patch("torch.tensor", new=mock_pin_memory(torch.tensor))
324+
def test_reduce_sample_recovered_tokens_blockwise_pytorch_ngram(self):
325+
"""Test recovered token sampling for blockwise speculative decoding with n-gram."""
326+
output_token_ids = torch.empty(2, dtype=torch.int32)
327+
cu_num_draft_tokens = torch.tensor([1, 2])
328+
draft_token_ids = torch.tensor([1, 2])
329+
draft_probs = None
330+
target_probs = torch.tensor(
331+
[
332+
[0.1, 0.2, 0.7],
333+
[0.3, 0.3, 0.4],
334+
]
335+
)
336+
q = torch.tensor(
337+
[
338+
[0.1, 0.2, 0.7],
339+
[0.5, 0.4, 0.1],
340+
]
341+
)
342+
vocab_size = 3
343+
target_indices = torch.tensor(
344+
[
345+
[0, 1, 2],
346+
[0, 1, 2],
347+
]
348+
)
349+
enable_reduce_sampling = True
350+
sample_recovered_tokens_blockwise_pytorch(
351+
output_token_ids,
352+
cu_num_draft_tokens,
353+
draft_token_ids,
354+
draft_probs,
355+
target_probs,
356+
q,
357+
vocab_size,
358+
IS_NGRAM=True,
359+
target_indices=target_indices,
360+
enable_reduce_sampling=enable_reduce_sampling,
361+
)
362+
363+
assert output_token_ids[0].item() == 0
364+
assert output_token_ids[1].item() == 1
365+
366+
@patch("torch.arange", new=mock_pin_memory(torch.arange))
367+
@patch("torch.ones", new=mock_pin_memory(torch.ones))
368+
@patch("torch.full", new=mock_pin_memory(torch.full))
369+
@patch("torch.tensor", new=mock_pin_memory(torch.tensor))
370+
def test_reduce_sample_recovered_tokens_blockwise_pytorch(self):
371+
"""Test recovered token sampling for blockwise speculative decoding."""
372+
output_token_ids = torch.empty(2, dtype=torch.int32)
373+
cu_num_draft_tokens = torch.tensor([1, 2])
374+
draft_token_ids = torch.tensor([0, 1])
375+
draft_probs = torch.tensor(
376+
[
377+
[0.6, 0.1, 0.3],
378+
[0.2, 0.7, 0.1],
379+
]
380+
)
381+
target_probs = torch.tensor(
382+
[
383+
[0.8, 0.1, 0.1],
384+
[0.3, 0.6, 0.1],
385+
]
386+
)
387+
q = torch.tensor(
388+
[
389+
[0.5, 0.3, 0.2],
390+
[0.1, 0.8, 0.1],
391+
]
392+
)
393+
vocab_size = 3
394+
target_indices = torch.tensor(
395+
[
396+
[0, 1, 2],
397+
[0, 1, 2],
398+
]
399+
)
400+
enable_reduce_sampling = True
401+
sample_recovered_tokens_blockwise_pytorch(
402+
output_token_ids,
403+
cu_num_draft_tokens,
404+
draft_token_ids,
405+
draft_probs,
406+
target_probs,
407+
q,
408+
vocab_size,
409+
IS_NGRAM=False,
410+
target_indices=target_indices,
411+
enable_reduce_sampling=enable_reduce_sampling,
412+
)
413+
assert output_token_ids[0].item() == 0
414+
assert output_token_ids[1].item() == 0
415+
228416
@patch("torch.arange", new=mock_pin_memory(torch.arange))
229417
@patch("torch.ones", new=mock_pin_memory(torch.ones))
230418
@patch("torch.full", new=mock_pin_memory(torch.full))
@@ -276,6 +464,64 @@ def test_rejection_random_sample_block_verify_pytorch(self):
276464
assert output_token_ids[0, 1].item() == 0
277465
assert output_token_ids[0, 2].item() == 100
278466

467+
@patch("torch.arange", new=mock_pin_memory(torch.arange))
468+
@patch("torch.ones", new=mock_pin_memory(torch.ones))
469+
@patch("torch.full", new=mock_pin_memory(torch.full))
470+
@patch("torch.tensor", new=mock_pin_memory(torch.tensor))
471+
def test_rejection_random_reduce_sample_pytorch(self):
472+
"""Test random rejection sampling: accept based on uniform probability"""
473+
batch_size = 2
474+
max_spec_len = 3
475+
output_token_ids = torch.full((batch_size, max_spec_len + 1), PLACEHOLDER_TOKEN_ID)
476+
cu_num_draft_tokens = torch.tensor([2, 1])
477+
draft_token_ids = torch.tensor([1, 0, 2])
478+
draft_probs = torch.tensor(
479+
[
480+
[0.0, 0.6, 0.0, 0.4, 0.0], # vocab_size=5
481+
[0.1, 0.2, 0.3, 0.4, 0.0],
482+
[0.5, 0.5, 0.0, 0.0, 0.0],
483+
]
484+
)
485+
target_probs = torch.tensor(
486+
[
487+
[0.0, 0.8, 0.0, 0.2],
488+
[0.2, 0.1, 0.3, 0.4],
489+
[0.9, 0.1, 0.0, 0.0],
490+
]
491+
)
492+
bonus_token_ids = torch.tensor([[100], [200]])
493+
recovered_token_ids = torch.tensor([1, 2, 3])
494+
uniform_probs = torch.tensor([0.7, 0.6, 0.5])
495+
is_greedy = torch.tensor([False, False])
496+
vocab_size = 5
497+
target_indices = torch.tensor(
498+
[
499+
[0, 1, 2, 3],
500+
[0, 1, 2, 3],
501+
[0, 1, 2, 3],
502+
]
503+
)
504+
enable_reduce_sampling = True
505+
rejection_random_sample_pytorch(
506+
output_token_ids,
507+
cu_num_draft_tokens,
508+
draft_token_ids,
509+
draft_probs,
510+
target_probs,
511+
bonus_token_ids,
512+
recovered_token_ids,
513+
uniform_probs,
514+
is_greedy,
515+
max_spec_len,
516+
vocab_size,
517+
IS_NGRAM=False,
518+
target_indices=target_indices,
519+
enable_reduce_sampling=enable_reduce_sampling,
520+
)
521+
assert output_token_ids[0, 0].item() == 1
522+
assert output_token_ids[0, 1].item() == 0
523+
assert output_token_ids[0, 2].item() == 100
524+
279525
@patch("torch.arange", new=mock_pin_memory(torch.arange))
280526
@patch("torch.ones", new=mock_pin_memory(torch.ones))
281527
@patch("torch.full", new=mock_pin_memory(torch.full))

‎tests/ut/spec_decode/test_eagle_proposer.py‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2161,8 +2161,9 @@ def test_intermediate_variables_precision(self):
21612161
class MockDraftModel:
21622162
"""Draft model that records prepared forward inputs."""
21632163

2164-
def __init__(self, returns_tuple=True, vocab_size=200000):
2164+
def __init__(self, returns_tuple=True, enable_reduce_sample=False, vocab_size=200000):
21652165
self.returns_tuple = returns_tuple
2166+
self.enable_reduce_sample = enable_reduce_sample
21662167
self.vocab_size = vocab_size
21672168
self.calls = []
21682169
self.logit_inputs = []
@@ -2186,11 +2187,13 @@ def __call__(self, **kwargs):
21862187
return last_hidden_states, hidden_states
21872188
return last_hidden_states
21882189

2189-
def compute_logits(self, sample_hidden_states):
2190+
def compute_logits(self, sample_hidden_states, enable_reduce_sample=False):
21902191
self.logit_inputs.append(sample_hidden_states.clone())
21912192
token_ids = sample_hidden_states[:, 0].to(torch.long)
21922193
logits = torch.full((sample_hidden_states.shape[0], self.vocab_size), -1000.0)
21932194
logits[torch.arange(sample_hidden_states.shape[0]), token_ids] = 1000.0
2195+
if self.enable_reduce_sample:
2196+
logits = logits.argmax(dim=-1)
21942197
return logits
21952198

21962199
def embed_input_ids(self, input_ids):
@@ -2414,7 +2417,7 @@ def check_mock(self):
24142417
assert sig_name == ["self", "input_ids", "positions", "hidden_states", "inputs_embeds"]
24152418
sig = inspect.signature(RunnerCls.compute_logits)
24162419
sig_name = self.get_param_names(sig)
2417-
assert sig_name == ["self", "hidden_states"]
2420+
assert sig_name == ["self", "hidden_states", "enable_reduce_sample"]
24182421

24192422
import vllm_ascend.ascend_forward_context
24202423

@@ -2510,7 +2513,7 @@ def get_param_names(self, sig):
25102513
return [p.name for p in sig.parameters.values()]
25112514

25122515
def test_run_merged_draft_eagle3_decode_prepares_each_forward_input(self):
2513-
self.proposer.model = MockDraftModel(returns_tuple=True)
2516+
self.proposer.model = MockDraftModel(returns_tuple=True, enable_reduce_sample= True)
25142517
self.proposer.supports_mm_inputs = True
25152518
initial_input_ids = torch.tensor(
25162519
[279, 1196, 374, 8014, 151667, 198, 32313, 11, 151667, 198, 32313, 11],
@@ -2531,8 +2534,11 @@ def test_run_merged_draft_eagle3_decode_prepares_each_forward_input(self):
25312534
forward_context.attn_metadata = None
25322535
multi_steps_attn_metadata = [MagicMock(), MagicMock(), MagicMock()]
25332536

2537+
mock_ascend_config = MagicMock()
2538+
mock_ascend_config.enable_reduce_sample = True
25342539
with (
25352540
patch.object(llm_base_proposer, "lmhead_tp_enable", return_value=False),
2541+
patch.object(llm_base_proposer, "get_ascend_config", return_value=mock_ascend_config),
25362542
patch.object(llm_base_proposer, "get_forward_context", return_value=forward_context),
25372543
):
25382544
draft_token_ids = self.proposer._run_merged_draft(
@@ -2594,7 +2600,12 @@ def test_run_merged_draft_dflash_uses_first_pass_inputs_and_returns_early(self):
25942600
}
25952601
)
25962602

2597-
with patch.object(llm_base_proposer, "lmhead_tp_enable", return_value=False):
2603+
mock_ascend_config = MagicMock()
2604+
mock_ascend_config.enable_reduce_sample = False
2605+
with (
2606+
patch.object(llm_base_proposer, "lmhead_tp_enable", return_value=False),
2607+
patch.object(llm_base_proposer, "get_ascend_config", return_value=mock_ascend_config),
2608+
):
25982609
draft_token_ids = self.proposer._run_merged_draft(
25992610
num_input_tokens=12,
26002611
batch_size=2,
@@ -2644,8 +2655,11 @@ def test_run_merged_draft_mtp_mrope_graph_and_lmhead_tp_preparation(self):
26442655
forward_context.attn_metadata = None
26452656
multi_steps_attn_metadata = [MagicMock(), MagicMock(), MagicMock()]
26462657

2658+
mock_ascend_config = MagicMock()
2659+
mock_ascend_config.enable_reduce_sample = False
26472660
with (
26482661
patch.object(llm_base_proposer, "lmhead_tp_enable", return_value=True),
2662+
patch.object(llm_base_proposer, "get_ascend_config", return_value=mock_ascend_config),
26492663
patch.object(llm_base_proposer, "get_forward_context", return_value=forward_context),
26502664
):
26512665
draft_token_ids = self.proposer._run_merged_draft(
@@ -2700,6 +2714,8 @@ def test_run_merged_draft_early_return_conditions(self):
27002714
(1, False, torch.tensor([1, 3], dtype=torch.int64), (2, 1)),
27012715
(2, True, torch.tensor([0, 1, 2, 3], dtype=torch.int64), (2, 2)),
27022716
]
2717+
mock_ascend_config = MagicMock()
2718+
mock_ascend_config.enable_reduce_sample = False
27032719
for num_speculative_tokens, parallel_drafting, token_indices_to_sample, expected_shape in test_cases:
27042720
with self.subTest(num_speculative_tokens=num_speculative_tokens, parallel_drafting=parallel_drafting):
27052721
self.proposer.method = "eagle3"
@@ -2710,7 +2726,10 @@ def test_run_merged_draft_early_return_conditions(self):
27102726
self.proposer.input_ids[:4] = torch.tensor([279, 1196, 374, 8014], dtype=torch.int32)
27112727
self.proposer.positions[:4] = torch.tensor([17, 18, 19, 20], dtype=torch.int64)
27122728

2713-
with patch.object(llm_base_proposer, "lmhead_tp_enable", return_value=False):
2729+
with (
2730+
patch.object(llm_base_proposer, "lmhead_tp_enable", return_value=False),
2731+
patch.object(llm_base_proposer, "get_ascend_config", return_value=mock_ascend_config),
2732+
):
27142733
draft_token_ids = self.proposer._run_merged_draft(
27152734
num_input_tokens=4,
27162735
batch_size=2,

0 commit comments

Comments
 (0)