[Feat] Unified Synthetic Acceptance Rate for V1 and V2 (#40662)

Signed-off-by: Benjamin Chislett <bchislett@nvidia.com>
Signed-off-by: Benjamin Chislett <chislett.ben@gmail.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
This commit is contained in:
Benjamin Chislett
2026-04-24 00:48:08 +00:00
committed by GitHub
co-authored by gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
parent fe85a92e86
commit 626daa2076
10 changed files with 340 additions and 137 deletions
@@ -1310,6 +1310,54 @@ def test_dflash_acceptance_rates(dflash_config):
cleanup_dist_env_and_memory()
@single_gpu_only
def test_synthetic_acceptance_rate():
"""Verify that synthetic rejection sampling produces an acceptance
length close to the requested mean acceptance length."""
num_spec_tokens = 3
expected_acceptance_len = 1.875
tolerance = 0.15
spec_llm = LLM(
model="meta-llama/Llama-3.2-1B-Instruct",
trust_remote_code=True,
speculative_config={
"method": "eagle3",
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
"num_speculative_tokens": num_spec_tokens,
"max_model_len": 2048,
"rejection_sample_method": "synthetic",
"synthetic_acceptance_length": expected_acceptance_len,
},
max_model_len=2048,
enforce_eager=True,
disable_log_stats=False,
)
test_prompts = get_test_prompts(mm_enabled=False, num_prompts=50)
spec_llm.chat(
test_prompts,
SamplingParams(temperature=0, max_tokens=64, ignore_eos=True),
)
metrics = spec_llm.get_metrics()
acceptance_len = compute_acceptance_len(metrics)
print(
f"Synthetic acceptance length: {acceptance_len:.3f}"
f" (expected={expected_acceptance_len:.3f},"
f" tolerance=±{tolerance})"
)
assert abs(acceptance_len - expected_acceptance_len) <= tolerance, (
f"Synthetic acceptance length {acceptance_len:.3f} is not within"
f" ±{tolerance} of expected {expected_acceptance_len:.3f}"
)
del spec_llm
torch.accelerator.empty_cache()
cleanup_dist_env_and_memory()
def test_dflash_correctness(dflash_config):
"""
E2E test for DFlash (block diffusion) speculative decoding.
+61
View File
@@ -933,3 +933,64 @@ def test_sample_recovered_tokens(
device=DEVICE_TYPE,
)
assert torch.equal(recovered_token_ids, ref_recovered_token_ids)
########################### Tests for Synthetic Rejection Sampling #########
def _make_synthetic_sampler(rates: list[float]) -> RejectionSampler:
mock_sampler = Mock(spec=Sampler)
mock_sampler.logprobs_mode = "raw_logprobs"
spec_config = Mock()
spec_config.rejection_sample_method = "synthetic"
spec_config.synthetic_acceptance_rates = rates
return RejectionSampler(mock_sampler, spec_config, torch.device(DEVICE_TYPE))
def _make_sampling_metadata(all_greedy: bool) -> SamplingMetadata:
temperature = None if all_greedy else torch.tensor([1.0, 1.0], device=DEVICE_TYPE)
return create_sampling_metadata(all_greedy=all_greedy, temperature=temperature)
@pytest.mark.parametrize("all_greedy", [True, False])
def test_synthetic_all_accepted(all_greedy: bool):
"""With all rates=1.0, every draft token is accepted."""
sampler = _make_synthetic_sampler([1.0, 1.0])
spec_tokens = [[1, 2], [3]]
output_tokens = [[10, 20, 50], [30, 40]]
metadata = _make_sampling_metadata(all_greedy)
logits = create_logits_tensor(output_tokens)
bonus = torch.tensor([50, 40], device=DEVICE_TYPE)
spec_decode_metadata = create_spec_decode_metadata(spec_tokens, logits)
mock_sampler_output(sampler, bonus)
output = sampler(spec_decode_metadata, None, logits, metadata)
expected = torch.tensor(
[[1, 2, 50], [3, 40, PLACEHOLDER_TOKEN_ID]],
dtype=torch.int,
device=DEVICE_TYPE,
)
assert torch.equal(output.sampled_token_ids, expected)
@pytest.mark.parametrize("all_greedy", [True, False])
def test_synthetic_all_rejected(all_greedy: bool):
"""With all rates=0.0, the first token is always rejected."""
sampler = _make_synthetic_sampler([0.0, 0.0])
spec_tokens = [[1, 2], [3]]
output_tokens = [[10, 20, 50], [30, 40]]
metadata = _make_sampling_metadata(all_greedy)
logits = create_logits_tensor(output_tokens)
bonus = torch.tensor([50, 40], device=DEVICE_TYPE)
spec_decode_metadata = create_spec_decode_metadata(spec_tokens, logits)
mock_sampler_output(sampler, bonus)
output = sampler(spec_decode_metadata, None, logits, metadata)
result = output.sampled_token_ids
# Exactly one token emitted per sequence (the rejection fallback),
# followed by placeholders.
for row in result:
assert row[0] != PLACEHOLDER_TOKEN_ID
assert (row[1:] == PLACEHOLDER_TOKEN_ID).all()
@@ -2,33 +2,48 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from vllm.v1.worker.gpu.spec_decode.synthetic_rejection_sampler_utils import (
compute_synthetic_rejection_sampler_params,
from vllm.config.speculative import SpeculativeConfig
from vllm.v1.spec_decode.utils import unconditional_to_conditional_rates
def test_unconditional_to_conditional_rates_basic():
# c_0 = p_0; c_i = p_i / p_{i-1}
assert unconditional_to_conditional_rates([0.9, 0.5, 0.2]) == pytest.approx(
[0.9, 0.5 / 0.9, 0.2 / 0.5]
)
def test_unconditional_to_conditional_rates_handles_zero():
# After a zero, subsequent conditional rates are clamped to 0 (the chain
# has already terminated in the kernel, so these values are unused).
assert unconditional_to_conditional_rates([1.0, 0.6, 0.0, 0.0]) == pytest.approx(
[1.0, 0.6, 0.0, 0.0]
)
def test_unconditional_to_conditional_rates_all_ones():
assert unconditional_to_conditional_rates([1.0, 1.0, 1.0]) == pytest.approx(
[1.0, 1.0, 1.0]
)
@pytest.mark.parametrize(
"length,n,expected",
[
(2.6, 3, [1.0, 0.6, 0.0]),
(1.0, 3, [0.0, 0.0, 0.0]),
(4.0, 3, [1.0, 1.0, 1.0]),
(2.0, 3, [1.0, 0.0, 0.0]),
(3.5, 4, [1.0, 1.0, 0.5, 0.0]),
],
)
NUM_SPECULATIVE_STEPS = [1, 2, 3, 4, 5, 7, 10]
ACCEPTANCE_RATES = [i / 100 for i in range(0, 100)]
def test_acceptance_length_to_rates(length, n, expected):
assert SpeculativeConfig._acceptance_length_to_rates(length, n) == pytest.approx(
expected
)
@pytest.mark.parametrize("num_speculative_steps", NUM_SPECULATIVE_STEPS)
def test_compute_synthetic_rejection_sampler_params(num_speculative_steps: int):
"""Test that the base acceptance rate and decay factor generated for
synthetic rejection sampling have a mean joint acceptance probability
that matches the desired acceptance rate."""
tol = 1e-9
for desired_acceptance_rate in ACCEPTANCE_RATES:
base_rate, decay_factor = compute_synthetic_rejection_sampler_params(
desired_acceptance_rate, num_speculative_steps, tol=tol
)
# Compute the mean of joint acceptance probabilities across
# all speculative positions.
joint_prob = 1.0
mean_joint = 0.0
for i in range(num_speculative_steps):
joint_prob *= base_rate * decay_factor**i
mean_joint += joint_prob
mean_joint /= num_speculative_steps
assert abs(desired_acceptance_rate - mean_joint) < 10 * tol
assert base_rate <= 1.0
def test_resolve_length_produces_minvariance_schedule():
assert SpeculativeConfig._resolve_synthetic_acceptance_rates(
3, None, 2.6
) == pytest.approx([1.0, 0.6, 0.0])