Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

100 changes: 67 additions & 33 deletions tests/e2e/pull_request/one_card/test_gumbel_sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
import torch
from vllm.v1.worker.gpu.spec_decode.dspark.speculator import DSparkSpeculator

from vllm_ascend.ops.triton.v2.sample.categorical_sample import categorical_sample
from vllm_ascend.utils import vllm_version_is
from vllm_ascend.worker.v2.sample.gumbel import apply_temperature
from vllm_ascend.worker.v2.sample.gumbel import gumbel_sample as _sample_for_version
from vllm_ascend.worker.v2.spec_decode.rejection_sampler_utils import rejection_sample

DEVICE = "npu"
Expand All @@ -30,8 +31,20 @@ def gumbel_sample(
*,
is_drafting: bool = False,
) -> torch.Tensor:
"""Run sampling assertions against the Ascend categorical implementation."""
return categorical_sample(
"""Run the existing target-sampling assertions through each lane's API."""
if vllm_version_is("0.28.0"):
return _sample_for_version(
logits,
expanded_idx_mapping,
temperature,
seed,
pos,
apply_temperature=apply_temperature,
logits_cache=logits_cache,
logits_cache_col=logits_cache_col,
is_drafting=is_drafting,
)
return _sample_for_version(
logits,
expanded_idx_mapping,
temperature,
Expand Down Expand Up @@ -174,6 +187,27 @@ def test_gumbel_sample_deterministic(self, num_tokens, num_reqs, vocab_size):

assert torch.equal(r1, r2), "gumbel_sample is non-deterministic with same seed"

def test_gumbel_sample_different_seeds(self):
"""Different seeds must (almost surely) produce different results."""
torch.manual_seed(8)
num_tokens, num_reqs, vocab_size = 16, 16, 32000
logits = torch.randn(num_tokens, vocab_size, dtype=torch.float32, device=DEVICE)
expanded_idx_mapping = torch.arange(num_tokens, dtype=torch.int32, device=DEVICE)
temperature = torch.ones(num_reqs, dtype=torch.float32, device=DEVICE) * 1.0
pos = torch.arange(num_tokens, dtype=torch.int32, device=DEVICE)

seed1 = torch.randint(0, 2**31, (num_reqs,), dtype=torch.int64, device=DEVICE)
seed2 = torch.randint(0, 2**31, (num_reqs,), dtype=torch.int64, device=DEVICE)
# Ensure seeds differ
seed2[0] = seed1[0] + 1

r1 = gumbel_sample(logits, expanded_idx_mapping, temperature, seed1, pos, apply_temperature=False)
r2 = gumbel_sample(logits, expanded_idx_mapping, temperature, seed2, pos, apply_temperature=False)
torch.npu.synchronize()

# With 16 tokens and vocab 32000 at temp=1.0, identical results are astronomically unlikely
assert not torch.equal(r1, r2), "Different seeds produced identical results"

@pytest.mark.parametrize(
"num_tokens,num_reqs,vocab_size",
[
Expand All @@ -200,44 +234,46 @@ def test_gumbel_sample_valid_token_ids(self, num_tokens, num_reqs, vocab_size):
)

def test_gumbel_sample_temperature_affects_distribution(self):
"""Higher temperature should make a peaked distribution less concentrated."""
"""Higher temperature should increase sampling entropy (less concentrated).

Strategy: create logits with a clear winner. At low temp the winner should
be sampled most often. At high temp other tokens get more probability.
"""
vocab_size = 100
num_trials = 256
logits_base = torch.zeros(1, vocab_size, dtype=torch.float32, device=DEVICE)
logits_base[0, 0] = 10.0 # strong signal at token 0

logits = torch.zeros(num_trials, vocab_size, dtype=torch.float32, device=DEVICE)
logits[:, 0] = 10.0
expanded_idx_mapping = torch.arange(num_trials, dtype=torch.int32, device=DEVICE)
seed = torch.arange(num_trials, dtype=torch.int64, device=DEVICE) * 1000 + 42
pos = torch.arange(num_trials, dtype=torch.int32, device=DEVICE)
expanded_idx_mapping = torch.zeros(1, dtype=torch.int32, device=DEVICE)

low_temp = torch.full((num_trials,), 0.1, dtype=torch.float32, device=DEVICE)
high_temp = torch.full((num_trials,), 5.0, dtype=torch.float32, device=DEVICE)
low_temp = torch.tensor([0.1], dtype=torch.float32, device=DEVICE)
high_temp = torch.tensor([5.0], dtype=torch.float32, device=DEVICE)

low_samples = gumbel_sample(
logits,
expanded_idx_mapping,
low_temp,
seed,
pos,
apply_temperature=True,
)
high_samples = gumbel_sample(
logits,
expanded_idx_mapping,
high_temp,
seed,
pos,
apply_temperature=True,
)
torch.npu.synchronize()
low_temp_winner_count = 0
high_temp_winner_count = 0

low_temp_winner_count = (low_samples == 0).sum().item()
high_temp_winner_count = (high_samples == 0).sum().item()
for i in range(num_trials):
seed = torch.tensor([i * 1000 + 42], dtype=torch.int64, device=DEVICE)
pos = torch.tensor([i], dtype=torch.int32, device=DEVICE)

s_low = gumbel_sample(
logits_base.clone(), expanded_idx_mapping, low_temp, seed, pos, apply_temperature=True
)
s_high = gumbel_sample(
logits_base.clone(), expanded_idx_mapping, high_temp, seed, pos, apply_temperature=True
)
if s_low.item() == 0:
low_temp_winner_count += 1
if s_high.item() == 0:
high_temp_winner_count += 1

torch.npu.synchronize()
# Low temp should pick the winner much more often than high temp
assert low_temp_winner_count > high_temp_winner_count, (
f"Low temp winner count ({low_temp_winner_count}) should be > "
f"high temp winner count ({high_temp_winner_count})"
)
# Low temp with such a strong signal should almost always pick token 0
assert low_temp_winner_count > num_trials * 0.9, (
f"Low temp winner count ({low_temp_winner_count}/{num_trials}) should be >90%"
)
Expand Down Expand Up @@ -595,11 +631,9 @@ def test_gumbel_sample_rejects_narrow_cache(self):
def test_dspark_uses_ascend_gumbel(self):
"""Exercise the inherited DSpark entry point with real NPU sampling."""
# Check the installed implementation, not this test module's API wrapper.
assert DSparkSpeculator._sample_logits.__globals__["gumbel_sample"] is categorical_sample
assert DSparkSpeculator._sample_logits.__globals__["gumbel_sample"] is _sample_for_version
speculator = DSparkSpeculator.__new__(DSparkSpeculator)
speculator._d2t_scatter_index = None
speculator.acceptance_estimator = None
speculator.draft_watermarker = None
speculator.temperature = torch.tensor([0.5, 1.5], device=DEVICE)
speculator.seeds = torch.tensor([3, 7], dtype=torch.int64, device=DEVICE)
speculator._step_cols = torch.arange(2, dtype=torch.int32, device=DEVICE)
Expand Down
121 changes: 0 additions & 121 deletions tests/ut/attention/test_attention_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
)
from vllm_ascend.attention.utils import (
AscendCommonAttentionMetadata,
PagedAttentionGraphParam,
cache_graph_workspace,
needs_layer_aware_fia_graph_replay,
using_paged_attention,
Expand Down Expand Up @@ -887,123 +886,3 @@ def test_forward_decode_only_swa_seq_len_mismatch(
mock_reshape_and_cache.assert_called_once()

assert output.shape == (10, 8, 64)

@patch("vllm_ascend.attention.attention_v1.torch.npu.stream")
@patch("vllm_ascend.attention.attention_v1.torch.npu.graph_task_update_begin")
@patch("vllm_ascend.attention.attention_v1.torch.npu.graph_task_update_end")
@patch("torch_npu.npu_fused_infer_attention_score")
@patch("vllm_ascend.attention.attention_v1.get_graph_params")
@patch("vllm_ascend.attention.attention_v1._EXTRA_CTX")
@patch("vllm_ascend.attention.attention_v1.using_paged_attention", return_value=False)
@patch("vllm_ascend.attention.attention_v1.needs_layer_aware_fia_graph_replay", return_value=False)
@patch("vllm_ascend.attention.attention_v1._ATTN_KEYS_BUFFER", new=[])
def test_update_graph_params(
self,
mock_needs_layer_aware_fia_graph_replay,
mock_using_paged_attention,
mock_EXTRA_CTX,
mock_get_graph_params,
mock_fia,
mock_graph_task_update_end,
mock_graph_task_update_begin,
mock_stream,
):
"""Test behavior when _ATTN_KEYS_BUFFER is [] after dummy_run."""

mock_EXTRA_CTX.sinks = False
mock_EXTRA_CTX.is_draft_model = False

param: list[MagicMock | None] = [MagicMock()] * 22
param[16] = None # sliding_window
param[17] = None # c8_k_aq_scale
param[21] = None # layer_name

mock_get_graph_params.return_value.attn_params = {1: [tuple(param)] * 3}
mock_get_graph_params.return_value.handles = {1: [MagicMock()] * 3}
mock_get_graph_params.return_value.events = {1: [MagicMock()] * 3}

attn_metadata_keys = [
"model.layers.10.self_attn.attn",
"model.layers.2.self_attn.attn",
"model.layers.5.self_attn.attn",
]
forward_context = MagicMock()
forward_context.attn_metadata = {key: MagicMock() for key in attn_metadata_keys}
# breakpoint()
self.impl.update_graph_params(self.mock_stream, forward_context, 1, self.mock_vllm_config)

expected = [
"model.layers.2.self_attn.attn",
"model.layers.5.self_attn.attn",
"model.layers.10.self_attn.attn",
]
self.assertEqual(attn_module._ATTN_KEYS_BUFFER, expected)
self.assertEqual(mock_fia.out.call_count, 3)

@patch("vllm_ascend.attention.attention_v1.torch.npu.stream")
@patch("vllm_ascend.attention.attention_v1.torch.npu.graph_task_update_begin")
@patch("vllm_ascend.attention.attention_v1.torch.npu.graph_task_update_end")
@patch("vllm_ascend.attention.attention_v1.torch_npu._npu_paged_attention")
@patch("vllm_ascend.attention.attention_v1.torch_npu._npu_paged_attention_get_workspace", return_value=MagicMock())
@patch("vllm_ascend.attention.attention_v1.get_graph_params")
@patch("vllm_ascend.attention.attention_v1._EXTRA_CTX")
@patch("vllm_ascend.attention.attention_v1.using_paged_attention", return_value=True)
@patch("vllm_ascend.attention.attention_v1.needs_layer_aware_fia_graph_replay", return_value=False)
@patch("vllm_ascend.attention.attention_v1._ATTN_KEYS_BUFFER", new=[])
def test_update_graph_params_handles_captured_paged_attention_params(
self,
mock_needs_layer_aware_fia_graph_replay,
mock_using_paged_attention,
mock_EXTRA_CTX,
mock_get_graph_params,
mock_get_workspace,
mock_paged_attention,
mock_graph_task_update_end,
mock_graph_task_update_begin,
mock_stream,
):
mock_EXTRA_CTX.sinks = False
mock_EXTRA_CTX.is_draft_model = False

query = MagicMock()
key_cache = MagicMock()
value_cache = MagicMock()
block_table = MagicMock()
output = MagicMock()
captured_seq_lens = MagicMock()
current_seq_lens = MagicMock()
pa_param = PagedAttentionGraphParam(
(
query,
key_cache,
value_cache,
8,
8,
1.0,
block_table,
captured_seq_lens,
output,
),
"model.layers.0.self_attn.attn",
)

mock_get_graph_params.return_value.attn_params = {1: [pa_param]}
mock_get_graph_params.return_value.handles = {1: [MagicMock()]}
mock_get_graph_params.return_value.events = {1: [MagicMock()]}

forward_context = MagicMock()
forward_context.attn_metadata = {
"model.layers.0.self_attn.attn": MagicMock(
seq_lens=current_seq_lens,
block_tables=block_table,
seq_lens_list=[10],
),
}

self.impl.update_graph_params(self.mock_stream, forward_context, 1, self.mock_vllm_config)

mock_get_workspace.assert_called_once()
mock_paged_attention.assert_called_once()
self.assertEqual(mock_paged_attention.call_args.kwargs["context_lens"], current_seq_lens)
mock_graph_task_update_begin.assert_called_once()
mock_graph_task_update_end.assert_called_once()
Loading
Loading