Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 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
35 changes: 33 additions & 2 deletions docs/features/speculative_decoding/dynamic_speculative_decoding.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ SD methods need to verify K tokens for each sequence during decoding. As BS incr

## `--speculative-config` schema

To use Dynamic SD, add `num_speculative_tokens_per_batch_size` to the config of an SD method which is a list of list. Here, an entry is `[start_bs, end_bs, optimal_K]` which means when the concurrency is within range `[start_bs, end_bs]` then `optimal_K` number of draft tokens are used. For e.g.,
To use Dynamic SD, add `num_speculative_tokens_per_batch_size` to the config of an SD method which is a list of list. Here, an entry is `[start_bs, end_bs, optimal_K]` which means when the concurrency is within range `[start_bs, end_bs]` then `optimal_K` number of draft tokens are used.

Every `optimal_K` must be less than or equal to `num_speculative_tokens`, which defines the maximum draft window.

```bash
--speculative-config '{
Expand All @@ -32,8 +34,37 @@ implies that:
* K=1 will be used when the concurrency is in range [65, 128]
* K=0 will be used when the concurrency is in range [129, 512], i.e., no draft tokens will be produced.

## Adaptive verification

Adaptive verification is supported with the Model Runner V2 DSpark implementation. Enable it by setting `adaptive_verification` to `true` in the speculative config.

In this mode, `num_speculative_tokens` is the maximum per-request draft length. The drafter returns `num_speculative_tokens` tokens per request, and the scheduler reserves KV-cache capacity for that full window. For `N` scheduled requests, Dynamic SD maps this through the `num_speculative_tokens_per_batch_size` table to calculate the total verification budget of `N * optimal_K`. The worker distributes that budget across the draft prefixes using the DSpark confidence head, so individual requests can verify different numbers of draft tokens while the batch total remains fixed. Only the allocated draft positions, plus one bonus position per request, run through the target model.

## Online Examples

### Adaptive Dynamic SD with DSpark

```bash
vllm serve Qwen/Qwen3-4B-FP8 \
--trust-remote-code \
--max-model-len 4096 \
--attention-backend FLASH_ATTN \
--speculative-config '{
"method": "dspark",
"model": "deepseek-ai/dspark_qwen3_4b_block7",
"num_speculative_tokens": 11,
"num_speculative_tokens_per_batch_size": [
[1, 32, 7],
[33, 128, 5],
[129, 512, 3]
],
"adaptive_verification": true,
"draft_sample_method": "probabilistic"
}'
```

Here the drafter produces 11 draft tokens for each request, but uses a different total verification budget depending on the batch size.

### Dynamic SD Eagle Drafter

```bash
Expand All @@ -57,7 +88,7 @@ VLLM_USE_V2_MODEL_RUNNER=0 vllm serve meta-llama/Llama-3.1-8B-Instruct \
--speculative-config '{
"method": "eagle3",
"model": "yuhuili/EAGLE3-LLaMA3.1-Instruct-8B",
"num_speculative_tokens": 3,
"num_speculative_tokens": 5,
"num_speculative_tokens_per_batch_size": [
[1, 16, 5],
[17, 32, 4],
Expand Down
29 changes: 29 additions & 0 deletions tests/kernels/attention/test_attention_selector.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

from types import SimpleNamespace
from unittest.mock import patch

import pytest
Expand All @@ -14,6 +15,7 @@
)
from vllm.platforms import current_platform
from vllm.platforms.cpu import CpuPlatform
from vllm.v1.attention.backend import AttentionCGSupport

if current_platform.is_cuda():
from vllm.platforms.cuda import CudaPlatform
Expand All @@ -35,6 +37,33 @@ def clear_cache():
_cached_get_attn_backend.cache_clear()


def test_adaptive_verification_requires_varlen_for_dspark_drafter(monkeypatch):
from vllm.compilation.backends import set_model_tag
from vllm.v1.attention import selector

vllm_config = SimpleNamespace(
cache_config=None,
kv_transfer_config=None,
speculative_config=SimpleNamespace(adaptive_verification=True),
attention_config=SimpleNamespace(backend=None, use_non_causal=False),
)
monkeypatch.setattr("vllm.config.get_current_vllm_config", lambda: vllm_config)

selector_configs = []

def capture_selector_config(*, backend, attn_selector_config, num_heads):
selector_configs.append(attn_selector_config)

monkeypatch.setattr(selector, "_cached_get_attn_backend", capture_selector_config)

selector.get_attn_backend(16, torch.float16, None)
with set_model_tag("dspark_head"):
selector.get_attn_backend(16, torch.float16, None)

assert selector_configs[0].required_cg_support == AttentionCGSupport.VARLEN_BATCH
assert selector_configs[1].required_cg_support == AttentionCGSupport.VARLEN_BATCH


# Define MLA and non-MLA backends separately
DEVICE_MLA_BACKENDS = {
"cuda": [
Expand Down
86 changes: 79 additions & 7 deletions tests/v1/core/test_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1040,21 +1040,87 @@ def test_reset_connector_cache_no_connector_is_no_op_success():

# Note - these test cases mirror some of those in test_rejection_sampler.py
@pytest.mark.parametrize(
"spec_tokens,output_tokens,expected",
(
"spec_tokens,output_tokens,actual_num_draft_tokens,"
"invalid_spec_tokens_per_req,missing_req_indices,expected"
),
[
([[1, 2, 3]], [[1, 2, 3, 4]], (1, 3, 3, [1, 1, 1])), # perfect match
([[1, 2, 3]], [[1, 5]], (1, 3, 1, [1, 0, 0])), # early mismatch
([[1, 2], [3]], [[1, 2, 5], [3, 4]], (2, 3, 3, [2, 1])), # multiple sequences
([[1]], [[1, 2]], (1, 1, 1, [1])), # single token sequence
([[]], [[5]], (0, 0, 0, [0])), # empty sequence
(
[[1, 2, 3]],
[[1, 2, 3, 4]],
None,
None,
None,
(1, 3, 3, [1, 1, 1]),
), # perfect match
(
[[1, 2, 3]],
[[1, 5]],
None,
None,
None,
(1, 3, 1, [1, 0, 0]),
), # early mismatch
(
[[1, 2], [3]],
[[1, 2, 5], [3, 4]],
None,
None,
None,
(2, 3, 3, [2, 1]),
), # multiple sequences
([[1]], [[1, 2]], None, None, None, (1, 1, 1, [1])), # single token
([[]], [[5]], None, None, None, (0, 0, 0, [0])), # empty sequence
(
[[1, 2, 3], [4, 5, 6]],
[[1, 2, 7], [4, 8]],
None,
None,
None,
(2, 6, 3, [2, 1, 0]),
), # multiple mismatches
(
[list(range(7)), list(range(7)), list(range(7))],
[[10], [10], [10]],
[7, 0, 6],
None,
None,
(3, 13, 0, [0] * 7),
), # adaptive allocation including zero
(
[[-1] * 7] * 3,
[[10], [10], [10]],
[7, 0, 6],
None,
None,
(3, 13, 0, [0] * 7),
), # GPU-only adaptive draft placeholders
(
[[0, 1, 2, 3, 4, -1, -1]] * 3,
[[10], [10], [10]],
[3, 6, 0],
[2, 2, 2],
None,
(3, 8, 0, [0] * 7),
), # adaptive allocation with invalid suffixes
(
[[-1] * 7] * 3,
[[10], [10], [10]],
[1, 7, 7],
None,
[0],
(3, 15, 0, [0] * 7),
), # completed async request still counts
],
)
def test_schedule_spec_decoding_stats(spec_tokens, output_tokens, expected):
def test_schedule_spec_decoding_stats(
spec_tokens,
output_tokens,
actual_num_draft_tokens,
invalid_spec_tokens_per_req,
missing_req_indices,
expected,
):
"""Test scheduling behavior with speculative decoding.

This test verifies that:
Expand Down Expand Up @@ -1122,6 +1188,8 @@ def test_schedule_spec_decoding_stats(spec_tokens, output_tokens, expected):
)
else:
assert req_id not in output.scheduled_spec_decode_tokens
if invalid_spec_tokens_per_req is not None:
output.num_invalid_spec_tokens = dict(zip(req_ids, invalid_spec_tokens_per_req))

model_runner_output = ModelRunnerOutput(
req_ids=req_ids,
Expand All @@ -1130,7 +1198,11 @@ def test_schedule_spec_decoding_stats(spec_tokens, output_tokens, expected):
logprobs=None,
prompt_logprobs_dict={},
pooler_output=[],
num_draft_tokens=actual_num_draft_tokens,
)
if missing_req_indices is not None:
for req_index in missing_req_indices:
del scheduler.requests[req_ids[req_index]]
engine_core_outputs = scheduler.update_from_output(output, model_runner_output)

scheduler_stats = (
Expand Down
54 changes: 52 additions & 2 deletions tests/v1/e2e/spec_decode/test_spec_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -1439,6 +1439,21 @@ def dspark_config():
)


@pytest.fixture
def dspark_adaptive_config(dspark_config):
speculative_config = dspark_config["speculative_config"] | {
"num_speculative_tokens": 7,
"num_speculative_tokens_per_batch_size": [(1, 1024, 5)],
"adaptive_verification": True,
}
speculative_config.pop("attention_backend")
return dspark_config | {
"attention_backend": "FLASH_ATTN",
"speculative_config": speculative_config,
"max_num_seqs": 1024,
}


@single_gpu_only
@large_gpu_mark(min_gb=24)
def test_dspark_correctness_and_acceptance_rate(dspark_config):
Expand Down Expand Up @@ -1471,8 +1486,43 @@ def test_dspark_correctness_and_acceptance_rate(dspark_config):
f"gsm8k_accuracy={gsm8k_accuracy:.3f}"
)

assert acceptance_rate >= 0.428 * 0.9
assert acceptance_len >= 3.994 * 0.9
assert acceptance_rate >= 0.428 * 0.95
assert acceptance_len >= 3.994 * 0.95
assert gsm8k_accuracy >= 0.801 * 0.9

del spec_llm
torch.accelerator.empty_cache()
cleanup_dist_env_and_memory()


@single_gpu_only
@large_gpu_mark(min_gb=24)
def test_dspark_adaptive_correctness_and_acceptance_length(dspark_adaptive_config):
"""Check adaptive verification quality with a larger draft window.
The drafter produces up to 7 candidates per request, while the target verifies an
average budget of 5 draft tokens per request.
"""
spec_llm = LLM(**dspark_adaptive_config)

results = evaluate_gsm8k_offline(spec_llm, temperature=1.0)
gsm8k_accuracy = results["accuracy"]
metrics = spec_llm.get_metrics()
acceptance_len = compute_acceptance_len(metrics)

# Check the actual low-level stats to ensure we're not over- or under-allocating.
name2metric = {metric.name: metric for metric in metrics}
num_drafts = name2metric["vllm:spec_decode_num_drafts"].value
num_draft_tokens = name2metric["vllm:spec_decode_num_draft_tokens"].value

print(
f"Adaptive DSpark acceptance_len={acceptance_len:.2f}, "
f"gsm8k_accuracy={gsm8k_accuracy:.3f}"
)

assert num_drafts > 0
assert num_draft_tokens < num_drafts * 7
assert 0.99 * (num_drafts * 5) <= num_draft_tokens <= 1.01 * (num_drafts * 5)
assert acceptance_len >= 3.62 * 0.95 # Measured on non-adaptive K=5 baseline
assert gsm8k_accuracy >= 0.801 * 0.9

del spec_llm
Expand Down
Loading
Loading